xrpl 4.3.0-smartescrow.3 → 4.4.0-smartescrow.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 (476) hide show
  1. package/README.md +2 -2
  2. package/build/xrpl-latest-min.js +3 -0
  3. package/build/xrpl-latest-min.js.map +1 -0
  4. package/build/xrpl-latest.js +1457 -1505
  5. package/build/xrpl-latest.js.map +1 -1
  6. package/dist/npm/Wallet/batchSigner.d.ts +8 -0
  7. package/dist/npm/Wallet/batchSigner.d.ts.map +1 -0
  8. package/dist/npm/Wallet/batchSigner.js +111 -0
  9. package/dist/npm/Wallet/batchSigner.js.map +1 -0
  10. package/dist/npm/Wallet/defaultFaucets.d.ts +3 -2
  11. package/dist/npm/Wallet/defaultFaucets.d.ts.map +1 -1
  12. package/dist/npm/Wallet/defaultFaucets.js +16 -15
  13. package/dist/npm/Wallet/defaultFaucets.js.map +1 -1
  14. package/dist/npm/Wallet/fundWallet.d.ts.map +1 -1
  15. package/dist/npm/Wallet/fundWallet.js +8 -16
  16. package/dist/npm/Wallet/fundWallet.js.map +1 -1
  17. package/dist/npm/Wallet/index.d.ts.map +1 -1
  18. package/dist/npm/Wallet/index.js +10 -4
  19. package/dist/npm/Wallet/index.js.map +1 -1
  20. package/dist/npm/Wallet/signer.d.ts.map +1 -1
  21. package/dist/npm/Wallet/signer.js +4 -20
  22. package/dist/npm/Wallet/signer.js.map +1 -1
  23. package/dist/npm/Wallet/utils.d.ts +9 -0
  24. package/dist/npm/Wallet/utils.d.ts.map +1 -0
  25. package/dist/npm/Wallet/utils.js +28 -0
  26. package/dist/npm/Wallet/utils.js.map +1 -0
  27. package/dist/npm/client/RequestManager.d.ts.map +1 -1
  28. package/dist/npm/client/RequestManager.js +3 -3
  29. package/dist/npm/client/RequestManager.js.map +1 -1
  30. package/dist/npm/client/connection.d.ts.map +1 -1
  31. package/dist/npm/client/connection.js.map +1 -1
  32. package/dist/npm/client/index.d.ts +3 -3
  33. package/dist/npm/client/index.d.ts.map +1 -1
  34. package/dist/npm/client/index.js +14 -14
  35. package/dist/npm/client/index.js.map +1 -1
  36. package/dist/npm/client/partialPayment.d.ts.map +1 -1
  37. package/dist/npm/client/partialPayment.js +2 -2
  38. package/dist/npm/client/partialPayment.js.map +1 -1
  39. package/dist/npm/models/common/index.d.ts +1 -0
  40. package/dist/npm/models/common/index.d.ts.map +1 -1
  41. package/dist/npm/models/ledger/AccountRoot.d.ts +1 -1
  42. package/dist/npm/models/ledger/AccountRoot.d.ts.map +1 -1
  43. package/dist/npm/models/ledger/Credential.d.ts +2 -2
  44. package/dist/npm/models/ledger/Credential.d.ts.map +1 -1
  45. package/dist/npm/models/ledger/LedgerEntry.d.ts +3 -2
  46. package/dist/npm/models/ledger/LedgerEntry.d.ts.map +1 -1
  47. package/dist/npm/models/ledger/Vault.d.ts +21 -0
  48. package/dist/npm/models/ledger/Vault.d.ts.map +1 -0
  49. package/dist/npm/models/ledger/Vault.js +3 -0
  50. package/dist/npm/models/ledger/Vault.js.map +1 -0
  51. package/dist/npm/models/ledger/XChainOwnedClaimID.d.ts +1 -2
  52. package/dist/npm/models/ledger/XChainOwnedClaimID.d.ts.map +1 -1
  53. package/dist/npm/models/ledger/index.d.ts +2 -1
  54. package/dist/npm/models/ledger/index.d.ts.map +1 -1
  55. package/dist/npm/models/ledger/index.js.map +1 -1
  56. package/dist/npm/models/methods/baseMethod.d.ts +1 -0
  57. package/dist/npm/models/methods/baseMethod.d.ts.map +1 -1
  58. package/dist/npm/models/methods/index.d.ts +5 -4
  59. package/dist/npm/models/methods/index.d.ts.map +1 -1
  60. package/dist/npm/models/methods/vaultInfo.d.ts +46 -0
  61. package/dist/npm/models/methods/vaultInfo.d.ts.map +1 -0
  62. package/dist/npm/models/methods/vaultInfo.js +3 -0
  63. package/dist/npm/models/methods/vaultInfo.js.map +1 -0
  64. package/dist/npm/models/transactions/AMMBid.d.ts.map +1 -1
  65. package/dist/npm/models/transactions/AMMBid.js +7 -5
  66. package/dist/npm/models/transactions/AMMBid.js.map +1 -1
  67. package/dist/npm/models/transactions/AMMClawback.d.ts +2 -2
  68. package/dist/npm/models/transactions/AMMClawback.d.ts.map +1 -1
  69. package/dist/npm/models/transactions/AMMClawback.js +5 -6
  70. package/dist/npm/models/transactions/AMMClawback.js.map +1 -1
  71. package/dist/npm/models/transactions/AMMDelete.d.ts.map +1 -1
  72. package/dist/npm/models/transactions/AMMDelete.js +2 -2
  73. package/dist/npm/models/transactions/AMMDelete.js.map +1 -1
  74. package/dist/npm/models/transactions/AMMDeposit.d.ts +2 -2
  75. package/dist/npm/models/transactions/AMMDeposit.d.ts.map +1 -1
  76. package/dist/npm/models/transactions/AMMDeposit.js +3 -3
  77. package/dist/npm/models/transactions/AMMDeposit.js.map +1 -1
  78. package/dist/npm/models/transactions/AMMVote.d.ts.map +1 -1
  79. package/dist/npm/models/transactions/AMMVote.js +2 -2
  80. package/dist/npm/models/transactions/AMMVote.js.map +1 -1
  81. package/dist/npm/models/transactions/AMMWithdraw.d.ts +2 -2
  82. package/dist/npm/models/transactions/AMMWithdraw.d.ts.map +1 -1
  83. package/dist/npm/models/transactions/AMMWithdraw.js +3 -3
  84. package/dist/npm/models/transactions/AMMWithdraw.js.map +1 -1
  85. package/dist/npm/models/transactions/MPTokenAuthorize.d.ts +2 -2
  86. package/dist/npm/models/transactions/MPTokenAuthorize.d.ts.map +1 -1
  87. package/dist/npm/models/transactions/MPTokenIssuanceCreate.d.ts +2 -2
  88. package/dist/npm/models/transactions/MPTokenIssuanceCreate.d.ts.map +1 -1
  89. package/dist/npm/models/transactions/MPTokenIssuanceCreate.js +3 -3
  90. package/dist/npm/models/transactions/MPTokenIssuanceCreate.js.map +1 -1
  91. package/dist/npm/models/transactions/MPTokenIssuanceSet.d.ts +2 -2
  92. package/dist/npm/models/transactions/MPTokenIssuanceSet.d.ts.map +1 -1
  93. package/dist/npm/models/transactions/MPTokenIssuanceSet.js +4 -4
  94. package/dist/npm/models/transactions/MPTokenIssuanceSet.js.map +1 -1
  95. package/dist/npm/models/transactions/NFTokenCancelOffer.d.ts.map +1 -1
  96. package/dist/npm/models/transactions/NFTokenCancelOffer.js +1 -1
  97. package/dist/npm/models/transactions/NFTokenCancelOffer.js.map +1 -1
  98. package/dist/npm/models/transactions/NFTokenCreateOffer.d.ts +2 -2
  99. package/dist/npm/models/transactions/NFTokenCreateOffer.d.ts.map +1 -1
  100. package/dist/npm/models/transactions/NFTokenCreateOffer.js +6 -2
  101. package/dist/npm/models/transactions/NFTokenCreateOffer.js.map +1 -1
  102. package/dist/npm/models/transactions/NFTokenMint.d.ts +2 -2
  103. package/dist/npm/models/transactions/NFTokenMint.d.ts.map +1 -1
  104. package/dist/npm/models/transactions/XChainAddAccountCreateAttestation.js.map +1 -1
  105. package/dist/npm/models/transactions/XChainAddClaimAttestation.js.map +1 -1
  106. package/dist/npm/models/transactions/XChainClaim.js.map +1 -1
  107. package/dist/npm/models/transactions/XChainCommit.js.map +1 -1
  108. package/dist/npm/models/transactions/XChainModifyBridge.d.ts +2 -2
  109. package/dist/npm/models/transactions/XChainModifyBridge.d.ts.map +1 -1
  110. package/dist/npm/models/transactions/accountDelete.d.ts.map +1 -1
  111. package/dist/npm/models/transactions/accountDelete.js.map +1 -1
  112. package/dist/npm/models/transactions/accountSet.d.ts +2 -2
  113. package/dist/npm/models/transactions/accountSet.d.ts.map +1 -1
  114. package/dist/npm/models/transactions/accountSet.js.map +1 -1
  115. package/dist/npm/models/transactions/batch.d.ts +39 -0
  116. package/dist/npm/models/transactions/batch.d.ts.map +1 -0
  117. package/dist/npm/models/transactions/batch.js +64 -0
  118. package/dist/npm/models/transactions/batch.js.map +1 -0
  119. package/dist/npm/models/transactions/checkCreate.d.ts.map +1 -1
  120. package/dist/npm/models/transactions/checkCreate.js +1 -2
  121. package/dist/npm/models/transactions/checkCreate.js.map +1 -1
  122. package/dist/npm/models/transactions/clawback.d.ts +2 -2
  123. package/dist/npm/models/transactions/clawback.d.ts.map +1 -1
  124. package/dist/npm/models/transactions/clawback.js +4 -6
  125. package/dist/npm/models/transactions/clawback.js.map +1 -1
  126. package/dist/npm/models/transactions/common.d.ts +30 -9
  127. package/dist/npm/models/transactions/common.d.ts.map +1 -1
  128. package/dist/npm/models/transactions/common.js +74 -36
  129. package/dist/npm/models/transactions/common.js.map +1 -1
  130. package/dist/npm/models/transactions/delegateSet.d.ts.map +1 -1
  131. package/dist/npm/models/transactions/delegateSet.js +1 -0
  132. package/dist/npm/models/transactions/delegateSet.js.map +1 -1
  133. package/dist/npm/models/transactions/depositPreauth.d.ts.map +1 -1
  134. package/dist/npm/models/transactions/depositPreauth.js.map +1 -1
  135. package/dist/npm/models/transactions/escrowFinish.d.ts.map +1 -1
  136. package/dist/npm/models/transactions/escrowFinish.js.map +1 -1
  137. package/dist/npm/models/transactions/index.d.ts +9 -2
  138. package/dist/npm/models/transactions/index.d.ts.map +1 -1
  139. package/dist/npm/models/transactions/index.js +4 -1
  140. package/dist/npm/models/transactions/index.js.map +1 -1
  141. package/dist/npm/models/transactions/metadata.d.ts +1 -0
  142. package/dist/npm/models/transactions/metadata.d.ts.map +1 -1
  143. package/dist/npm/models/transactions/offerCreate.d.ts +2 -2
  144. package/dist/npm/models/transactions/offerCreate.d.ts.map +1 -1
  145. package/dist/npm/models/transactions/oracleSet.d.ts.map +1 -1
  146. package/dist/npm/models/transactions/oracleSet.js +22 -21
  147. package/dist/npm/models/transactions/oracleSet.js.map +1 -1
  148. package/dist/npm/models/transactions/payment.d.ts +3 -2
  149. package/dist/npm/models/transactions/payment.d.ts.map +1 -1
  150. package/dist/npm/models/transactions/payment.js +9 -4
  151. package/dist/npm/models/transactions/payment.js.map +1 -1
  152. package/dist/npm/models/transactions/paymentChannelClaim.d.ts +2 -2
  153. package/dist/npm/models/transactions/paymentChannelClaim.d.ts.map +1 -1
  154. package/dist/npm/models/transactions/paymentChannelClaim.js.map +1 -1
  155. package/dist/npm/models/transactions/permissionedDomainSet.d.ts.map +1 -1
  156. package/dist/npm/models/transactions/permissionedDomainSet.js +1 -1
  157. package/dist/npm/models/transactions/permissionedDomainSet.js.map +1 -1
  158. package/dist/npm/models/transactions/signerListSet.d.ts.map +1 -1
  159. package/dist/npm/models/transactions/signerListSet.js +10 -16
  160. package/dist/npm/models/transactions/signerListSet.js.map +1 -1
  161. package/dist/npm/models/transactions/transaction.d.ts +8 -1
  162. package/dist/npm/models/transactions/transaction.d.ts.map +1 -1
  163. package/dist/npm/models/transactions/transaction.js +35 -35
  164. package/dist/npm/models/transactions/transaction.js.map +1 -1
  165. package/dist/npm/models/transactions/trustSet.d.ts +2 -2
  166. package/dist/npm/models/transactions/trustSet.d.ts.map +1 -1
  167. package/dist/npm/models/transactions/vaultClawback.d.ts +10 -0
  168. package/dist/npm/models/transactions/vaultClawback.d.ts.map +1 -0
  169. package/dist/npm/models/transactions/vaultClawback.js +12 -0
  170. package/dist/npm/models/transactions/vaultClawback.js.map +1 -0
  171. package/dist/npm/models/transactions/vaultCreate.d.ts +24 -0
  172. package/dist/npm/models/transactions/vaultCreate.d.ts.map +1 -0
  173. package/dist/npm/models/transactions/vaultCreate.js +51 -0
  174. package/dist/npm/models/transactions/vaultCreate.js.map +1 -0
  175. package/dist/npm/models/transactions/vaultDelete.d.ts +7 -0
  176. package/dist/npm/models/transactions/vaultDelete.d.ts.map +1 -0
  177. package/dist/npm/models/transactions/vaultDelete.js +10 -0
  178. package/dist/npm/models/transactions/vaultDelete.js.map +1 -0
  179. package/dist/npm/models/transactions/vaultDeposit.d.ts +9 -0
  180. package/dist/npm/models/transactions/vaultDeposit.d.ts.map +1 -0
  181. package/dist/npm/models/transactions/vaultDeposit.js +11 -0
  182. package/dist/npm/models/transactions/vaultDeposit.js.map +1 -0
  183. package/dist/npm/models/transactions/vaultSet.d.ts +10 -0
  184. package/dist/npm/models/transactions/vaultSet.d.ts.map +1 -0
  185. package/dist/npm/models/transactions/vaultSet.js +25 -0
  186. package/dist/npm/models/transactions/vaultSet.js.map +1 -0
  187. package/dist/npm/models/transactions/vaultWithdraw.d.ts +10 -0
  188. package/dist/npm/models/transactions/vaultWithdraw.d.ts.map +1 -0
  189. package/dist/npm/models/transactions/vaultWithdraw.js +12 -0
  190. package/dist/npm/models/transactions/vaultWithdraw.js.map +1 -0
  191. package/dist/npm/models/utils/flags.d.ts.map +1 -1
  192. package/dist/npm/models/utils/flags.js +26 -9
  193. package/dist/npm/models/utils/flags.js.map +1 -1
  194. package/dist/npm/models/utils/index.d.ts +2 -0
  195. package/dist/npm/models/utils/index.d.ts.map +1 -1
  196. package/dist/npm/models/utils/index.js +11 -1
  197. package/dist/npm/models/utils/index.js.map +1 -1
  198. package/dist/npm/snippets/tsconfig.tsbuildinfo +1 -1
  199. package/dist/npm/src/Wallet/batchSigner.d.ts +8 -0
  200. package/dist/npm/src/Wallet/batchSigner.d.ts.map +1 -0
  201. package/dist/npm/src/Wallet/batchSigner.js +111 -0
  202. package/dist/npm/src/Wallet/batchSigner.js.map +1 -0
  203. package/dist/npm/src/Wallet/defaultFaucets.d.ts +3 -2
  204. package/dist/npm/src/Wallet/defaultFaucets.d.ts.map +1 -1
  205. package/dist/npm/src/Wallet/defaultFaucets.js +16 -15
  206. package/dist/npm/src/Wallet/defaultFaucets.js.map +1 -1
  207. package/dist/npm/src/Wallet/fundWallet.d.ts.map +1 -1
  208. package/dist/npm/src/Wallet/fundWallet.js +8 -16
  209. package/dist/npm/src/Wallet/fundWallet.js.map +1 -1
  210. package/dist/npm/src/Wallet/index.d.ts.map +1 -1
  211. package/dist/npm/src/Wallet/index.js +10 -4
  212. package/dist/npm/src/Wallet/index.js.map +1 -1
  213. package/dist/npm/src/Wallet/signer.d.ts.map +1 -1
  214. package/dist/npm/src/Wallet/signer.js +4 -20
  215. package/dist/npm/src/Wallet/signer.js.map +1 -1
  216. package/dist/npm/src/Wallet/utils.d.ts +9 -0
  217. package/dist/npm/src/Wallet/utils.d.ts.map +1 -0
  218. package/dist/npm/src/Wallet/utils.js +28 -0
  219. package/dist/npm/src/Wallet/utils.js.map +1 -0
  220. package/dist/npm/src/client/RequestManager.d.ts.map +1 -1
  221. package/dist/npm/src/client/RequestManager.js +3 -3
  222. package/dist/npm/src/client/RequestManager.js.map +1 -1
  223. package/dist/npm/src/client/connection.d.ts.map +1 -1
  224. package/dist/npm/src/client/connection.js.map +1 -1
  225. package/dist/npm/src/client/index.d.ts +3 -3
  226. package/dist/npm/src/client/index.d.ts.map +1 -1
  227. package/dist/npm/src/client/index.js +14 -14
  228. package/dist/npm/src/client/index.js.map +1 -1
  229. package/dist/npm/src/client/partialPayment.d.ts.map +1 -1
  230. package/dist/npm/src/client/partialPayment.js +2 -2
  231. package/dist/npm/src/client/partialPayment.js.map +1 -1
  232. package/dist/npm/src/models/common/index.d.ts +1 -0
  233. package/dist/npm/src/models/common/index.d.ts.map +1 -1
  234. package/dist/npm/src/models/ledger/AccountRoot.d.ts +1 -1
  235. package/dist/npm/src/models/ledger/AccountRoot.d.ts.map +1 -1
  236. package/dist/npm/src/models/ledger/Credential.d.ts +2 -2
  237. package/dist/npm/src/models/ledger/Credential.d.ts.map +1 -1
  238. package/dist/npm/src/models/ledger/LedgerEntry.d.ts +3 -2
  239. package/dist/npm/src/models/ledger/LedgerEntry.d.ts.map +1 -1
  240. package/dist/npm/src/models/ledger/Vault.d.ts +21 -0
  241. package/dist/npm/src/models/ledger/Vault.d.ts.map +1 -0
  242. package/dist/npm/src/models/ledger/Vault.js +3 -0
  243. package/dist/npm/src/models/ledger/Vault.js.map +1 -0
  244. package/dist/npm/src/models/ledger/XChainOwnedClaimID.d.ts +1 -2
  245. package/dist/npm/src/models/ledger/XChainOwnedClaimID.d.ts.map +1 -1
  246. package/dist/npm/src/models/ledger/index.d.ts +2 -1
  247. package/dist/npm/src/models/ledger/index.d.ts.map +1 -1
  248. package/dist/npm/src/models/ledger/index.js.map +1 -1
  249. package/dist/npm/src/models/methods/baseMethod.d.ts +1 -0
  250. package/dist/npm/src/models/methods/baseMethod.d.ts.map +1 -1
  251. package/dist/npm/src/models/methods/index.d.ts +5 -4
  252. package/dist/npm/src/models/methods/index.d.ts.map +1 -1
  253. package/dist/npm/src/models/methods/vaultInfo.d.ts +46 -0
  254. package/dist/npm/src/models/methods/vaultInfo.d.ts.map +1 -0
  255. package/dist/npm/src/models/methods/vaultInfo.js +3 -0
  256. package/dist/npm/src/models/methods/vaultInfo.js.map +1 -0
  257. package/dist/npm/src/models/transactions/AMMBid.d.ts.map +1 -1
  258. package/dist/npm/src/models/transactions/AMMBid.js +7 -5
  259. package/dist/npm/src/models/transactions/AMMBid.js.map +1 -1
  260. package/dist/npm/src/models/transactions/AMMClawback.d.ts +2 -2
  261. package/dist/npm/src/models/transactions/AMMClawback.d.ts.map +1 -1
  262. package/dist/npm/src/models/transactions/AMMClawback.js +5 -6
  263. package/dist/npm/src/models/transactions/AMMClawback.js.map +1 -1
  264. package/dist/npm/src/models/transactions/AMMDelete.d.ts.map +1 -1
  265. package/dist/npm/src/models/transactions/AMMDelete.js +2 -2
  266. package/dist/npm/src/models/transactions/AMMDelete.js.map +1 -1
  267. package/dist/npm/src/models/transactions/AMMDeposit.d.ts +2 -2
  268. package/dist/npm/src/models/transactions/AMMDeposit.d.ts.map +1 -1
  269. package/dist/npm/src/models/transactions/AMMDeposit.js +3 -3
  270. package/dist/npm/src/models/transactions/AMMDeposit.js.map +1 -1
  271. package/dist/npm/src/models/transactions/AMMVote.d.ts.map +1 -1
  272. package/dist/npm/src/models/transactions/AMMVote.js +2 -2
  273. package/dist/npm/src/models/transactions/AMMVote.js.map +1 -1
  274. package/dist/npm/src/models/transactions/AMMWithdraw.d.ts +2 -2
  275. package/dist/npm/src/models/transactions/AMMWithdraw.d.ts.map +1 -1
  276. package/dist/npm/src/models/transactions/AMMWithdraw.js +3 -3
  277. package/dist/npm/src/models/transactions/AMMWithdraw.js.map +1 -1
  278. package/dist/npm/src/models/transactions/MPTokenAuthorize.d.ts +2 -2
  279. package/dist/npm/src/models/transactions/MPTokenAuthorize.d.ts.map +1 -1
  280. package/dist/npm/src/models/transactions/MPTokenIssuanceCreate.d.ts +2 -2
  281. package/dist/npm/src/models/transactions/MPTokenIssuanceCreate.d.ts.map +1 -1
  282. package/dist/npm/src/models/transactions/MPTokenIssuanceCreate.js +3 -3
  283. package/dist/npm/src/models/transactions/MPTokenIssuanceCreate.js.map +1 -1
  284. package/dist/npm/src/models/transactions/MPTokenIssuanceSet.d.ts +2 -2
  285. package/dist/npm/src/models/transactions/MPTokenIssuanceSet.d.ts.map +1 -1
  286. package/dist/npm/src/models/transactions/MPTokenIssuanceSet.js +4 -4
  287. package/dist/npm/src/models/transactions/MPTokenIssuanceSet.js.map +1 -1
  288. package/dist/npm/src/models/transactions/NFTokenCancelOffer.d.ts.map +1 -1
  289. package/dist/npm/src/models/transactions/NFTokenCancelOffer.js +1 -1
  290. package/dist/npm/src/models/transactions/NFTokenCancelOffer.js.map +1 -1
  291. package/dist/npm/src/models/transactions/NFTokenCreateOffer.d.ts +2 -2
  292. package/dist/npm/src/models/transactions/NFTokenCreateOffer.d.ts.map +1 -1
  293. package/dist/npm/src/models/transactions/NFTokenCreateOffer.js +6 -2
  294. package/dist/npm/src/models/transactions/NFTokenCreateOffer.js.map +1 -1
  295. package/dist/npm/src/models/transactions/NFTokenMint.d.ts +2 -2
  296. package/dist/npm/src/models/transactions/NFTokenMint.d.ts.map +1 -1
  297. package/dist/npm/src/models/transactions/XChainAddAccountCreateAttestation.js.map +1 -1
  298. package/dist/npm/src/models/transactions/XChainAddClaimAttestation.js.map +1 -1
  299. package/dist/npm/src/models/transactions/XChainClaim.js.map +1 -1
  300. package/dist/npm/src/models/transactions/XChainCommit.js.map +1 -1
  301. package/dist/npm/src/models/transactions/XChainModifyBridge.d.ts +2 -2
  302. package/dist/npm/src/models/transactions/XChainModifyBridge.d.ts.map +1 -1
  303. package/dist/npm/src/models/transactions/accountDelete.d.ts.map +1 -1
  304. package/dist/npm/src/models/transactions/accountDelete.js.map +1 -1
  305. package/dist/npm/src/models/transactions/accountSet.d.ts +2 -2
  306. package/dist/npm/src/models/transactions/accountSet.d.ts.map +1 -1
  307. package/dist/npm/src/models/transactions/accountSet.js.map +1 -1
  308. package/dist/npm/src/models/transactions/batch.d.ts +39 -0
  309. package/dist/npm/src/models/transactions/batch.d.ts.map +1 -0
  310. package/dist/npm/src/models/transactions/batch.js +64 -0
  311. package/dist/npm/src/models/transactions/batch.js.map +1 -0
  312. package/dist/npm/src/models/transactions/checkCreate.d.ts.map +1 -1
  313. package/dist/npm/src/models/transactions/checkCreate.js +1 -2
  314. package/dist/npm/src/models/transactions/checkCreate.js.map +1 -1
  315. package/dist/npm/src/models/transactions/clawback.d.ts +2 -2
  316. package/dist/npm/src/models/transactions/clawback.d.ts.map +1 -1
  317. package/dist/npm/src/models/transactions/clawback.js +4 -6
  318. package/dist/npm/src/models/transactions/clawback.js.map +1 -1
  319. package/dist/npm/src/models/transactions/common.d.ts +30 -9
  320. package/dist/npm/src/models/transactions/common.d.ts.map +1 -1
  321. package/dist/npm/src/models/transactions/common.js +74 -36
  322. package/dist/npm/src/models/transactions/common.js.map +1 -1
  323. package/dist/npm/src/models/transactions/delegateSet.d.ts.map +1 -1
  324. package/dist/npm/src/models/transactions/delegateSet.js +1 -0
  325. package/dist/npm/src/models/transactions/delegateSet.js.map +1 -1
  326. package/dist/npm/src/models/transactions/depositPreauth.d.ts.map +1 -1
  327. package/dist/npm/src/models/transactions/depositPreauth.js.map +1 -1
  328. package/dist/npm/src/models/transactions/escrowFinish.d.ts.map +1 -1
  329. package/dist/npm/src/models/transactions/escrowFinish.js.map +1 -1
  330. package/dist/npm/src/models/transactions/index.d.ts +9 -2
  331. package/dist/npm/src/models/transactions/index.d.ts.map +1 -1
  332. package/dist/npm/src/models/transactions/index.js +4 -1
  333. package/dist/npm/src/models/transactions/index.js.map +1 -1
  334. package/dist/npm/src/models/transactions/metadata.d.ts +1 -0
  335. package/dist/npm/src/models/transactions/metadata.d.ts.map +1 -1
  336. package/dist/npm/src/models/transactions/offerCreate.d.ts +2 -2
  337. package/dist/npm/src/models/transactions/offerCreate.d.ts.map +1 -1
  338. package/dist/npm/src/models/transactions/oracleSet.d.ts.map +1 -1
  339. package/dist/npm/src/models/transactions/oracleSet.js +22 -21
  340. package/dist/npm/src/models/transactions/oracleSet.js.map +1 -1
  341. package/dist/npm/src/models/transactions/payment.d.ts +3 -2
  342. package/dist/npm/src/models/transactions/payment.d.ts.map +1 -1
  343. package/dist/npm/src/models/transactions/payment.js +9 -4
  344. package/dist/npm/src/models/transactions/payment.js.map +1 -1
  345. package/dist/npm/src/models/transactions/paymentChannelClaim.d.ts +2 -2
  346. package/dist/npm/src/models/transactions/paymentChannelClaim.d.ts.map +1 -1
  347. package/dist/npm/src/models/transactions/paymentChannelClaim.js.map +1 -1
  348. package/dist/npm/src/models/transactions/permissionedDomainSet.d.ts.map +1 -1
  349. package/dist/npm/src/models/transactions/permissionedDomainSet.js +1 -1
  350. package/dist/npm/src/models/transactions/permissionedDomainSet.js.map +1 -1
  351. package/dist/npm/src/models/transactions/signerListSet.d.ts.map +1 -1
  352. package/dist/npm/src/models/transactions/signerListSet.js +10 -16
  353. package/dist/npm/src/models/transactions/signerListSet.js.map +1 -1
  354. package/dist/npm/src/models/transactions/transaction.d.ts +8 -1
  355. package/dist/npm/src/models/transactions/transaction.d.ts.map +1 -1
  356. package/dist/npm/src/models/transactions/transaction.js +35 -35
  357. package/dist/npm/src/models/transactions/transaction.js.map +1 -1
  358. package/dist/npm/src/models/transactions/trustSet.d.ts +2 -2
  359. package/dist/npm/src/models/transactions/trustSet.d.ts.map +1 -1
  360. package/dist/npm/src/models/transactions/vaultClawback.d.ts +10 -0
  361. package/dist/npm/src/models/transactions/vaultClawback.d.ts.map +1 -0
  362. package/dist/npm/src/models/transactions/vaultClawback.js +12 -0
  363. package/dist/npm/src/models/transactions/vaultClawback.js.map +1 -0
  364. package/dist/npm/src/models/transactions/vaultCreate.d.ts +24 -0
  365. package/dist/npm/src/models/transactions/vaultCreate.d.ts.map +1 -0
  366. package/dist/npm/src/models/transactions/vaultCreate.js +51 -0
  367. package/dist/npm/src/models/transactions/vaultCreate.js.map +1 -0
  368. package/dist/npm/src/models/transactions/vaultDelete.d.ts +7 -0
  369. package/dist/npm/src/models/transactions/vaultDelete.d.ts.map +1 -0
  370. package/dist/npm/src/models/transactions/vaultDelete.js +10 -0
  371. package/dist/npm/src/models/transactions/vaultDelete.js.map +1 -0
  372. package/dist/npm/src/models/transactions/vaultDeposit.d.ts +9 -0
  373. package/dist/npm/src/models/transactions/vaultDeposit.d.ts.map +1 -0
  374. package/dist/npm/src/models/transactions/vaultDeposit.js +11 -0
  375. package/dist/npm/src/models/transactions/vaultDeposit.js.map +1 -0
  376. package/dist/npm/src/models/transactions/vaultSet.d.ts +10 -0
  377. package/dist/npm/src/models/transactions/vaultSet.d.ts.map +1 -0
  378. package/dist/npm/src/models/transactions/vaultSet.js +25 -0
  379. package/dist/npm/src/models/transactions/vaultSet.js.map +1 -0
  380. package/dist/npm/src/models/transactions/vaultWithdraw.d.ts +10 -0
  381. package/dist/npm/src/models/transactions/vaultWithdraw.d.ts.map +1 -0
  382. package/dist/npm/src/models/transactions/vaultWithdraw.js +12 -0
  383. package/dist/npm/src/models/transactions/vaultWithdraw.js.map +1 -0
  384. package/dist/npm/src/models/utils/flags.d.ts.map +1 -1
  385. package/dist/npm/src/models/utils/flags.js +26 -9
  386. package/dist/npm/src/models/utils/flags.js.map +1 -1
  387. package/dist/npm/src/models/utils/index.d.ts +2 -0
  388. package/dist/npm/src/models/utils/index.d.ts.map +1 -1
  389. package/dist/npm/src/models/utils/index.js +11 -1
  390. package/dist/npm/src/models/utils/index.js.map +1 -1
  391. package/dist/npm/src/sugar/autofill.d.ts +4 -2
  392. package/dist/npm/src/sugar/autofill.d.ts.map +1 -1
  393. package/dist/npm/src/sugar/autofill.js +109 -16
  394. package/dist/npm/src/sugar/autofill.js.map +1 -1
  395. package/dist/npm/src/sugar/submit.d.ts.map +1 -1
  396. package/dist/npm/src/sugar/submit.js.map +1 -1
  397. package/dist/npm/src/utils/hashes/hashLedger.d.ts.map +1 -1
  398. package/dist/npm/src/utils/hashes/hashLedger.js +4 -1
  399. package/dist/npm/src/utils/hashes/hashLedger.js.map +1 -1
  400. package/dist/npm/sugar/autofill.d.ts +4 -2
  401. package/dist/npm/sugar/autofill.d.ts.map +1 -1
  402. package/dist/npm/sugar/autofill.js +109 -16
  403. package/dist/npm/sugar/autofill.js.map +1 -1
  404. package/dist/npm/sugar/submit.d.ts.map +1 -1
  405. package/dist/npm/sugar/submit.js.map +1 -1
  406. package/dist/npm/utils/hashes/hashLedger.d.ts.map +1 -1
  407. package/dist/npm/utils/hashes/hashLedger.js +4 -1
  408. package/dist/npm/utils/hashes/hashLedger.js.map +1 -1
  409. package/package.json +7 -6
  410. package/src/Wallet/batchSigner.ts +198 -0
  411. package/src/Wallet/defaultFaucets.ts +20 -18
  412. package/src/Wallet/fundWallet.ts +17 -28
  413. package/src/Wallet/index.ts +9 -3
  414. package/src/Wallet/signer.ts +4 -39
  415. package/src/Wallet/utils.ts +58 -0
  416. package/src/client/RequestManager.ts +4 -1
  417. package/src/client/connection.ts +0 -1
  418. package/src/client/index.ts +50 -66
  419. package/src/client/partialPayment.ts +2 -4
  420. package/src/models/common/index.ts +2 -0
  421. package/src/models/ledger/AccountRoot.ts +1 -1
  422. package/src/models/ledger/Credential.ts +2 -2
  423. package/src/models/ledger/LedgerEntry.ts +3 -0
  424. package/src/models/ledger/Vault.ts +83 -0
  425. package/src/models/ledger/XChainOwnedClaimID.ts +1 -3
  426. package/src/models/ledger/index.ts +3 -1
  427. package/src/models/methods/baseMethod.ts +1 -0
  428. package/src/models/methods/index.ts +10 -0
  429. package/src/models/methods/vaultInfo.ts +193 -0
  430. package/src/models/transactions/AMMBid.ts +12 -21
  431. package/src/models/transactions/AMMClawback.ts +10 -13
  432. package/src/models/transactions/AMMDelete.ts +7 -3
  433. package/src/models/transactions/AMMDeposit.ts +6 -6
  434. package/src/models/transactions/AMMVote.ts +7 -3
  435. package/src/models/transactions/AMMWithdraw.ts +6 -6
  436. package/src/models/transactions/MPTokenAuthorize.ts +2 -2
  437. package/src/models/transactions/MPTokenIssuanceCreate.ts +6 -3
  438. package/src/models/transactions/MPTokenIssuanceSet.ts +3 -3
  439. package/src/models/transactions/NFTokenCancelOffer.ts +2 -2
  440. package/src/models/transactions/NFTokenCreateOffer.ts +10 -6
  441. package/src/models/transactions/NFTokenMint.ts +2 -2
  442. package/src/models/transactions/XChainAddAccountCreateAttestation.ts +2 -2
  443. package/src/models/transactions/XChainAddClaimAttestation.ts +2 -2
  444. package/src/models/transactions/XChainClaim.ts +1 -1
  445. package/src/models/transactions/XChainCommit.ts +1 -1
  446. package/src/models/transactions/XChainModifyBridge.ts +2 -2
  447. package/src/models/transactions/accountDelete.ts +1 -2
  448. package/src/models/transactions/accountSet.ts +2 -1
  449. package/src/models/transactions/batch.ts +151 -0
  450. package/src/models/transactions/checkCreate.ts +2 -6
  451. package/src/models/transactions/clawback.ts +9 -10
  452. package/src/models/transactions/common.ts +194 -69
  453. package/src/models/transactions/delegateSet.ts +1 -0
  454. package/src/models/transactions/depositPreauth.ts +2 -4
  455. package/src/models/transactions/escrowFinish.ts +1 -2
  456. package/src/models/transactions/index.ts +14 -3
  457. package/src/models/transactions/metadata.ts +2 -0
  458. package/src/models/transactions/offerCreate.ts +2 -2
  459. package/src/models/transactions/oracleSet.ts +88 -91
  460. package/src/models/transactions/payment.ts +21 -13
  461. package/src/models/transactions/paymentChannelClaim.ts +4 -4
  462. package/src/models/transactions/permissionedDomainSet.ts +3 -7
  463. package/src/models/transactions/signerListSet.ts +21 -21
  464. package/src/models/transactions/transaction.ts +61 -43
  465. package/src/models/transactions/trustSet.ts +2 -2
  466. package/src/models/transactions/vaultClawback.ts +55 -0
  467. package/src/models/transactions/vaultCreate.ts +142 -0
  468. package/src/models/transactions/vaultDelete.ts +32 -0
  469. package/src/models/transactions/vaultDeposit.ts +41 -0
  470. package/src/models/transactions/vaultSet.ts +71 -0
  471. package/src/models/transactions/vaultWithdraw.ts +50 -0
  472. package/src/models/utils/flags.ts +30 -10
  473. package/src/models/utils/index.ts +24 -0
  474. package/src/sugar/autofill.ts +165 -35
  475. package/src/sugar/submit.ts +1 -2
  476. package/src/utils/hashes/hashLedger.ts +5 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xrpl-latest-min.js","mappings":";oIAAA,eAEA,UAwCA,sCAA2CA,GAGzC,IAFA,IAAAC,yBAAwBD,QAELE,IAAfF,EAAGG,QACL,MAAM,IAAI,EAAAC,gBAAgB,uCAG5B,GAA0B,iBAAfJ,EAAGG,QACZ,MAAM,IAAI,EAAAC,gBAAgB,gDAG5B,QAAkBF,IAAdF,EAAGK,OACL,MAAM,IAAI,EAAAD,gBAAgB,sCAG5B,GAAyB,iBAAdJ,EAAGK,OACZ,MAAM,IAAI,EAAAD,gBAAgB,+CAG5B,QAAsBF,IAAlBF,EAAGM,YAAqD,iBAAlBN,EAAGM,WAC3C,MAAM,IAAI,EAAAF,gBAAgB,kDAE9B,+FChEA,gBACA,SAKA,MAAMG,UAAgB,EAAAC,KAIpB,WAAAC,CAAYC,GACNA,GAA8B,IAArBA,EAAMC,aACjBD,EAAQH,EAAQK,SAASF,OAG3BG,MAAMH,QAAAA,EAASH,EAAQK,SAASF,MAClC,CAOA,KAAAI,GACE,MAAMC,GAAM,IAAAC,YAAWC,KAAKC,WAC5B,MAAI,OAAOC,KAAKJ,GACP,GAEFA,CACT,EAGO,EAAAR,QAAAA,EAzBS,EAAAa,MAAQ,GACR,EAAAR,SAAoB,IAAIL,EAAQ,IAAIc,WAAWd,EAAQa,kKCNzE,MAAME,EAAY,kBAwBlB,SAAgBC,EAAcC,EAAeC,GAE3C,OAAQC,OAAOD,GAAaC,OAAOF,MAAYE,OAAOD,EACxD,CA1Ba,EAAAE,qBAAuB,YASpC,yBACEC,EACAC,GAEA,OAAOC,OAAOC,KAAKH,GAAKI,OAAOC,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H,OAAOA,EAAap/D,QAGrB,IAAI2+D,EAASK,EAAyBG,GAAY,CAGjDn/D,QAAS,CAAC,GAOX,OAHAq/D,EAAoBF,GAAUj/E,KAAKy+E,EAAO3+D,QAAS2+D,EAAQA,EAAO3+D,QAASk/D,GAGpEP,EAAO3+D,OACf,CCnB0Bk/D,CAAoB","sources":["webpack://xrpl/./src/models/transactions/paymentChannelFund.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/hash-128.ts","webpack://xrpl/./src/models/utils/index.ts","webpack://xrpl/./src/utils/hashes/SHAMap/node.ts","webpack://xrpl/./src/models/transactions/checkCash.ts","webpack://xrpl/./src/errors.ts","webpack://xrpl/./src/utils/signPaymentChannelClaim.ts","webpack://xrpl/./src/models/transactions/CredentialAccept.ts","webpack://xrpl/./src/utils/verifyPaymentChannelClaim.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/uint-8.ts","webpack://xrpl/./src/models/transactions/XChainCreateClaimID.ts","webpack://xrpl/./src/utils/hashes/SHAMap/InnerNode.ts","webpack://xrpl/./src/models/transactions/MPTokenIssuanceSet.ts","webpack://xrpl/./src/models/transactions/depositPreauth.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/utils/browser.ts","webpack://xrpl/./src/Wallet/utils.ts","webpack://xrpl/./src/models/transactions/XChainCreateBridge.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts","webpack://xrpl/../../node_modules/bignumber.js/bignumber.js","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/modular.ts","webpack://xrpl/./src/client/partialPayment.ts","webpack://xrpl/./src/models/transactions/permissionedDomainSet.ts","webpack://xrpl/../../node_modules/@scure/bip32/index.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/serdes/binary-parser.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/ws/browser.ts","webpack://xrpl/./src/models/transactions/AMMWithdraw.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/legacy.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/hash-to-curve.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/index.ts","webpack://xrpl/../../node_modules/@scure/bip39/wordlists/english.js","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/serialized-type.ts","webpack://xrpl/./src/models/common/index.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/crypto.ts","webpack://xrpl/./src/models/transactions/MPTokenIssuanceDestroy.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/uint-16.ts","webpack://xrpl/./src/utils/hashes/index.ts","webpack://xrpl/./src/models/transactions/oracleSet.ts","webpack://xrpl/./src/models/transactions/payment.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts","webpack://xrpl/./src/sugar/autofill.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/utils/shared.ts","webpack://xrpl/../../node_modules/@scure/base/index.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/ripemd160/browser.ts","webpack://xrpl/./src/models/transactions/setRegularKey.ts","webpack://xrpl/./src/models/transactions/paymentChannelCreate.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_md.ts","webpack://xrpl/./src/models/ledger/SignerList.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/utils/getAlgorithmFromKey.ts","webpack://xrpl/./src/models/transactions/vaultSet.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/issue.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/internal/normalizeInput.ts","webpack://xrpl/./src/models/transactions/XChainAddClaimAttestation.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","webpack://xrpl/./src/models/transactions/paymentChannelClaim.ts","webpack://xrpl/./src/models/transactions/AMMVote.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha256.ts","webpack://xrpl/./src/utils/timeConversion.ts","webpack://xrpl/./src/models/transactions/vaultDelete.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/ledger-hashes.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/signing-schemes/secp256k1/index.ts","webpack://xrpl/./src/utils/hashes/sha512Half.ts","webpack://xrpl/../../node_modules/@xrplf/secret-numbers/src/schema/Account.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/internal/wrapNoble.ts","webpack://xrpl/./src/utils/xrpConversion.ts","webpack://xrpl/./src/models/transactions/common.ts","webpack://xrpl/../../node_modules/ripple-address-codec/src/utils.ts","webpack://xrpl/./src/models/transactions/checkCreate.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/sha512/browser.ts","webpack://xrpl/./src/models/transactions/signerListSet.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/xchain-bridge.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/bytes.ts","webpack://xrpl/./src/utils/getBalanceChanges.ts","webpack://xrpl/./src/models/transactions/ticketCreate.ts","webpack://xrpl/./src/models/transactions/MPTokenAuthorize.ts","webpack://xrpl/./src/utils/hashes/SHAMap/index.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/utils/assert.ts","webpack://xrpl/./src/sugar/getOrderbook.ts","webpack://xrpl/./src/models/transactions/escrowCreate.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/uint.ts","webpack://xrpl/./src/models/transactions/metadata.ts","webpack://xrpl/./src/utils/quality.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/utils.ts","webpack://xrpl/./src/models/transactions/vaultDeposit.ts","webpack://xrpl/./src/models/transactions/XChainCommit.ts","webpack://xrpl/./src/models/transactions/offerCancel.ts","webpack://xrpl/./src/utils/hashes/ledgerSpaces.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/vector-256.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/field.ts","webpack://xrpl/./src/models/transactions/AMMClawback.ts","webpack://xrpl/./src/models/transactions/accountSet.ts","webpack://xrpl/../../node_modules/@xrplf/secret-numbers/src/index.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/hash.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","webpack://xrpl/./src/Wallet/signer.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/path-set.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/curve.ts","webpack://xrpl/./src/client/connection.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/coretypes.ts","webpack://xrpl/./src/utils/getXChainClaimID.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/uint-32.ts","webpack://xrpl/./src/Wallet/defaultFaucets.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/pbkdf2.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/utils.ts","webpack://xrpl/./src/Wallet/rfc1751.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/sha2.ts","webpack://xrpl/./src/models/transactions/AMMBid.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/weierstrass.ts","webpack://xrpl/./src/sugar/submit.ts","webpack://xrpl/./src/models/transactions/XChainModifyBridge.ts","webpack://xrpl/./src/models/transactions/delegateSet.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/xrpl-definitions.ts","webpack://xrpl/./src/models/transactions/permissionedDomainDelete.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/crypto.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/utils/Sha512.ts","webpack://xrpl/./src/models/transactions/AMMDelete.ts","webpack://xrpl/./src/models/transactions/XChainAccountCreateCommit.ts","webpack://xrpl/./src/client/index.ts","webpack://xrpl/./src/models/transactions/NFTokenBurn.ts","webpack://xrpl/./src/models/ledger/Offer.ts","webpack://xrpl/./src/Wallet/index.ts","webpack://xrpl/./src/utils/parseNFTokenID.ts","webpack://xrpl/./src/models/ledger/NegativeUNL.ts","webpack://xrpl/./src/client/ExponentialBackoff.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/index.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/uint-64.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/utils.ts","webpack://xrpl/../../node_modules/ripple-address-codec/src/xrp-codec.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/utils.ts","webpack://xrpl/./src/models/transactions/vaultCreate.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/index.ts","webpack://xrpl/./src/index.ts","webpack://xrpl/./src/utils/hashes/SHAMap/LeafNode.ts","webpack://xrpl/./src/utils/index.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_assert.ts","webpack://xrpl/./src/models/transactions/vaultWithdraw.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/blob.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/account-id.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/edwards.ts","webpack://xrpl/./src/models/transactions/NFTokenCreateOffer.ts","webpack://xrpl/./src/models/transactions/transaction.ts","webpack://xrpl/./src/models/transactions/clawback.ts","webpack://xrpl/./src/Wallet/walletFromSecretNumbers.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/sha512.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/currency.ts","webpack://xrpl/./src/ECDSA.ts","webpack://xrpl/./src/models/transactions/NFTokenAcceptOffer.ts","webpack://xrpl/./src/models/transactions/trustSet.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/hmac.ts","webpack://xrpl/./src/models/transactions/AMMDeposit.ts","webpack://xrpl/./src/utils/hashes/hashLedger.ts","webpack://xrpl/./src/models/transactions/checkCancel.ts","webpack://xrpl/../../node_modules/ripple-address-codec/src/index.ts","webpack://xrpl/./src/utils/stringConversion.ts","webpack://xrpl/./src/sugar/balances.ts","webpack://xrpl/./src/sugar/getFeeXrp.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/sha512.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/ripemd160.ts","webpack://xrpl/../../node_modules/@noble/curves/src/_shortw_utils.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/_u64.ts","webpack://xrpl/./src/utils/getNFTokenID.ts","webpack://xrpl/./src/models/transactions/batch.ts","webpack://xrpl/./src/models/transactions/CredentialDelete.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/_md.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/hash-192.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/index.ts","webpack://xrpl/../../node_modules/@noble/hashes/src/sha256.ts","webpack://xrpl/./src/models/ledger/FeeSettings.ts","webpack://xrpl/./src/models/transactions/escrowCancel.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/hmac.ts","webpack://xrpl/./src/Wallet/fundWallet.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/hash-160.ts","webpack://xrpl/./src/models/transactions/escrowFinish.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/hash-prefixes.ts","webpack://xrpl/../../node_modules/@xrplf/isomorphic/src/sha256/browser.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/hashes.ts","webpack://xrpl/./src/models/transactions/enableAmendment.ts","webpack://xrpl/./src/models/transactions/NFTokenModify.ts","webpack://xrpl/./src/models/transactions/NFTokenCancelOffer.ts","webpack://xrpl/./src/models/transactions/CredentialCreate.ts","webpack://xrpl/../../node_modules/@noble/curves/src/abstract/montgomery.ts","webpack://xrpl/./src/sugar/index.ts","webpack://xrpl/./src/models/transactions/XChainAddAccountCreateAttestation.ts","webpack://xrpl/./src/models/ledger/Amendments.ts","webpack://xrpl/./src/sugar/utils.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/serdes/binary-serializer.ts","webpack://xrpl/../../node_modules/@xrplf/secret-numbers/src/utils/index.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/constants.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/quality.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/st-array.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/hash-256.ts","webpack://xrpl/./src/models/transactions/DIDSet.ts","webpack://xrpl/./src/models/transactions/XChainClaim.ts","webpack://xrpl/./src/models/transactions/DIDDelete.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/shamap.ts","webpack://xrpl/./src/utils/derive.ts","webpack://xrpl/./src/models/ledger/AccountRoot.ts","webpack://xrpl/../../node_modules/@noble/curves/src/ed25519.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/ripemd160.ts","webpack://xrpl/./src/models/transactions/accountDelete.ts","webpack://xrpl/./src/models/transactions/NFTokenMint.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/st-number.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/enums/xrpl-definitions-base.ts","webpack://xrpl/./src/models/ledger/index.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/st-object.ts","webpack://xrpl/./src/models/ledger/RippleState.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/signing-schemes/secp256k1/utils.ts","webpack://xrpl/../../node_modules/@noble/curves/src/secp256k1.ts","webpack://xrpl/./src/models/transactions/vaultClawback.ts","webpack://xrpl/./src/utils/collections.ts","webpack://xrpl/./src/models/transactions/offerCreate.ts","webpack://xrpl/./src/utils/hashes/HashPrefix.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/types/amount.ts","webpack://xrpl/../../node_modules/ripple-binary-codec/src/binary.ts","webpack://xrpl/./src/client/RequestManager.ts","webpack://xrpl/../../node_modules/ripple-keypairs/src/signing-schemes/ed25519/index.ts","webpack://xrpl/./src/models/utils/flags.ts","webpack://xrpl/./src/models/transactions/oracleDelete.ts","webpack://xrpl/./src/models/index.ts","webpack://xrpl/../../node_modules/@scure/bip39/index.js","webpack://xrpl/../../node_modules/eventemitter3/index.js","webpack://xrpl/./src/models/transactions/index.ts","webpack://xrpl/../../node_modules/@scure/bip32/node_modules/@noble/hashes/src/_u64.ts","webpack://xrpl/./src/client/ConnectionManager.ts","webpack://xrpl/./src/models/transactions/MPTokenIssuanceCreate.ts","webpack://xrpl/./src/models/transactions/AMMCreate.ts","webpack://xrpl/../../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","webpack://xrpl/webpack/bootstrap","webpack://xrpl/webpack/startup"],"sourcesContent":["import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, validateBaseTransaction } from './common'\n\n/**\n * Add additional XRP to an open payment channel, and optionally update the\n * expiration time of the channel. Only the source address of the channel can\n * use this transaction.\n *\n * @category Transaction Models\n */\nexport interface PaymentChannelFund extends BaseTransaction {\n TransactionType: 'PaymentChannelFund'\n /**\n * The unique ID of the channel to fund as a 64-character hexadecimal\n * string.\n */\n Channel: string\n /**\n * Amount of XRP in drops to add to the channel. Must be a positive amount\n * of XRP.\n */\n Amount: string\n /**\n * New Expiration time to set for the channel in seconds since the Ripple\n * Epoch. This must be later than either the current time plus the SettleDelay\n * of the channel, or the existing Expiration of the channel. After the\n * Expiration time, any transaction that would access the channel closes the\n * channel without taking its normal action. Any unspent XRP is returned to\n * the source address when the channel closes. (Expiration is separate from\n * the channel's immutable CancelAfter time.) For more information, see the\n * PayChannel ledger object type.\n */\n Expiration?: number\n}\n\n/**\n * Verify the form and type of an PaymentChannelFund at runtime.\n *\n * @param tx - An PaymentChannelFund Transaction.\n * @throws When the PaymentChannelFund is Malformed.\n */\nexport function validatePaymentChannelFund(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Channel === undefined) {\n throw new ValidationError('PaymentChannelFund: missing Channel')\n }\n\n if (typeof tx.Channel !== 'string') {\n throw new ValidationError('PaymentChannelFund: Channel must be a string')\n }\n\n if (tx.Amount === undefined) {\n throw new ValidationError('PaymentChannelFund: missing Amount')\n }\n\n if (typeof tx.Amount !== 'string') {\n throw new ValidationError('PaymentChannelFund: Amount must be a string')\n }\n\n if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') {\n throw new ValidationError('PaymentChannelFund: Expiration must be a number')\n }\n}\n","import { Hash } from './hash'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\n/**\n * Hash with a width of 128 bits\n */\nclass Hash128 extends Hash {\n static readonly width = 16\n static readonly ZERO_128: Hash128 = new Hash128(new Uint8Array(Hash128.width))\n\n constructor(bytes: Uint8Array) {\n if (bytes && bytes.byteLength === 0) {\n bytes = Hash128.ZERO_128.bytes\n }\n\n super(bytes ?? Hash128.ZERO_128.bytes)\n }\n\n /**\n * Get the hex representation of a hash-128 bytes, allowing unset\n *\n * @returns hex String of this.bytes\n */\n toHex(): string {\n const hex = bytesToHex(this.toBytes())\n if (/^0+$/.exec(hex)) {\n return ''\n }\n return hex\n }\n}\n\nexport { Hash128 }\n","import type { Transaction } from '../transactions'\n\nconst HEX_REGEX = /^[0-9A-Fa-f]+$/u\nexport const INTEGER_SANITY_CHECK = /^[0-9]+$/u\n\n/**\n * Verify that all fields of an object are in fields.\n *\n * @param obj - Object to verify fields.\n * @param fields - Fields to verify.\n * @returns True if keys in object are all in fields.\n */\nexport function onlyHasFields(\n obj: Record<string, unknown>,\n fields: string[],\n): boolean {\n return Object.keys(obj).every((key: string) => fields.includes(key))\n}\n\n/**\n * Perform bitwise AND (&) to check if a flag is enabled within Flags (as a number).\n *\n * @param Flags - A number that represents flags enabled.\n * @param checkFlag - A specific flag to check if it's enabled within Flags.\n * @returns True if checkFlag is enabled within Flags.\n */\nexport function isFlagEnabled(Flags: number, checkFlag: number): boolean {\n // eslint-disable-next-line no-bitwise -- flags need bitwise\n return (BigInt(checkFlag) & BigInt(Flags)) === BigInt(checkFlag)\n}\n\n/**\n * Determines whether a transaction has a certain flag enabled.\n *\n * @param tx The transaction to check for the flag.\n * @param flag The flag to check.\n * @param flagName The name of the flag to check, used for object flags.\n * @returns Whether `flag` is enabled on `tx`.\n */\nexport function hasFlag(\n tx: Transaction | Record<string, unknown>,\n flag: number,\n flagName: string,\n): boolean {\n if (tx.Flags == null) {\n return false\n }\n if (typeof tx.Flags === 'number') {\n return isFlagEnabled(tx.Flags, flag)\n }\n return tx.Flags[flagName] === true\n}\n\n/**\n * Check if string is in hex format.\n *\n * @param str - The string to check if it's in hex format.\n * @returns True if string is in hex format\n */\nexport function isHex(str: string): boolean {\n return HEX_REGEX.test(str)\n}\n","export enum NodeType {\n INNER = 1,\n TRANSACTION_NO_METADATA = 2,\n TRANSACTION_METADATA = 3,\n ACCOUNT_STATE = 4,\n}\n\n/**\n * Abstract base class for SHAMapNode.\n */\nexport abstract class Node {\n public abstract get hash(): string\n public abstract addItem(_tag: string, _node: Node): void\n}\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\n\nimport { BaseTransaction, validateBaseTransaction, isAmount } from './common'\n\n/**\n * Attempts to redeem a Check object in the ledger to receive up to the amount\n * authorized by the corresponding CheckCreate transaction. Only the Destination\n * address of a Check can cash it with a CheckCash transaction.\n *\n * @category Transaction Models\n */\nexport interface CheckCash extends BaseTransaction {\n TransactionType: 'CheckCash'\n /**\n * The ID of the Check ledger object to cash as a 64-character hexadecimal\n * string.\n */\n CheckID: string\n /**\n * Redeem the Check for exactly this amount, if possible. The currency must\n * match that of the SendMax of the corresponding CheckCreate transaction. You.\n * must provide either this field or DeliverMin.\n */\n Amount?: Amount\n /**\n * Redeem the Check for at least this amount and for as much as possible. The\n * currency must match that of the SendMax of the corresponding CheckCreate.\n * transaction. You must provide either this field or Amount.\n */\n DeliverMin?: Amount\n}\n\n/**\n * Verify the form and type of an CheckCash at runtime.\n *\n * @param tx - An CheckCash Transaction.\n * @throws When the CheckCash is Malformed.\n */\nexport function validateCheckCash(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Amount == null && tx.DeliverMin == null) {\n throw new ValidationError(\n 'CheckCash: must have either Amount or DeliverMin',\n )\n }\n\n if (tx.Amount != null && tx.DeliverMin != null) {\n throw new ValidationError(\n 'CheckCash: cannot have both Amount and DeliverMin',\n )\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Necessary check\n if (tx.Amount != null && tx.Amount !== undefined && !isAmount(tx.Amount)) {\n throw new ValidationError('CheckCash: invalid Amount')\n }\n\n if (\n tx.DeliverMin != null &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Necessary check\n tx.DeliverMin !== undefined &&\n !isAmount(tx.DeliverMin)\n ) {\n throw new ValidationError('CheckCash: invalid DeliverMin')\n }\n\n if (tx.CheckID !== undefined && typeof tx.CheckID !== 'string') {\n throw new ValidationError('CheckCash: invalid CheckID')\n }\n}\n","/* eslint-disable max-classes-per-file -- Errors can be defined in the same file */\n/**\n * Base Error class for xrpl.js. All Errors thrown by xrpl.js should throw\n * XrplErrors.\n *\n * @category Errors\n */\nclass XrplError extends Error {\n public readonly name: string\n public readonly message: string\n public readonly data?: unknown\n\n /**\n * Construct an XrplError.\n *\n * @param message - The error message.\n * @param data - The data that caused the error.\n */\n public constructor(message = '', data?: unknown) {\n super(message)\n\n this.name = this.constructor.name\n this.message = message\n this.data = data\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- `captureStackTrace` can be null in browsers\n if (Error.captureStackTrace != null) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n /**\n * Converts the Error to a human-readable String form.\n *\n * @returns The String output of the Error.\n */\n public toString(): string {\n let result = `[${this.name}(${this.message}`\n if (this.data) {\n result += `, ${JSON.stringify(this.data)}`\n }\n result += ')]'\n return result\n }\n\n /**\n * Console.log in node uses util.inspect on object, and util.inspect allows\n * us to customize its output:\n * https://nodejs.org/api/util.html#util_custom_inspect_function_on_objects.\n *\n * @returns The String output of the Error.\n */\n public inspect(): string {\n return this.toString()\n }\n}\n\n/**\n * Error thrown when rippled responds with an error.\n *\n * @category Errors\n */\nclass RippledError extends XrplError {}\n\n/**\n * Error thrown when xrpl.js cannot specify error type.\n *\n * @category Errors\n */\nclass UnexpectedError extends XrplError {}\n\n/**\n * Error thrown when xrpl.js has an error with connection to rippled.\n *\n * @category Errors\n */\nclass ConnectionError extends XrplError {}\n\n/**\n * Error thrown when xrpl.js is not connected to rippled server.\n *\n * @category Errors\n */\nclass NotConnectedError extends ConnectionError {}\n\n/**\n * Error thrown when xrpl.js has disconnected from rippled server.\n *\n * @category Errors\n */\nclass DisconnectedError extends ConnectionError {}\n\n/**\n * Error thrown when rippled is not initialized.\n *\n * @category Errors\n */\nclass RippledNotInitializedError extends ConnectionError {}\n\n/**\n * Error thrown when xrpl.js times out.\n *\n * @category Errors\n */\nclass TimeoutError extends ConnectionError {}\n\n/**\n * Error thrown when xrpl.js sees a response in the wrong format.\n *\n * @category Errors\n */\nclass ResponseFormatError extends ConnectionError {}\n\n/**\n * Error thrown when xrpl.js sees a malformed transaction.\n *\n * @category Errors\n */\nclass ValidationError extends XrplError {}\n\n/**\n * Error thrown when a client cannot generate a wallet from the testnet/devnet\n * faucets, or when the client cannot infer the faucet URL (i.e. when the Client\n * is connected to mainnet).\n *\n * @category Errors\n */\nclass XRPLFaucetError extends XrplError {}\n\n/**\n * Error thrown when xrpl.js cannot retrieve a transaction, ledger, account, etc.\n * From rippled.\n *\n * @category Errors\n */\nclass NotFoundError extends XrplError {\n /**\n * Construct an XrplError.\n *\n * @param message - The error message. Defaults to \"Not found\".\n */\n public constructor(message = 'Not found') {\n super(message)\n }\n}\n\nexport {\n XrplError,\n UnexpectedError,\n ConnectionError,\n RippledError,\n NotConnectedError,\n DisconnectedError,\n RippledNotInitializedError,\n TimeoutError,\n ResponseFormatError,\n ValidationError,\n NotFoundError,\n XRPLFaucetError,\n}\n","import { encodeForSigningClaim } from 'ripple-binary-codec'\nimport { sign } from 'ripple-keypairs'\n\nimport { xrpToDrops } from './xrpConversion'\n\n/**\n * Sign a payment channel claim.\n *\n * @param channel - Channel identifier specified by the paymentChannelClaim.\n * @param xrpAmount - XRP Amount specified by the paymentChannelClaim.\n * @param privateKey - Private Key to sign paymentChannelClaim with.\n * @returns True if the channel is valid.\n * @category Utilities\n */\nfunction signPaymentChannelClaim(\n channel: string,\n xrpAmount: string,\n privateKey: string,\n): string {\n const signingData = encodeForSigningClaim({\n channel,\n amount: xrpToDrops(xrpAmount),\n })\n return sign(signingData, privateKey)\n}\n\nexport default signPaymentChannelClaim\n","import {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateCredentialType,\n validateRequiredField,\n} from './common'\n\n/**\n * Accepts a credential issued to the Account (i.e. the Account is the Subject of the Credential object).\n * Credentials are represented in hex. Whilst they are allowed a maximum length of 64\n * bytes, every byte requires 2 hex characters for representation.\n * The credential is not considered valid until it has been transferred/accepted.\n *\n * @category Transaction Models\n * */\nexport interface CredentialAccept extends BaseTransaction {\n TransactionType: 'CredentialAccept'\n\n /** The subject of the credential. */\n Account: string\n\n /** The issuer of the credential. */\n Issuer: string\n\n /** A hex-encoded value to identify the type of credential from the issuer. */\n CredentialType: string\n}\n\n/**\n * Verify the form and type of a CredentialAccept at runtime.\n *\n * @param tx - A CredentialAccept Transaction.\n * @throws When the CredentialAccept is Malformed.\n */\nexport function validateCredentialAccept(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Account', isString)\n\n validateRequiredField(tx, 'Issuer', isString)\n\n validateCredentialType(tx)\n}\n","import { encodeForSigningClaim } from 'ripple-binary-codec'\nimport { verify } from 'ripple-keypairs'\n\nimport { xrpToDrops } from './xrpConversion'\n\n/**\n * Verify the signature of a payment channel claim.\n *\n * @param channel - Channel identifier specified by the paymentChannelClaim.\n * @param xrpAmount - XRP Amount specified by the paymentChannelClaim.\n * @param signature - Signature produced from signing paymentChannelClaim.\n * @param publicKey - Public key that signed the paymentChannelClaim.\n * @returns True if the channel is valid.\n * @category Utilities\n */\n// eslint-disable-next-line max-params -- Needs 4 params\nfunction verifyPaymentChannelClaim(\n channel: string,\n xrpAmount: string,\n signature: string,\n publicKey: string,\n): boolean {\n const signingData = encodeForSigningClaim({\n channel,\n amount: xrpToDrops(xrpAmount),\n })\n return verify(signingData, signature, publicKey)\n}\n\nexport default verifyPaymentChannelClaim\n","import { UInt } from './uint'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\nimport { writeUInt8 } from '../utils'\n\n/**\n * Derived UInt class for serializing/deserializing 8 bit UInt\n */\nclass UInt8 extends UInt {\n protected static readonly width: number = 8 / 8 // 1\n static readonly defaultUInt8: UInt8 = new UInt8(new Uint8Array(UInt8.width))\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? UInt8.defaultUInt8.bytes)\n }\n\n static fromParser(parser: BinaryParser): UInt {\n return new UInt8(parser.read(UInt8.width))\n }\n\n /**\n * Construct a UInt8 object from a number\n *\n * @param val UInt8 object or number\n */\n static from<T extends UInt8 | number>(val: T): UInt8 {\n if (val instanceof UInt8) {\n return val\n }\n\n if (typeof val === 'number') {\n UInt8.checkUintRange(val, 0, 0xff)\n\n const buf = new Uint8Array(UInt8.width)\n writeUInt8(buf, val, 0)\n return new UInt8(buf)\n }\n\n throw new Error('Cannot construct UInt8 from given value')\n }\n\n /**\n * get the value of a UInt8 object\n *\n * @returns the number represented by this.bytes\n */\n valueOf(): number {\n return parseInt(bytesToHex(this.bytes), 16)\n }\n}\n\nexport { UInt8 }\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isAmount,\n isXChainBridge,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainCreateClaimID transaction creates a new cross-chain claim ID that is\n * used for a cross-chain transfer. A cross-chain claim ID represents one\n * cross-chain transfer of value.\n *\n * @category Transaction Models\n */\nexport interface XChainCreateClaimID extends BaseTransaction {\n TransactionType: 'XChainCreateClaimID'\n\n /**\n * The bridge to create the claim ID for.\n */\n XChainBridge: XChainBridge\n\n /**\n * The amount, in XRP, to reward the witness servers for providing signatures.\n * This must match the amount on the {@link Bridge} ledger object.\n */\n SignatureReward: Amount\n\n /**\n * The account that must send the {@link XChainCommit} transaction on the source chain.\n */\n OtherChainSource: Account\n}\n\n/**\n * Verify the form and type of an XChainCreateClaimID at runtime.\n *\n * @param tx - An XChainCreateClaimID Transaction.\n * @throws When the XChainCreateClaimID is malformed.\n */\nexport function validateXChainCreateClaimID(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(tx, 'SignatureReward', isAmount)\n\n validateRequiredField(tx, 'OtherChainSource', isAccount)\n}\n","import { XrplError } from '../../../errors'\nimport HashPrefix from '../HashPrefix'\nimport sha512Half from '../sha512Half'\n\nimport LeafNode from './LeafNode'\nimport { NodeType, Node } from './node'\n\nconst HEX_ZERO =\n '0000000000000000000000000000000000000000000000000000000000000000'\n\nconst SLOT_MAX = 15\nconst HEX = 16\n\n/**\n * Class for SHAMap InnerNode.\n */\nclass InnerNode extends Node {\n public leaves: { [slot: number]: Node | undefined }\n public type: NodeType\n public depth: number\n public empty: boolean\n\n /**\n * Define an Inner (non-leaf) node in a SHAMap tree.\n *\n * @param depth - I.e. How many parent inner nodes.\n */\n public constructor(depth = 0) {\n super()\n this.leaves = {}\n this.type = NodeType.INNER\n this.depth = depth\n this.empty = true\n }\n\n /**\n * Get the hash of a LeafNode.\n *\n * @returns Hash of the LeafNode.\n */\n public get hash(): string {\n if (this.empty) {\n return HEX_ZERO\n }\n let hex = ''\n for (let iter = 0; iter <= SLOT_MAX; iter++) {\n const child = this.leaves[iter]\n const hash: string = child == null ? HEX_ZERO : child.hash\n hex += hash\n }\n\n const prefix = HashPrefix.INNER_NODE.toString(HEX)\n return sha512Half(prefix + hex)\n }\n\n /**\n * Adds an item to the InnerNode.\n *\n * @param tag - Equates to a ledger entry `index`.\n * @param node - Node to add.\n * @throws If there is a index collision.\n */\n public addItem(tag: string, node: Node): void {\n const existingNode = this.getNode(parseInt(tag[this.depth], HEX))\n\n if (existingNode === undefined) {\n this.setNode(parseInt(tag[this.depth], HEX), node)\n return\n }\n\n // A node already exists in this slot\n if (existingNode instanceof InnerNode) {\n // There is an inner node, so we need to go deeper\n existingNode.addItem(tag, node)\n } else if (existingNode instanceof LeafNode) {\n if (existingNode.tag === tag) {\n // Collision\n throw new XrplError(\n 'Tried to add a node to a SHAMap that was already in there.',\n )\n } else {\n const newInnerNode = new InnerNode(this.depth + 1)\n\n // Parent new and existing node\n newInnerNode.addItem(existingNode.tag, existingNode)\n newInnerNode.addItem(tag, node)\n\n // And place the newly created inner node in the slot\n this.setNode(parseInt(tag[this.depth], HEX), newInnerNode)\n }\n }\n }\n\n /**\n * Overwrite the node that is currently in a given slot.\n *\n * @param slot - A number 0-15.\n * @param node - To place.\n * @throws If slot is out of range.\n */\n public setNode(slot: number, node: Node): void {\n if (slot < 0 || slot > SLOT_MAX) {\n throw new XrplError('Invalid slot: slot must be between 0-15.')\n }\n this.leaves[slot] = node\n this.empty = false\n }\n\n /**\n * Get the node that is currently in a given slot.\n *\n * @param slot - A number 0-15.\n * @returns Node currently in a slot.\n * @throws If slot is out of range.\n */\n public getNode(slot: number): Node | undefined {\n if (slot < 0 || slot > SLOT_MAX) {\n throw new XrplError('Invalid slot: slot must be between 0-15.')\n }\n return this.leaves[slot]\n }\n}\n\nexport default InnerNode\n","import { ValidationError } from '../../errors'\nimport { isFlagEnabled } from '../utils'\n\nimport {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateRequiredField,\n Account,\n validateOptionalField,\n isAccount,\n GlobalFlagsInterface,\n} from './common'\n\n/**\n * Transaction Flags for an MPTokenIssuanceSet Transaction.\n *\n * @category Transaction Flags\n */\nexport enum MPTokenIssuanceSetFlags {\n /**\n * If set, indicates that issuer locks the MPT\n */\n tfMPTLock = 0x00000001,\n /**\n * If set, indicates that issuer unlocks the MPT\n */\n tfMPTUnlock = 0x00000002,\n}\n\n/**\n * Map of flags to boolean values representing {@link MPTokenIssuanceSet} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface MPTokenIssuanceSetFlagsInterface extends GlobalFlagsInterface {\n tfMPTLock?: boolean\n tfMPTUnlock?: boolean\n}\n\n/**\n * The MPTokenIssuanceSet transaction is used to globally lock/unlock a MPTokenIssuance,\n * or lock/unlock an individual's MPToken.\n */\nexport interface MPTokenIssuanceSet extends BaseTransaction {\n TransactionType: 'MPTokenIssuanceSet'\n /**\n * Identifies the MPTokenIssuance\n */\n MPTokenIssuanceID: string\n /**\n * An optional XRPL Address of an individual token holder balance to lock/unlock.\n * If omitted, this transaction will apply to all any accounts holding MPTs.\n */\n Holder?: Account\n Flags?: number | MPTokenIssuanceSetFlagsInterface\n}\n\n/**\n * Verify the form and type of an MPTokenIssuanceSet at runtime.\n *\n * @param tx - An MPTokenIssuanceSet Transaction.\n * @throws When the MPTokenIssuanceSet is Malformed.\n */\nexport function validateMPTokenIssuanceSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n validateRequiredField(tx, 'MPTokenIssuanceID', isString)\n validateOptionalField(tx, 'Holder', isAccount)\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Not necessary\n const flags = (tx.Flags ?? 0) as number | MPTokenIssuanceSetFlagsInterface\n const isTfMPTLock =\n typeof flags === 'number'\n ? isFlagEnabled(flags, MPTokenIssuanceSetFlags.tfMPTLock)\n : flags.tfMPTLock ?? false\n\n const isTfMPTUnlock =\n typeof flags === 'number'\n ? isFlagEnabled(flags, MPTokenIssuanceSetFlags.tfMPTUnlock)\n : flags.tfMPTUnlock ?? false\n\n if (isTfMPTLock && isTfMPTUnlock) {\n throw new ValidationError('MPTokenIssuanceSet: flag conflict')\n }\n}\n","import { ValidationError } from '../../errors'\nimport { AuthorizeCredential } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateCredentialsList,\n MAX_AUTHORIZED_CREDENTIALS,\n} from './common'\n\n/**\n * A DepositPreauth transaction gives another account pre-approval to deliver\n * payments to the sender of this transaction. This is only useful if the sender\n * of this transaction is using (or plans to use) Deposit Authorization.\n *\n * @category Transaction Models\n */\nexport interface DepositPreauth extends BaseTransaction {\n TransactionType: 'DepositPreauth'\n /** The XRP Ledger address of the sender to preauthorize. */\n Authorize?: string\n /**\n * The XRP Ledger address of a sender whose preauthorization should be.\n * revoked.\n */\n Unauthorize?: string\n\n /**\n * The credential(s) to preauthorize.\n */\n AuthorizeCredentials?: AuthorizeCredential[]\n\n /**\n * The credential(s) whose preauthorization should be revoked.\n */\n UnauthorizeCredentials?: AuthorizeCredential[]\n}\n\n/**\n * Verify the form and type of a DepositPreauth at runtime.\n *\n * @param tx - A DepositPreauth Transaction.\n * @throws When the DepositPreauth is malformed.\n */\nexport function validateDepositPreauth(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateSingleAuthorizationFieldProvided(tx)\n\n if (tx.Authorize !== undefined) {\n if (typeof tx.Authorize !== 'string') {\n throw new ValidationError('DepositPreauth: Authorize must be a string')\n }\n\n if (tx.Account === tx.Authorize) {\n throw new ValidationError(\n \"DepositPreauth: Account can't preauthorize its own address\",\n )\n }\n } else if (tx.Unauthorize !== undefined) {\n if (typeof tx.Unauthorize !== 'string') {\n throw new ValidationError('DepositPreauth: Unauthorize must be a string')\n }\n\n if (tx.Account === tx.Unauthorize) {\n throw new ValidationError(\n \"DepositPreauth: Account can't unauthorize its own address\",\n )\n }\n } else if (tx.AuthorizeCredentials !== undefined) {\n validateCredentialsList(\n tx.AuthorizeCredentials,\n tx.TransactionType,\n false,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n } else if (tx.UnauthorizeCredentials !== undefined) {\n validateCredentialsList(\n tx.UnauthorizeCredentials,\n tx.TransactionType,\n false,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n }\n}\n\n// Boolean logic to ensure exactly one of 4 inputs was provided\nfunction validateSingleAuthorizationFieldProvided(\n tx: Record<string, unknown>,\n): void {\n const fields = [\n 'Authorize',\n 'Unauthorize',\n 'AuthorizeCredentials',\n 'UnauthorizeCredentials',\n ]\n const countProvided = fields.filter((key) => tx[key] !== undefined).length\n\n if (countProvided !== 1) {\n throw new ValidationError(\n 'DepositPreauth: Requires exactly one field of the following: Authorize, Unauthorize, AuthorizeCredentials, UnauthorizeCredentials.',\n )\n }\n}\n","import {\n bytesToHex as nobleBytesToHex,\n randomBytes as nobleRandomBytes,\n} from '@noble/hashes/utils'\nimport type {\n BytesToHexFn,\n HexToBytesFn,\n HexToStringFn,\n RandomBytesFn,\n StringToHexFn,\n} from './types'\nimport { HEX_REGEX } from './shared'\n\n/* eslint-disable func-style -- Typed to ensure uniformity between node and browser implementations and docs */\nexport const bytesToHex: typeof BytesToHexFn = (bytes) => {\n const hex = nobleBytesToHex(\n bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes),\n )\n return hex.toUpperCase()\n}\n\n// A clone of hexToBytes from @noble/hashes without the length checks. This allows us to do our own checks.\nexport const hexToBytes: typeof HexToBytesFn = (hex): Uint8Array => {\n const len = hex.length\n const array = new Uint8Array(len / 2)\n if (!HEX_REGEX.test(hex)) {\n throw new Error('Invalid hex string')\n }\n for (let i = 0; i < array.length; i++) {\n const j = i * 2\n const hexByte = hex.slice(j, j + 2)\n const byte = Number.parseInt(hexByte, 16)\n if (Number.isNaN(byte) || byte < 0) {\n throw new Error('Invalid byte sequence')\n }\n array[i] = byte\n }\n return array\n}\n\nexport const hexToString: typeof HexToStringFn = (\n hex: string,\n encoding = 'utf8',\n): string => {\n return new TextDecoder(encoding).decode(hexToBytes(hex))\n}\n\nexport const stringToHex: typeof StringToHexFn = (string: string): string => {\n return bytesToHex(new TextEncoder().encode(string))\n}\n/* eslint-enable func-style */\n\nexport const randomBytes: typeof RandomBytesFn = nobleRandomBytes\nexport * from './shared'\n","import { bytesToHex } from '@xrplf/isomorphic/utils'\nimport BigNumber from 'bignumber.js'\nimport { decodeAccountID } from 'ripple-address-codec'\nimport { decode, encode } from 'ripple-binary-codec'\n\nimport { Transaction } from '../models'\n\n/**\n * If presented in binary form, the Signers array must be sorted based on\n * the numeric value of the signer addresses, with the lowest value first.\n * (If submitted as JSON, the submit_multisigned method handles this automatically.)\n * https://xrpl.org/multi-signing.html.\n *\n * @param left - A Signer to compare with.\n * @param right - A second Signer to compare with.\n * @returns 1 if left \\> right, 0 if left = right, -1 if left \\< right, and null if left or right are NaN.\n */\nexport function compareSigners<T extends { Account: string }>(\n left: T,\n right: T,\n): number {\n return addressToBigNumber(left.Account).comparedTo(\n addressToBigNumber(right.Account),\n )\n}\n\nexport const NUM_BITS_IN_HEX = 16\n\n/**\n * Converts an address to a BigNumber.\n *\n * @param address - The address to convert.\n * @returns A BigNumber representing the address.\n */\nexport function addressToBigNumber(address: string): BigNumber {\n const hex = bytesToHex(decodeAccountID(address))\n return new BigNumber(hex, NUM_BITS_IN_HEX)\n}\n\n/**\n * Decodes a transaction or transaction blob into a Transaction object.\n *\n * @param txOrBlob - A Transaction object or a hex string representing a transaction blob.\n * @returns A Transaction object.\n * @throws If the input is not a valid Transaction or transaction blob.\n */\nexport function getDecodedTransaction(\n txOrBlob: Transaction | string,\n): Transaction {\n if (typeof txOrBlob === 'object') {\n // We need this to handle X-addresses in multisigning\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We are casting here to get strong typing\n return decode(encode(txOrBlob)) as unknown as Transaction\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We are casting here to get strong typing\n return decode(txOrBlob) as unknown as Transaction\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n BaseTransaction,\n isAmount,\n isXChainBridge,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainCreateBridge transaction creates a new {@link Bridge} ledger object\n * and defines a new cross-chain bridge entrance on the chain that the transaction\n * is submitted on. It includes information about door accounts and assets for the\n * bridge.\n *\n * @category Transaction Models\n */\nexport interface XChainCreateBridge extends BaseTransaction {\n TransactionType: 'XChainCreateBridge'\n\n /**\n * The bridge (door accounts and assets) to create.\n */\n XChainBridge: XChainBridge\n\n /**\n * The total amount to pay the witness servers for their signatures. This amount\n * will be split among the signers.\n */\n SignatureReward: Amount\n\n /**\n * The minimum amount, in XRP, required for a {@link XChainAccountCreateCommit}\n * transaction. If this isn't present, the {@link XChainAccountCreateCommit}\n * transaction will fail. This field can only be present on XRP-XRP bridges.\n */\n MinAccountCreateAmount?: Amount\n}\n\n/**\n * Verify the form and type of an XChainCreateBridge at runtime.\n *\n * @param tx - An XChainCreateBridge Transaction.\n * @throws When the XChainCreateBridge is malformed.\n */\nexport function validateXChainCreateBridge(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(tx, 'SignatureReward', isAmount)\n\n validateOptionalField(tx, 'MinAccountCreateAmount', isAmount)\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n */\nimport { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { type CHash, wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x6a09e667 | 0;\n protected Al: number = 0xf3bcc908 | 0;\n protected Bh: number = 0xbb67ae85 | 0;\n protected Bl: number = 0x84caa73b | 0;\n protected Ch: number = 0x3c6ef372 | 0;\n protected Cl: number = 0xfe94f82b | 0;\n protected Dh: number = 0xa54ff53a | 0;\n protected Dl: number = 0x5f1d36f1 | 0;\n protected Eh: number = 0x510e527f | 0;\n protected El: number = 0xade682d1 | 0;\n protected Fh: number = 0x9b05688c | 0;\n protected Fl: number = 0x2b3e6c1f | 0;\n protected Gh: number = 0x1f83d9ab | 0;\n protected Gl: number = 0xfb41bd6b | 0;\n protected Hh: number = 0x5be0cd19 | 0;\n protected Hl: number = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy(): void {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x8c3d37c8 | 0;\n protected Al: number = 0x19544da2 | 0;\n protected Bh: number = 0x73e19966 | 0;\n protected Bl: number = 0x89dcd4d6 | 0;\n protected Ch: number = 0x1dfab7ae | 0;\n protected Cl: number = 0x32ff9c82 | 0;\n protected Dh: number = 0x679dd514 | 0;\n protected Dl: number = 0x582f9fcf | 0;\n protected Eh: number = 0x0f6d2b69 | 0;\n protected El: number = 0x7bd44da8 | 0;\n protected Fh: number = 0x77e36f73 | 0;\n protected Fl: number = 0x04c48942 | 0;\n protected Gh: number = 0x3f9d85a8 | 0;\n protected Gl: number = 0x6a1d36c8 | 0;\n protected Hh: number = 0x1112e6ad | 0;\n protected Hl: number = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x22312194 | 0;\n protected Al: number = 0xfc2bf72c | 0;\n protected Bh: number = 0x9f555fa3 | 0;\n protected Bl: number = 0xc84c64c2 | 0;\n protected Ch: number = 0x2393b86b | 0;\n protected Cl: number = 0x6f53b151 | 0;\n protected Dh: number = 0x96387719 | 0;\n protected Dl: number = 0x5940eabd | 0;\n protected Eh: number = 0x96283ee2 | 0;\n protected El: number = 0xa88effe3 | 0;\n protected Fh: number = 0xbe5e1e25 | 0;\n protected Fl: number = 0x53863992 | 0;\n protected Gh: number = 0x2b0199fc | 0;\n protected Gl: number = 0x2c85b8aa | 0;\n protected Hh: number = 0x0eb72ddc | 0;\n protected Hl: number = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nexport class SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0xcbbb9d5d | 0;\n protected Al: number = 0xc1059ed8 | 0;\n protected Bh: number = 0x629a292a | 0;\n protected Bl: number = 0x367cd507 | 0;\n protected Ch: number = 0x9159015a | 0;\n protected Cl: number = 0x3070dd17 | 0;\n protected Dh: number = 0x152fecd8 | 0;\n protected Dl: number = 0xf70e5939 | 0;\n protected Eh: number = 0x67332667 | 0;\n protected El: number = 0xffc00b31 | 0;\n protected Fh: number = 0x8eb44a87 | 0;\n protected Fl: number = 0x68581511 | 0;\n protected Gh: number = 0xdb0c2e0d | 0;\n protected Gl: number = 0x64f98fa7 | 0;\n protected Hh: number = 0x47b5481d | 0;\n protected Hl: number = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\n/** SHA2-512 hash function. */\nexport const sha512: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512());\n/** SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\n/** SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\n/** SHA2-384 hash function. */\nexport const sha384: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n",";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.1.2\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // THe index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne;\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n =/* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @todo use field version && remove\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000) throw new Error('Cannot find square root: likely non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(order: bigint): <T>(f: IField<T>, x: T) => T {\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return <T>(f: IField<T>, x: T): T => f.pow(x, legendreConst);\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>): (x: T) => boolean {\n const legendre = FpLegendre(f.ORDER);\n return (x: T): boolean => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","import BigNumber from 'bignumber.js'\nimport { decode } from 'ripple-binary-codec'\n\nimport type {\n TransactionEntryResponse,\n TransactionStream,\n TransactionV1Stream,\n TxResponse,\n} from '..'\nimport type {\n Amount,\n IssuedCurrency,\n APIVersion,\n DEFAULT_API_VERSION,\n MPTAmount,\n} from '../models/common'\nimport type {\n AccountTxTransaction,\n RequestResponseMap,\n} from '../models/methods'\nimport { AccountTxVersionResponseMap } from '../models/methods/accountTx'\nimport { BaseRequest, BaseResponse } from '../models/methods/baseMethod'\nimport { PaymentFlags, Transaction, isMPTAmount } from '../models/transactions'\nimport type { TransactionMetadata } from '../models/transactions/metadata'\nimport { isFlagEnabled } from '../models/utils'\n\nconst WARN_PARTIAL_PAYMENT_CODE = 2001\n\n/* eslint-disable complexity -- check different token types */\n/* eslint-disable @typescript-eslint/consistent-type-assertions -- known currency type */\nfunction amountsEqual(\n amt1: Amount | MPTAmount,\n amt2: Amount | MPTAmount,\n): boolean {\n // Compare XRP\n if (typeof amt1 === 'string' && typeof amt2 === 'string') {\n return amt1 === amt2\n }\n\n if (typeof amt1 === 'string' || typeof amt2 === 'string') {\n return false\n }\n\n // Compare MPTs\n if (isMPTAmount(amt1) && isMPTAmount(amt2)) {\n const aValue = new BigNumber(amt1.value)\n const bValue = new BigNumber(amt2.value)\n\n return (\n amt1.mpt_issuance_id === amt2.mpt_issuance_id && aValue.isEqualTo(bValue)\n )\n }\n\n if (isMPTAmount(amt1) || isMPTAmount(amt2)) {\n return false\n }\n\n // Compare issued currency (IOU)\n const aValue = new BigNumber(amt1.value)\n const bValue = new BigNumber(amt2.value)\n\n return (\n (amt1 as IssuedCurrency).currency === (amt2 as IssuedCurrency).currency &&\n (amt1 as IssuedCurrency).issuer === (amt2 as IssuedCurrency).issuer &&\n aValue.isEqualTo(bValue)\n )\n}\n/* eslint-enable complexity */\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n\nfunction isPartialPayment(\n tx?: Transaction,\n metadata?: TransactionMetadata | string,\n): boolean {\n if (tx == null || metadata == null || tx.TransactionType !== 'Payment') {\n return false\n }\n\n let meta = metadata\n if (typeof meta === 'string') {\n if (meta === 'unavailable') {\n return false\n }\n\n /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- binary-codec typing */\n meta = decode(meta) as unknown as TransactionMetadata\n }\n\n const tfPartial =\n typeof tx.Flags === 'number'\n ? isFlagEnabled(tx.Flags, PaymentFlags.tfPartialPayment)\n : tx.Flags?.tfPartialPayment\n\n if (!tfPartial) {\n return false\n }\n\n const delivered = meta.delivered_amount\n\n const amount = tx.DeliverMax ?? tx.Amount\n\n if (delivered === undefined) {\n return false\n }\n\n return !amountsEqual(delivered, amount)\n}\n\nfunction txHasPartialPayment(response: TxResponse): boolean {\n return isPartialPayment(response.result.tx_json, response.result.meta)\n}\n\nfunction txEntryHasPartialPayment(response: TransactionEntryResponse): boolean {\n return isPartialPayment(response.result.tx_json, response.result.metadata)\n}\n\nfunction accountTxHasPartialPayment<\n Version extends APIVersion = typeof DEFAULT_API_VERSION,\n>(response: AccountTxVersionResponseMap<Version>): boolean {\n const { transactions } = response.result\n const foo = transactions.some((tx) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- required to check API version model\n if (tx.tx_json != null) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- use API v2 model\n const transaction = tx as AccountTxTransaction\n return isPartialPayment(transaction.tx_json, transaction.meta)\n }\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- use API v1 model\n const transaction = tx as AccountTxTransaction<1>\n return isPartialPayment(transaction.tx, transaction.meta)\n })\n return foo\n}\n\nfunction hasPartialPayment<\n R extends BaseRequest,\n V extends APIVersion = typeof DEFAULT_API_VERSION,\n T = RequestResponseMap<R, V>,\n>(command: string, response: T): boolean {\n /* eslint-disable @typescript-eslint/consistent-type-assertions -- Request type is known at runtime from command */\n switch (command) {\n case 'tx':\n return txHasPartialPayment(response as TxResponse)\n case 'transaction_entry':\n return txEntryHasPartialPayment(response as TransactionEntryResponse)\n case 'account_tx':\n return accountTxHasPartialPayment(\n response as AccountTxVersionResponseMap<V>,\n )\n default:\n return false\n }\n /* eslint-enable @typescript-eslint/consistent-type-assertions */\n}\n\n/**\n * Checks a response for a partial payment.\n *\n * @param command - Command from the request, tells us what response to expect.\n * @param response - Response to check for a partial payment.\n */\nexport function handlePartialPayment<\n R extends BaseRequest,\n T = RequestResponseMap<R, APIVersion>,\n>(command: string, response: T): void {\n if (hasPartialPayment(command, response)) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We are checking dynamically and safely.\n const warnings = (response as BaseResponse).warnings ?? []\n\n const warning = {\n id: WARN_PARTIAL_PAYMENT_CODE,\n message: 'This response contains a Partial Payment',\n }\n\n warnings.push(warning)\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- We are checking dynamically and safely.\n // @ts-expect-error -- We are checking dynamically and safely.\n response.warnings = warnings\n }\n}\n\n/**\n * Check a transaction from a subscription stream for partial payment.\n *\n * @param stream - Stream Transaction to check for partial payment.\n * @param log - The method used for logging by the connection (to report the partial payment).\n */\nexport function handleStreamPartialPayment(\n stream: TransactionStream | TransactionV1Stream,\n log: (id: string, message: string) => void,\n): void {\n if (isPartialPayment(stream.tx_json ?? stream.transaction, stream.meta)) {\n const warnings = stream.warnings ?? []\n\n const warning = {\n id: WARN_PARTIAL_PAYMENT_CODE,\n message: 'This response contains a Partial Payment',\n }\n\n warnings.push(warning)\n\n /* eslint-disable-next-line no-param-reassign -- Handles the case where there are no warnings */\n stream.warnings = warnings\n\n log('Partial payment received', JSON.stringify(stream))\n }\n}\n","import { AuthorizeCredential } from '../common'\n\nimport {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n validateCredentialsList,\n isArray,\n} from './common'\n\nconst MAX_ACCEPTED_CREDENTIALS = 10\n\nexport interface PermissionedDomainSet extends BaseTransaction {\n /* The transaction type (PermissionedDomainSet). */\n TransactionType: 'PermissionedDomainSet'\n\n /* The domain to modify. Must be included if modifying an existing domain. */\n DomainID?: string\n\n /* The credentials that are accepted by the domain. Ownership of one\n of these credentials automatically makes you a member of the domain.\n An empty array means deleting the field. */\n AcceptedCredentials: AuthorizeCredential[]\n}\n\n/**\n * Validate a PermissionedDomainSet transaction.\n *\n * @param tx - The transaction to validate.\n * @throws {ValidationError} When the transaction is invalid.\n */\nexport function validatePermissionedDomainSet(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n validateOptionalField(tx, 'DomainID', isString)\n validateRequiredField(tx, 'AcceptedCredentials', isArray)\n\n validateCredentialsList(\n tx.AcceptedCredentials,\n tx.TransactionType,\n // PermissionedDomainSet uses AuthorizeCredential nested objects only, strings are not allowed\n false,\n // PermissionedDomainSet uses at most 10 accepted credentials. This is different from Credential-feature transactions.\n MAX_ACCEPTED_CREDENTIALS,\n )\n}\n","/**\n * @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { abytes } from '@noble/hashes/_assert';\nimport { bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { mod } from '@noble/curves/abstract/modular';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.ProjectivePoint;\nconst base58check = createBase58check(sha256);\n\nfunction bytesToNumber(bytes: Uint8Array): bigint {\n abytes(bytes);\n const h = bytes.length === 0 ? '0' : bytesToHex(bytes);\n return BigInt('0x' + h);\n}\n\nfunction numberToBytes(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n return hexToBytes(num.toString(16).padStart(64, '0'));\n}\n\nconst MASTER_SECRET = utf8ToBytes('Bitcoin seed');\n// Bitcoin hardcoded by default\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number) => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array | bigint;\n}\n\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this.privKeyBytes || null;\n }\n get publicKey(): Uint8Array | null {\n return this.pubKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this.pubKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this.pubKey));\n }\n\n public static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n return new HDKey({\n versions,\n chainCode: I.slice(32),\n privateKey: I.slice(0, 32),\n });\n }\n\n public static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n public readonly versions: Versions;\n public readonly depth: number = 0;\n public readonly index: number = 0;\n public readonly chainCode: Uint8Array | null = null;\n public readonly parentFingerprint: number = 0;\n private privKey?: bigint;\n private privKeyBytes?: Uint8Array;\n private pubKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidPrivateKey(opt.privateKey)) {\n throw new Error('Invalid private key');\n }\n this.privKey =\n typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);\n this.privKeyBytes = numberToBytes(this.privKey);\n this.pubKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this.pubKey);\n }\n\n public derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n public deriveChild(index: number): HDKey {\n if (!this.pubKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(new Uint8Array([0]), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this.pubKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = bytesToNumber(I.slice(0, 32));\n const chainCode = I.slice(32);\n if (!secp.utils.isValidPrivateKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n try {\n // Private parent key -> private child key\n if (this.privateKey) {\n const added = mod(this.privKey! + childTweak, secp.CURVE.n);\n if (!secp.utils.isValidPrivateKey(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = added;\n } else {\n const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toRawBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n public sign(hash: Uint8Array): Uint8Array {\n if (!this.privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this.privKey!).toCompactRawBytes();\n }\n\n public verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this.publicKey) {\n throw new Error('No publicKey set!');\n }\n let sig;\n try {\n sig = secp.Signature.fromCompact(signature);\n } catch (error) {\n return false;\n }\n return secp.verify(sig, hash, this.publicKey);\n }\n\n public wipePrivateData(): this {\n this.privKey = undefined;\n if (this.privKeyBytes) {\n this.privKeyBytes.fill(0);\n this.privKeyBytes = undefined;\n }\n return this;\n }\n public toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n","import {\n XrplDefinitionsBase,\n DEFAULT_DEFINITIONS,\n FieldInstance,\n} from '../enums'\nimport { type SerializedType } from '../types/serialized-type'\nimport { hexToBytes } from '@xrplf/isomorphic/utils'\n\n/**\n * BinaryParser is used to compute fields and values from a HexString\n */\nclass BinaryParser {\n private bytes: Uint8Array\n definitions: XrplDefinitionsBase\n\n /**\n * Initialize bytes to a hex string\n *\n * @param hexBytes a hex string\n * @param definitions Rippled definitions used to parse the values of transaction types and such.\n * Can be customized for sidechains and amendments.\n */\n constructor(\n hexBytes: string,\n definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n ) {\n this.bytes = hexToBytes(hexBytes)\n this.definitions = definitions\n }\n\n /**\n * Peek the first byte of the BinaryParser\n *\n * @returns The first byte of the BinaryParser\n */\n peek(): number {\n if (this.bytes.byteLength === 0) {\n throw new Error()\n }\n return this.bytes[0]\n }\n\n /**\n * Consume the first n bytes of the BinaryParser\n *\n * @param n the number of bytes to skip\n */\n skip(n: number): void {\n if (n > this.bytes.byteLength) {\n throw new Error()\n }\n this.bytes = this.bytes.slice(n)\n }\n\n /**\n * read the first n bytes from the BinaryParser\n *\n * @param n The number of bytes to read\n * @return The bytes\n */\n read(n: number): Uint8Array {\n if (n > this.bytes.byteLength) {\n throw new Error()\n }\n\n const slice = this.bytes.slice(0, n)\n this.skip(n)\n return slice\n }\n\n /**\n * Read an integer of given size\n *\n * @param n The number of bytes to read\n * @return The number represented by those bytes\n */\n readUIntN(n: number): number {\n if (0 >= n || n > 4) {\n throw new Error('invalid n')\n }\n return this.read(n).reduce((a, b) => (a << 8) | b) >>> 0\n }\n\n readUInt8(): number {\n return this.readUIntN(1)\n }\n\n readUInt16(): number {\n return this.readUIntN(2)\n }\n\n readUInt32(): number {\n return this.readUIntN(4)\n }\n\n size(): number {\n return this.bytes.byteLength\n }\n\n end(customEnd?: number): boolean {\n const length = this.bytes.byteLength\n return length === 0 || (customEnd !== undefined && length <= customEnd)\n }\n\n /**\n * Reads variable length encoded bytes\n *\n * @return The variable length bytes\n */\n readVariableLength(): Uint8Array {\n return this.read(this.readVariableLengthLength())\n }\n\n /**\n * Reads the length of the variable length encoded bytes\n *\n * @return The length of the variable length encoded bytes\n */\n readVariableLengthLength(): number {\n const b1 = this.readUInt8()\n if (b1 <= 192) {\n return b1\n } else if (b1 <= 240) {\n const b2 = this.readUInt8()\n return 193 + (b1 - 193) * 256 + b2\n } else if (b1 <= 254) {\n const b2 = this.readUInt8()\n const b3 = this.readUInt8()\n return 12481 + (b1 - 241) * 65536 + b2 * 256 + b3\n }\n throw new Error('Invalid variable length indicator')\n }\n\n /**\n * Reads the field ordinal from the BinaryParser\n *\n * @return Field ordinal\n */\n readFieldOrdinal(): number {\n let type = this.readUInt8()\n let nth = type & 15\n type >>= 4\n\n if (type === 0) {\n type = this.readUInt8()\n if (type === 0 || type < 16) {\n throw new Error(\n `Cannot read FieldOrdinal, type_code ${type} out of range`,\n )\n }\n }\n\n if (nth === 0) {\n nth = this.readUInt8()\n if (nth === 0 || nth < 16) {\n throw new Error(\n `Cannot read FieldOrdinal, field_code ${nth} out of range`,\n )\n }\n }\n\n return (type << 16) | nth\n }\n\n /**\n * Read the field from the BinaryParser\n *\n * @return The field represented by the bytes at the head of the BinaryParser\n */\n readField(): FieldInstance {\n return this.definitions.field.fromString(this.readFieldOrdinal().toString())\n }\n\n /**\n * Read a given type from the BinaryParser\n *\n * @param type The type that you want to read from the BinaryParser\n * @return The instance of that type read from the BinaryParser\n */\n readType(type: typeof SerializedType): SerializedType {\n return type.fromParser(this)\n }\n\n /**\n * Get the type associated with a given field\n *\n * @param field The field that you wan to get the type of\n * @return The type associated with the given field\n */\n typeForField(field: FieldInstance): typeof SerializedType {\n return field.associatedType\n }\n\n /**\n * Read value of the type specified by field from the BinaryParser\n *\n * @param field The field that you want to get the associated value for\n * @return The value associated with the given field\n */\n readFieldValue(field: FieldInstance): SerializedType {\n const type = this.typeForField(field)\n if (!type) {\n throw new Error(`unsupported: (${field.name}, ${field.type.name})`)\n }\n const sizeHint = field.isVariableLengthEncoded\n ? this.readVariableLengthLength()\n : undefined\n const value = type.fromParser(this, sizeHint)\n if (value === undefined) {\n throw new Error(\n `fromParser for (${field.name}, ${field.type.name}) -> undefined `,\n )\n }\n return value\n }\n\n /**\n * Get the next field and value from the BinaryParser\n *\n * @return The field and value\n */\n readFieldAndValue(): [FieldInstance, SerializedType] {\n const field = this.readField()\n return [field, this.readFieldValue(field)]\n }\n}\n\nexport { BinaryParser }\n","/* eslint-disable max-classes-per-file -- Needs to be a wrapper for ws */\nimport { EventEmitter } from 'eventemitter3'\n\n// Define the global WebSocket class found on the native browser\ndeclare class WebSocket {\n public onclose?: (closeEvent: CloseEvent) => void\n public onopen?: (openEvent: Event) => void\n public onerror?: (error: Error) => void\n public onmessage?: (message: MessageEvent) => void\n public readyState: number\n public constructor(url: string)\n public close(code?: number, reason?: Uint8Array): void\n public send(message: string): void\n}\n\ninterface WSWrapperOptions {\n perMessageDeflate: boolean\n handshakeTimeout: number\n protocolVersion: number\n origin: string\n maxPayload: number\n followRedirects: boolean\n maxRedirects: number\n}\n\n/**\n * Provides `EventEmitter` interface for native browser `WebSocket`,\n * same, as `ws` package provides.\n */\nexport default class WSWrapper extends EventEmitter {\n public static CONNECTING = 0\n public static OPEN = 1\n public static CLOSING = 2\n\n public static CLOSED = 3\n private readonly ws: WebSocket\n\n /**\n * Constructs a browser-safe websocket.\n *\n * @param url - URL to connect to.\n * @param _protocols - Not used.\n * @param _websocketOptions - Not used.\n */\n public constructor(\n url: string,\n _protocols: string | string[] | WSWrapperOptions | undefined,\n _websocketOptions: WSWrapperOptions,\n ) {\n super()\n\n this.ws = new WebSocket(url)\n\n this.ws.onclose = (closeEvent: CloseEvent): void => {\n let reason: Uint8Array | undefined\n if (closeEvent.reason) {\n const enc = new TextEncoder()\n reason = enc.encode(closeEvent.reason)\n }\n this.emit('close', closeEvent.code, reason)\n }\n\n this.ws.onopen = (): void => {\n this.emit('open')\n }\n\n this.ws.onerror = (error): void => {\n this.emit('error', error)\n }\n\n this.ws.onmessage = (message: MessageEvent): void => {\n this.emit('message', message.data)\n }\n }\n\n /**\n * Get the ready state of the websocket.\n *\n * @returns The Websocket's ready state.\n */\n public get readyState(): number {\n return this.ws.readyState\n }\n\n /**\n * Closes the websocket.\n *\n * @param code - Close code.\n * @param reason - Close reason.\n */\n public close(code?: number, reason?: Buffer): void {\n if (this.readyState === 1) {\n this.ws.close(code, reason)\n }\n }\n\n /**\n * Sends a message over the Websocket connection.\n *\n * @param message - Message to send.\n */\n public send(message: string): void {\n this.ws.send(message)\n }\n}\n","import { ValidationError } from '../../errors'\nimport { Amount, Currency, IssuedCurrencyAmount } from '../common'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n isAmount,\n isIssuedCurrency,\n isIssuedCurrencyAmount,\n validateBaseTransaction,\n} from './common'\n\n/**\n * Enum representing values for AMMWithdrawFlags Transaction Flags.\n *\n * @category Transaction Flags\n */\nexport enum AMMWithdrawFlags {\n tfLPToken = 0x00010000,\n tfWithdrawAll = 0x00020000,\n tfOneAssetWithdrawAll = 0x00040000,\n tfSingleAsset = 0x00080000,\n tfTwoAsset = 0x00100000,\n tfOneAssetLPToken = 0x00200000,\n tfLimitLPToken = 0x00400000,\n}\n\nexport interface AMMWithdrawFlagsInterface extends GlobalFlagsInterface {\n tfLPToken?: boolean\n tfWithdrawAll?: boolean\n tfOneAssetWithdrawAll?: boolean\n tfSingleAsset?: boolean\n tfTwoAsset?: boolean\n tfOneAssetLPToken?: boolean\n tfLimitLPToken?: boolean\n}\n\n/**\n * Withdraw assets from an Automated Market Maker (AMM) instance by returning the AMM's liquidity provider tokens (LP Tokens).\n */\nexport interface AMMWithdraw extends BaseTransaction {\n TransactionType: 'AMMWithdraw'\n\n /**\n * The definition for one of the assets in the AMM's pool.\n */\n Asset: Currency\n\n /**\n * The definition for the other asset in the AMM's pool.\n */\n Asset2: Currency\n\n /**\n * The amount of one asset to withdraw from the AMM.\n * This must match the type of one of the assets (tokens or XRP) in the AMM's pool.\n */\n Amount?: Amount\n\n /**\n * The amount of another asset to withdraw from the AMM.\n * If present, this must match the type of the other asset in the AMM's pool and cannot be the same type as Amount.\n */\n Amount2?: Amount\n\n /**\n * The minimum effective price, in LP Token returned, to pay per unit of the asset to withdraw.\n */\n EPrice?: Amount\n\n /**\n * How many of the AMM's LP Tokens to redeem.\n */\n LPTokenIn?: IssuedCurrencyAmount\n}\n\n/**\n * Verify the form and type of an AMMWithdraw at runtime.\n *\n * @param tx - An AMMWithdraw Transaction.\n * @throws When the AMMWithdraw is Malformed.\n */\nexport function validateAMMWithdraw(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Asset == null) {\n throw new ValidationError('AMMWithdraw: missing field Asset')\n }\n\n if (!isIssuedCurrency(tx.Asset)) {\n throw new ValidationError('AMMWithdraw: Asset must be a Currency')\n }\n\n if (tx.Asset2 == null) {\n throw new ValidationError('AMMWithdraw: missing field Asset2')\n }\n\n if (!isIssuedCurrency(tx.Asset2)) {\n throw new ValidationError('AMMWithdraw: Asset2 must be a Currency')\n }\n\n if (tx.Amount2 != null && tx.Amount == null) {\n throw new ValidationError('AMMWithdraw: must set Amount with Amount2')\n } else if (tx.EPrice != null && tx.Amount == null) {\n throw new ValidationError('AMMWithdraw: must set Amount with EPrice')\n }\n\n if (tx.LPTokenIn != null && !isIssuedCurrencyAmount(tx.LPTokenIn)) {\n throw new ValidationError(\n 'AMMWithdraw: LPTokenIn must be an IssuedCurrencyAmount',\n )\n }\n\n if (tx.Amount != null && !isAmount(tx.Amount)) {\n throw new ValidationError('AMMWithdraw: Amount must be an Amount')\n }\n\n if (tx.Amount2 != null && !isAmount(tx.Amount2)) {\n throw new ValidationError('AMMWithdraw: Amount2 must be an Amount')\n }\n\n if (tx.EPrice != null && !isAmount(tx.EPrice)) {\n throw new ValidationError('AMMWithdraw: EPrice must be an Amount')\n }\n}\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** SHA1 legacy hash class. */\nexport class SHA1 extends HashMD<SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** MD5 legacy hash class. */\nexport class MD5 extends HashMD<MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD<RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new RIPEMD160());\n","/**\n * hash-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380).\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.js';\nimport { type IField, mod } from './modular.js';\nimport type { CHash } from './utils.js';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js';\n\nexport type UnicodeOrBytes = string | Uint8Array;\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type Opts = {\n DST: UnicodeOrBytes;\n p: bigint;\n m: number;\n k: number;\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction anum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n abytes(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport type XY<T> = (\n x: T,\n y: T\n) => {\n x: T;\n y: T;\n};\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: [T[], T[], T[], T[]]): XY<T> {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x: x, y: y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\nexport interface H2CPoint<T> extends Group<H2CPoint<T>> {\n add(rhs: H2CPoint<T>): H2CPoint<T>;\n toAffine(iz?: bigint): AffinePoint<T>;\n clearCofactor(): H2CPoint<T>;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor<T> extends GroupConstructor<H2CPoint<T>> {\n fromAffine(ap: AffinePoint<T>): H2CPoint<T>;\n}\n\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\nexport type HTFMethod<T> = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint<T>;\nexport type MapMethod<T> = (scalars: bigint[]) => H2CPoint<T>;\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher<T>(\n Point: H2CPointConstructor<T>,\n mapToCurve: MapToCurve<T>,\n def: Opts & { encodeDST?: UnicodeOrBytes }\n): {\n hashToCurve: HTFMethod<T>;\n encodeToCurve: HTFMethod<T>;\n mapToCurve: MapMethod<T>;\n} {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts);\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts);\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint<T> {\n if (!Array.isArray(scalars)) throw new Error('mapToCurve: expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('mapToCurve: expected array of bigints');\n const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n","import enums from './definitions.json'\nimport {\n XrplDefinitionsBase,\n FieldInstance,\n Bytes,\n} from './xrpl-definitions-base'\n/**\n * By default, coreTypes from the `types` folder is where known type definitions are initialized to avoid import cycles.\n */\nconst DEFAULT_DEFINITIONS = new XrplDefinitionsBase(enums, {})\n\nconst Type = DEFAULT_DEFINITIONS.type\nconst LedgerEntryType = DEFAULT_DEFINITIONS.ledgerEntryType\nconst TransactionType = DEFAULT_DEFINITIONS.transactionType\nconst TransactionResult = DEFAULT_DEFINITIONS.transactionResult\nconst Field = DEFAULT_DEFINITIONS.field\n\n/*\n * @brief: All valid transaction types\n */\nconst TRANSACTION_TYPES = DEFAULT_DEFINITIONS.transactionNames\n\nexport {\n Bytes,\n XrplDefinitionsBase,\n DEFAULT_DEFINITIONS,\n Field,\n FieldInstance,\n Type,\n LedgerEntryType,\n TransactionResult,\n TransactionType,\n TRANSACTION_TYPES,\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.wordlist = void 0;\nexports.wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","import { BytesList } from '../serdes/binary-serializer'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { XrplDefinitionsBase } from '../enums'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\ntype JSON = string | number | boolean | null | undefined | JSON[] | JsonObject\n\ntype JsonObject = { [key: string]: JSON }\n\n/**\n * The base class for all binary-codec types\n */\nclass SerializedType {\n protected readonly bytes: Uint8Array = new Uint8Array(0)\n\n constructor(bytes?: Uint8Array) {\n this.bytes = bytes ?? new Uint8Array(0)\n }\n\n static fromParser(parser: BinaryParser, hint?: number): SerializedType {\n throw new Error('fromParser not implemented')\n return this.fromParser(parser, hint)\n }\n\n static from(value: SerializedType | JSON | bigint): SerializedType {\n throw new Error('from not implemented')\n return this.from(value)\n }\n\n /**\n * Write the bytes representation of a SerializedType to a BytesList\n *\n * @param list The BytesList to write SerializedType bytes to\n */\n toBytesSink(list: BytesList): void {\n list.put(this.bytes)\n }\n\n /**\n * Get the hex representation of a SerializedType's bytes\n *\n * @returns hex String of this.bytes\n */\n toHex(): string {\n return bytesToHex(this.toBytes())\n }\n\n /**\n * Get the bytes representation of a SerializedType\n *\n * @returns A Uint8Array of the bytes\n */\n toBytes(): Uint8Array {\n if (this.bytes) {\n return this.bytes\n }\n const bytes = new BytesList()\n this.toBytesSink(bytes)\n return bytes.toBytes()\n }\n\n /**\n * Return the JSON representation of a SerializedType\n *\n * @param _definitions rippled definitions used to parse the values of transaction types and such.\n * Unused in default, but used in STObject, STArray\n * Can be customized for sidechains and amendments.\n * @returns any type, if not overloaded returns hexString representation of bytes\n */\n toJSON(_definitions?: XrplDefinitionsBase, _fieldName?: string): JSON {\n return this.toHex()\n }\n\n /**\n * @returns hexString representation of this.bytes\n */\n toString(): string {\n return this.toHex()\n }\n}\n\n/**\n * Base class for SerializedTypes that are comparable.\n *\n * @template T - What types you want to allow comparisons between. You must specify all types. Primarily used to allow\n * comparisons between built-in types (like `string`) and SerializedType subclasses (like `Hash`).\n *\n * Ex. `class Hash extends Comparable<Hash | string>`\n */\nclass Comparable<T extends Object> extends SerializedType {\n lt(other: T): boolean {\n return this.compareTo(other) < 0\n }\n\n eq(other: T): boolean {\n return this.compareTo(other) === 0\n }\n\n gt(other: T): boolean {\n return this.compareTo(other) > 0\n }\n\n gte(other: T): boolean {\n return this.compareTo(other) > -1\n }\n\n lte(other: T): boolean {\n return this.compareTo(other) < 1\n }\n\n /**\n * Overload this method to define how two Comparable SerializedTypes are compared\n *\n * @param other The comparable object to compare this to\n * @returns A number denoting the relationship of this and other\n */\n compareTo(other: T): number {\n throw new Error(`cannot compare ${this.toString()} and ${other.toString()}`)\n }\n}\n\nexport { SerializedType, Comparable, JSON, JsonObject }\n","export const RIPPLED_API_V1 = 1\nexport const RIPPLED_API_V2 = 2\nexport const DEFAULT_API_VERSION = RIPPLED_API_V2\nexport type APIVersion = typeof RIPPLED_API_V1 | typeof RIPPLED_API_V2\nexport type LedgerIndex = number | ('validated' | 'closed' | 'current')\n\nexport interface XRP {\n currency: 'XRP'\n issuer?: never\n}\n\nexport interface IssuedCurrency {\n currency: string\n issuer: string\n}\n\nexport interface MPTCurrency {\n mpt_issuance_id: string\n}\n\nexport type Currency = IssuedCurrency | MPTCurrency | XRP\n\nexport interface IssuedCurrencyAmount extends IssuedCurrency {\n value: string\n}\n\nexport interface MPTAmount {\n mpt_issuance_id: string\n value: string\n}\n\nexport type Amount = IssuedCurrencyAmount | string\n\nexport type ClawbackAmount = IssuedCurrencyAmount | MPTAmount\n\nexport interface Balance {\n currency: string\n issuer?: string\n value: string\n}\n\nexport interface Signer {\n Signer: {\n Account: string\n TxnSignature: string\n SigningPubKey: string\n }\n}\n\nexport interface Memo {\n Memo: {\n MemoData?: string\n MemoType?: string\n MemoFormat?: string\n }\n}\n\nexport type StreamType =\n | 'consensus'\n | 'ledger'\n | 'manifests'\n | 'peer_status'\n | 'transactions'\n | 'transactions_proposed'\n | 'server'\n | 'validations'\n\nexport interface PathStep {\n account?: string\n currency?: string\n issuer?: string\n}\n\nexport type Path = PathStep[]\n\n/**\n * The object that describes the signer in SignerEntries.\n */\nexport interface SignerEntry {\n /**\n * The object that describes the signer in SignerEntries.\n */\n SignerEntry: {\n /**\n * An XRP Ledger address whose signature contributes to the multi-signature.\n * It does not need to be a funded address in the ledger.\n */\n Account: string\n /**\n * The weight of a signature from this signer.\n * A multi-signature is only valid if the sum weight of the signatures provided meets\n * or exceeds the signer list's SignerQuorum value.\n */\n SignerWeight: number\n /**\n * An arbitrary 256-bit (32-byte) field that can be used to identify the signer, which\n * may be useful for smart contracts, or for identifying who controls a key in a large\n * organization.\n */\n WalletLocator?: string\n }\n}\n\n/**\n * This information is added to Transactions in request responses, but is not part\n * of the canonical Transaction information on ledger. These fields are denoted with\n * lowercase letters to indicate this in the rippled responses.\n */\nexport interface ResponseOnlyTxInfo {\n /**\n * The date/time when this transaction was included in a validated ledger.\n */\n date?: number\n /**\n * An identifying hash value unique to this transaction, as a hex string.\n */\n hash?: string\n /**\n * The sequence number of the ledger that included this transaction.\n */\n ledger_index?: number\n /**\n * The hash of the ledger included this transaction.\n */\n ledger_hash?: string\n /**\n * @deprecated Alias for ledger_index.\n */\n inLedger?: number\n}\n\n/**\n * One offer that might be returned from either an {@link NFTBuyOffersRequest}\n * or an {@link NFTSellOffersRequest}.\n *\n * @category Responses\n */\nexport interface NFTOffer {\n amount: Amount\n flags: number\n nft_offer_index: string\n owner: string\n destination?: string\n expiration?: number\n}\n\n/**\n * One NFToken that might be returned from an {@link NFTInfoResponse}\n *\n * @category Responses\n */\nexport interface NFToken {\n nft_id: string\n ledger_index: number\n owner: string\n is_burned: boolean\n flags: number\n transfer_fee: number\n issuer: string\n nft_taxon: number\n nft_serial: number\n uri: string\n}\n\nexport interface AuthAccount {\n AuthAccount: {\n Account: string\n }\n}\n\nexport interface AuthorizeCredential {\n Credential: {\n /** The issuer of the credential. */\n Issuer: string\n\n /** A hex-encoded value to identify the type of credential from the issuer. */\n CredentialType: string\n }\n}\n\nexport interface XChainBridge {\n LockingChainDoor: string\n LockingChainIssue: Currency\n IssuingChainDoor: string\n IssuingChainIssue: Currency\n}\n\n/**\n * A PriceData object represents the price information for a token pair.\n *\n */\nexport interface PriceData {\n PriceData: {\n /**\n * The primary asset in a trading pair. Any valid identifier, such as a stock symbol, bond CUSIP, or currency code is allowed.\n * For example, in the BTC/USD pair, BTC is the base asset; in 912810RR9/BTC, 912810RR9 is the base asset.\n */\n BaseAsset: string\n\n /**\n * The quote asset in a trading pair. The quote asset denotes the price of one unit of the base asset. For example, in the\n * BTC/USD pair,BTC is the base asset; in 912810RR9/BTC, 912810RR9 is the base asset.\n */\n QuoteAsset: string\n\n /**\n * The asset price after applying the Scale precision level. It's not included if the last update transaction didn't include\n * the BaseAsset/QuoteAsset pair.\n */\n AssetPrice?: number | string\n\n /**\n * The scaling factor to apply to an asset price. For example, if Scale is 6 and original price is 0.155, then the scaled\n * price is 155000. Valid scale ranges are 0-10. It's not included if the last update transaction didn't include the\n * BaseAsset/QuoteAsset pair.\n */\n Scale?: number\n }\n}\n","/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * The MPTokenIssuanceDestroy transaction is used to remove an MPTokenIssuance object\n * from the directory node in which it is being held, effectively removing the token\n * from the ledger. If this operation succeeds, the corresponding\n * MPTokenIssuance is removed and the owner’s reserve requirement is reduced by one.\n * This operation must fail if there are any holders who have non-zero balances.\n */\nexport interface MPTokenIssuanceDestroy extends BaseTransaction {\n TransactionType: 'MPTokenIssuanceDestroy'\n /**\n * Identifies the MPTokenIssuance object to be removed by the transaction.\n */\n MPTokenIssuanceID: string\n}\n\n/**\n * Verify the form and type of an MPTokenIssuanceDestroy at runtime.\n *\n * @param tx - An MPTokenIssuanceDestroy Transaction.\n * @throws When the MPTokenIssuanceDestroy is Malformed.\n */\nexport function validateMPTokenIssuanceDestroy(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n validateRequiredField(tx, 'MPTokenIssuanceID', isString)\n}\n","import { UInt } from './uint'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { readUInt16BE, writeUInt16BE } from '../utils'\n\n/**\n * Derived UInt class for serializing/deserializing 16 bit UInt\n */\nclass UInt16 extends UInt {\n protected static readonly width: number = 16 / 8 // 2\n static readonly defaultUInt16: UInt16 = new UInt16(\n new Uint8Array(UInt16.width),\n )\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? UInt16.defaultUInt16.bytes)\n }\n\n static fromParser(parser: BinaryParser): UInt {\n return new UInt16(parser.read(UInt16.width))\n }\n\n /**\n * Construct a UInt16 object from a number\n *\n * @param val UInt16 object or number\n */\n static from<T extends UInt16 | number>(val: T): UInt16 {\n if (val instanceof UInt16) {\n return val\n }\n\n if (typeof val === 'number') {\n UInt16.checkUintRange(val, 0, 0xffff)\n\n const buf = new Uint8Array(UInt16.width)\n writeUInt16BE(buf, val, 0)\n return new UInt16(buf)\n }\n\n throw new Error('Can not construct UInt16 with given value')\n }\n\n /**\n * get the value of a UInt16 object\n *\n * @returns the number represented by this.bytes\n */\n valueOf(): number {\n return parseInt(readUInt16BE(this.bytes, 0))\n }\n}\n\nexport { UInt16 }\n","/* eslint-disable @typescript-eslint/no-magic-numbers -- this file mimics\n behavior in rippled. Magic numbers are used for lengths and conditions */\n/* eslint-disable no-bitwise -- this file mimics behavior in rippled. It uses\n bitwise operators for and-ing numbers with a mask and bit shifting. */\n\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\nimport BigNumber from 'bignumber.js'\nimport { decodeAccountID } from 'ripple-address-codec'\n\nimport hashLedger, {\n hashLedgerHeader,\n hashSignedTx,\n hashTxTree,\n hashStateTree,\n} from './hashLedger'\nimport HashPrefix from './HashPrefix'\nimport ledgerSpaces from './ledgerSpaces'\nimport sha512Half from './sha512Half'\n\nconst HEX = 16\nconst BYTE_LENGTH = 4\n\nfunction addressToHex(address: string): string {\n return bytesToHex(decodeAccountID(address))\n}\n\nfunction ledgerSpaceHex(name: keyof typeof ledgerSpaces): string {\n return ledgerSpaces[name].charCodeAt(0).toString(HEX).padStart(4, '0')\n}\n\nconst MASK = 0xff\nfunction currencyToHex(currency: string): string {\n if (currency.length !== 3) {\n return currency\n }\n\n const bytes = Array(20).fill(0)\n bytes[12] = currency.charCodeAt(0) & MASK\n bytes[13] = currency.charCodeAt(1) & MASK\n bytes[14] = currency.charCodeAt(2) & MASK\n return bytesToHex(Uint8Array.from(bytes))\n}\n\n/**\n * Hash the given binary transaction data with the single-signing prefix.\n *\n * See [Serialization Format](https://xrpl.org/serialization.html).\n *\n * @param txBlobHex - The binary transaction blob as a hexadecimal string.\n * @returns The hash to sign.\n * @category Utilities\n */\nexport function hashTx(txBlobHex: string): string {\n const prefix = HashPrefix.TRANSACTION_SIGN.toString(HEX).toUpperCase()\n return sha512Half(prefix + txBlobHex)\n}\n\n/**\n * Compute AccountRoot Ledger Object Index.\n *\n * All objects in a ledger's state tree have a unique Index.\n * The AccountRoot Ledger Object Index is derived by hashing the\n * address with a namespace identifier. This ensures every\n * Index is unique.\n *\n * See [Ledger Object Indexes](https://xrpl.org/ledger-object-ids.html).\n *\n * @param address - The classic account address.\n * @returns The Ledger Object Index for the account.\n * @category Utilities\n */\nexport function hashAccountRoot(address: string): string {\n return sha512Half(ledgerSpaceHex('account') + addressToHex(address))\n}\n\n/**\n * [SignerList Index Format](https://xrpl.org/signerlist.html#signerlist-id-format).\n *\n * The Index of a SignerList object is the SHA-512Half of the following values, concatenated in order:\n * * The RippleState space key (0x0053)\n * * The AccountID of the owner of the SignerList\n * * The SignerListID (currently always 0).\n *\n * This method computes a SignerList Ledger Object Index.\n *\n * @param address - The classic account address of the SignerList owner (starting with r).\n * @returns The Index of the account's SignerList object.\n * @category Utilities\n */\nexport function hashSignerListId(address: string): string {\n return sha512Half(\n `${ledgerSpaceHex('signerList') + addressToHex(address)}00000000`,\n )\n}\n\n/**\n * [Offer Index Format](https://xrpl.org/offer.html#offer-id-format).\n *\n * The Index of a Offer object is the SHA-512Half of the following values, concatenated in order:\n * * The Offer space key (0x006F)\n * * The AccountID of the account placing the offer\n * * The Sequence number of the OfferCreate transaction that created the offer.\n *\n * This method computes an Offer Index.\n *\n * @param address - The classic account address of the SignerList owner (starting with r).\n * @param sequence - Sequence of the Offer.\n * @returns The Index of the account's Offer object.\n * @category Utilities\n */\nexport function hashOfferId(address: string, sequence: number): string {\n const hexPrefix = ledgerSpaces.offer\n .charCodeAt(0)\n .toString(HEX)\n .padStart(2, '0')\n const hexSequence = sequence.toString(HEX).padStart(8, '0')\n const prefix = `00${hexPrefix}`\n return sha512Half(prefix + addressToHex(address) + hexSequence)\n}\n\n/**\n * Compute the hash of a Trustline.\n *\n * @param address1 - One of the addresses in the Trustline.\n * @param address2 - The other address in the Trustline.\n * @param currency - Currency in the Trustline.\n * @returns The hash of the Trustline.\n * @category Utilities\n */\nexport function hashTrustline(\n address1: string,\n address2: string,\n currency: string,\n): string {\n const address1Hex = addressToHex(address1)\n const address2Hex = addressToHex(address2)\n\n const swap = new BigNumber(address1Hex, 16).isGreaterThan(\n new BigNumber(address2Hex, 16),\n )\n const lowAddressHex = swap ? address2Hex : address1Hex\n const highAddressHex = swap ? address1Hex : address2Hex\n\n const prefix = ledgerSpaceHex('rippleState')\n return sha512Half(\n prefix + lowAddressHex + highAddressHex + currencyToHex(currency),\n )\n}\n\n/**\n * Compute the Hash of an Escrow LedgerEntry.\n *\n * @param address - Address of the Escrow.\n * @param sequence - OfferSequence of the Escrow.\n * @returns The hash of the Escrow LedgerEntry.\n * @category Utilities\n */\nexport function hashEscrow(address: string, sequence: number): string {\n return sha512Half(\n ledgerSpaceHex('escrow') +\n addressToHex(address) +\n sequence.toString(HEX).padStart(BYTE_LENGTH * 2, '0'),\n )\n}\n\n/**\n * Compute the hash of a Payment Channel.\n *\n * @param address - Account of the Payment Channel.\n * @param dstAddress - Destination Account of the Payment Channel.\n * @param sequence - Sequence number of the Transaction that created the Payment Channel.\n * @returns Hash of the Payment Channel.\n * @category Utilities\n */\nexport function hashPaymentChannel(\n address: string,\n dstAddress: string,\n sequence: number,\n): string {\n return sha512Half(\n ledgerSpaceHex('paychan') +\n addressToHex(address) +\n addressToHex(dstAddress) +\n sequence.toString(HEX).padStart(BYTE_LENGTH * 2, '0'),\n )\n}\n\nexport { hashLedgerHeader, hashSignedTx, hashLedger, hashStateTree, hashTxTree }\n","import { ValidationError } from '../../errors'\nimport { PriceData } from '../common'\nimport { isHex } from '../utils'\n\nimport {\n BaseTransaction,\n isArray,\n isNumber,\n isRecord,\n isString,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\nconst PRICE_DATA_SERIES_MAX_LENGTH = 10\nconst SCALE_MAX = 10\nconst MINIMUM_ASSET_PRICE_LENGTH = 1\nconst MAXIMUM_ASSET_PRICE_LENGTH = 16\n\n/**\n * Creates a new Oracle ledger entry or updates the fields of an existing one, using the Oracle ID.\n *\n * The oracle provider must complete these steps before submitting this transaction:\n * 1. Create or own the XRPL account in the Owner field and have enough XRP to meet the reserve and transaction fee requirements.\n * 2. Publish the XRPL account public key, so it can be used for verification by dApps.\n * 3. Publish a registry of available price oracles with their unique OracleDocumentID.\n *\n * @category Transaction Models\n */\nexport interface OracleSet extends BaseTransaction {\n TransactionType: 'OracleSet'\n\n /**\n * A unique identifier of the price oracle for the Account.\n */\n OracleDocumentID: number\n\n /**\n * The time the data was last updated, represented as a unix timestamp in seconds.\n */\n LastUpdateTime: number\n\n /**\n * An array of up to 10 PriceData objects, each representing the price information\n * for a token pair. More than five PriceData objects require two owner reserves.\n */\n PriceDataSeries: PriceData[]\n\n /**\n * An arbitrary value that identifies an oracle provider, such as Chainlink, Band,\n * or DIA. This field is a string, up to 256 ASCII hex encoded characters (0x20-0x7E).\n * This field is required when creating a new Oracle ledger entry, but is optional for updates.\n */\n Provider?: string\n\n /**\n * An optional Universal Resource Identifier to reference price data off-chain. This field is limited to 256 bytes.\n */\n URI?: string\n\n /**\n * Describes the type of asset, such as \"currency\", \"commodity\", or \"index\". This field is a string, up to 16 ASCII\n * hex encoded characters (0x20-0x7E). This field is required when creating a new Oracle ledger entry, but is optional\n * for updates.\n */\n AssetClass?: string\n}\n\n/**\n * Verify the form and type of a OracleSet at runtime.\n *\n * @param tx - A OracleSet Transaction.\n * @throws When the OracleSet is malformed.\n */\n// eslint-disable-next-line max-lines-per-function -- necessary to validate many fields\nexport function validateOracleSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'OracleDocumentID', isNumber)\n\n validateRequiredField(tx, 'LastUpdateTime', isNumber)\n\n validateOptionalField(tx, 'Provider', isString)\n\n validateOptionalField(tx, 'URI', isString)\n\n validateOptionalField(tx, 'AssetClass', isString)\n\n /* eslint-disable max-statements, max-lines-per-function -- necessary to validate many fields */\n validateRequiredField(\n tx,\n 'PriceDataSeries',\n (value: unknown): value is PriceData => {\n if (!isArray(value)) {\n throw new ValidationError('OracleSet: PriceDataSeries must be an array')\n }\n\n if (value.length > PRICE_DATA_SERIES_MAX_LENGTH) {\n throw new ValidationError(\n `OracleSet: PriceDataSeries must have at most ${PRICE_DATA_SERIES_MAX_LENGTH} PriceData objects`,\n )\n }\n\n // TODO: add support for handling inner objects easier (similar to validateRequiredField/validateOptionalField)\n for (const priceData of value) {\n if (!isRecord(priceData)) {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must be an array of objects',\n )\n }\n\n const priceDataInner = priceData.PriceData\n\n if (!isRecord(priceDataInner)) {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must have a `PriceData` object',\n )\n }\n\n // check if priceData only has PriceData\n if (Object.keys(priceData).length !== 1) {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must only have a single PriceData object',\n )\n }\n\n if (\n priceDataInner.BaseAsset == null ||\n typeof priceDataInner.BaseAsset !== 'string'\n ) {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must have a `BaseAsset` string',\n )\n }\n\n if (typeof priceDataInner.QuoteAsset !== 'string') {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must have a `QuoteAsset` string',\n )\n }\n\n // Either AssetPrice and Scale are both present or both excluded\n if (\n (priceDataInner.AssetPrice == null) !==\n (priceDataInner.Scale == null)\n ) {\n throw new ValidationError(\n 'OracleSet: PriceDataSeries must have both `AssetPrice` and `Scale` if any are present',\n )\n }\n\n /* eslint-disable max-depth --\n we need to validate priceDataInner.AssetPrice value */\n if ('AssetPrice' in priceDataInner) {\n if (!isNumber(priceDataInner.AssetPrice)) {\n if (typeof priceDataInner.AssetPrice !== 'string') {\n throw new ValidationError(\n 'OracleSet: Field AssetPrice must be a string or a number',\n )\n }\n if (!isHex(priceDataInner.AssetPrice)) {\n throw new ValidationError(\n 'OracleSet: Field AssetPrice must be a valid hex string',\n )\n }\n if (\n priceDataInner.AssetPrice.length < MINIMUM_ASSET_PRICE_LENGTH ||\n priceDataInner.AssetPrice.length > MAXIMUM_ASSET_PRICE_LENGTH\n ) {\n throw new ValidationError(\n `OracleSet: Length of AssetPrice field must be between ${MINIMUM_ASSET_PRICE_LENGTH} and ${MAXIMUM_ASSET_PRICE_LENGTH} characters long`,\n )\n }\n }\n }\n\n if ('Scale' in priceDataInner) {\n if (!isNumber(priceDataInner.Scale)) {\n throw new ValidationError('OracleSet: invalid field Scale')\n }\n\n if (priceDataInner.Scale < 0 || priceDataInner.Scale > SCALE_MAX) {\n throw new ValidationError(\n `OracleSet: Scale must be in range 0-${SCALE_MAX}`,\n )\n }\n /* eslint-enable max-depth */\n }\n }\n return true\n },\n )\n /* eslint-enable max-statements, max-lines-per-function */\n}\n","import { ValidationError } from '../../errors'\nimport { Amount, Path, MPTAmount } from '../common'\nimport { isFlagEnabled } from '../utils'\n\nimport {\n BaseTransaction,\n isAmount,\n GlobalFlagsInterface,\n validateBaseTransaction,\n isAccount,\n validateRequiredField,\n validateOptionalField,\n isNumber,\n Account,\n validateCredentialsList,\n MAX_AUTHORIZED_CREDENTIALS,\n isArray,\n} from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n/**\n * Enum representing values for Payment Transaction Flags.\n *\n * @category Transaction Flags\n */\nexport enum PaymentFlags {\n /**\n * Do not use the default path; only use paths included in the Paths field.\n * This is intended to force the transaction to take arbitrage opportunities.\n * Most clients do not need this.\n */\n tfNoRippleDirect = 0x00010000,\n /**\n * If the specified Amount cannot be sent without spending more than SendMax,\n * reduce the received amount instead of failing outright. See Partial.\n * Payments for more details.\n */\n tfPartialPayment = 0x00020000,\n /**\n * Only take paths where all the conversions have an input:output ratio that\n * is equal or better than the ratio of Amount:SendMax. See Limit Quality for\n * details.\n */\n tfLimitQuality = 0x00040000,\n}\n\n/**\n * Map of flags to boolean values representing {@link Payment} transaction\n * flags.\n *\n * @category Transaction Flags\n *\n * @example\n * ```typescript\n * const partialPayment: Payment = {\n * TransactionType: 'Payment',\n * Account: 'rM9WCfJU6udpFkvKThRaFHDMsp7L8rpgN',\n * Amount: {\n * currency: 'FOO',\n * value: '4000',\n * issuer: 'rPzwM2JfCSDjhbesdTCqFjWWdK7eFtTwZz',\n * },\n * Destination: 'rPzwM2JfCSDjhbesdTCqFjWWdK7eFtTwZz',\n * Flags: {\n * tfPartialPayment: true\n * }\n * }\n *\n * // Autofill the tx to see how flags actually look compared to the interface usage.\n * const autofilledTx = await client.autofill(partialPayment)\n * console.log(autofilledTx)\n * // {\n * // TransactionType: 'Payment',\n * // Account: 'rM9WCfJU6udpFkvKThRaFHDMsp7L8rpgN',\n * // Amount: {\n * // currency: 'FOO',\n * // value: '4000',\n * // issuer: 'rPzwM2JfCSDjhbesdTCqFjWWdK7eFtTwZz'\n * // },\n * // Destination: 'rPzwM2JfCSDjhbesdTCqFjWWdK7eFtTwZz',\n * // Flags: 131072,\n * // Sequence: 21970996,\n * // Fee: '12',\n * // LastLedgerSequence: 21971016\n * // }\n * ```\n */\nexport interface PaymentFlagsInterface extends GlobalFlagsInterface {\n /**\n * Do not use the default path; only use paths included in the Paths field.\n * This is intended to force the transaction to take arbitrage opportunities.\n * Most clients do not need this.\n */\n tfNoRippleDirect?: boolean\n /**\n * If the specified Amount cannot be sent without spending more than SendMax,\n * reduce the received amount instead of failing outright. See Partial.\n * Payments for more details.\n */\n tfPartialPayment?: boolean\n /**\n * Only take paths where all the conversions have an input:output ratio that\n * is equal or better than the ratio of Amount:SendMax. See Limit Quality for\n * details.\n */\n tfLimitQuality?: boolean\n}\n\n/**\n * A Payment transaction represents a transfer of value from one account to\n * another.\n *\n * @category Transaction Models\n */\nexport interface Payment extends BaseTransaction {\n TransactionType: 'Payment'\n /**\n * The amount of currency to deliver. For non-XRP amounts, the nested field\n * names MUST be lower-case. If the tfPartialPayment flag is set, deliver up\n * to this amount instead.\n */\n Amount: Amount | MPTAmount\n\n DeliverMax?: Amount | MPTAmount\n\n /** The unique address of the account receiving the payment. */\n Destination: Account\n /**\n * Arbitrary tag that identifies the reason for the payment to the\n * destination, or a hosted recipient to pay.\n */\n DestinationTag?: number\n /**\n * Arbitrary 256-bit hash representing a specific reason or identifier for\n * this payment.\n */\n InvoiceID?: string\n /**\n * Array of payment paths to be used for this transaction. Must be omitted\n * for XRP-to-XRP transactions.\n */\n Paths?: Path[]\n /**\n * Highest amount of source currency this transaction is allowed to cost,\n * including transfer fees, exchange rates, and slippage . Does not include\n * the XRP destroyed as a cost for submitting the transaction. For non-XRP\n * amounts, the nested field names MUST be lower-case. Must be supplied for\n * cross-currency/cross-issue payments. Must be omitted for XRP-to-XRP\n * Payments.\n */\n SendMax?: Amount | MPTAmount\n /**\n * Minimum amount of destination currency this transaction should deliver.\n * Only valid if this is a partial payment. For non-XRP amounts, the nested\n * field names are lower-case.\n */\n DeliverMin?: Amount | MPTAmount\n /**\n * Credentials associated with the sender of this transaction.\n * The credentials included must not be expired.\n */\n CredentialIDs?: string[]\n Flags?: number | PaymentFlagsInterface\n}\n\nexport interface PaymentMetadata extends TransactionMetadataBase {\n DeliveredAmount?: Amount | MPTAmount\n delivered_amount?: Amount | MPTAmount | 'unavailable'\n}\n\n/**\n * Verify the form and type of a Payment at runtime.\n *\n * @param tx - A Payment Transaction.\n * @throws When the Payment is malformed.\n */\nexport function validatePayment(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Amount === undefined) {\n throw new ValidationError('PaymentTransaction: missing field Amount')\n }\n\n if (!isAmount(tx.Amount)) {\n throw new ValidationError('PaymentTransaction: invalid Amount')\n }\n\n validateRequiredField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n validateCredentialsList(\n tx.CredentialIDs,\n tx.TransactionType,\n true,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n\n if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== 'string') {\n throw new ValidationError('PaymentTransaction: InvoiceID must be a string')\n }\n\n if (tx.Paths !== undefined && !isPaths(tx.Paths)) {\n throw new ValidationError('PaymentTransaction: invalid Paths')\n }\n\n if (tx.SendMax !== undefined && !isAmount(tx.SendMax)) {\n throw new ValidationError('PaymentTransaction: invalid SendMax')\n }\n\n checkPartialPayment(tx)\n\n if (tx.DeliverMax != null) {\n throw new ValidationError(\n 'PaymentTransaction: Cannot have DeliverMax in a submitted transaction',\n )\n }\n}\n\nfunction checkPartialPayment(tx: Record<string, unknown>): void {\n if (tx.DeliverMin != null) {\n if (tx.Flags == null) {\n throw new ValidationError(\n 'PaymentTransaction: tfPartialPayment flag required with DeliverMin',\n )\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS\n const flags = tx.Flags as number | PaymentFlagsInterface\n const isTfPartialPayment =\n typeof flags === 'number'\n ? isFlagEnabled(flags, PaymentFlags.tfPartialPayment)\n : flags.tfPartialPayment ?? false\n\n if (!isTfPartialPayment) {\n throw new ValidationError(\n 'PaymentTransaction: tfPartialPayment flag required with DeliverMin',\n )\n }\n\n if (!isAmount(tx.DeliverMin)) {\n throw new ValidationError('PaymentTransaction: invalid DeliverMin')\n }\n }\n}\n\nfunction isPathStep(pathStep: Record<string, unknown>): boolean {\n if (pathStep.account !== undefined && typeof pathStep.account !== 'string') {\n return false\n }\n if (\n pathStep.currency !== undefined &&\n typeof pathStep.currency !== 'string'\n ) {\n return false\n }\n if (pathStep.issuer !== undefined && typeof pathStep.issuer !== 'string') {\n return false\n }\n if (\n pathStep.account !== undefined &&\n pathStep.currency === undefined &&\n pathStep.issuer === undefined\n ) {\n return true\n }\n if (pathStep.currency !== undefined || pathStep.issuer !== undefined) {\n return true\n }\n return false\n}\n\nfunction isPath(path: unknown): path is Path {\n if (!Array.isArray(path) || path.length === 0) {\n return false\n }\n for (const pathStep of path) {\n if (!isPathStep(pathStep)) {\n return false\n }\n }\n return true\n}\n\nfunction isPaths(paths: unknown): paths is Path[] {\n if (!isArray(paths) || paths.length === 0) {\n return false\n }\n\n for (const path of paths) {\n if (!isArray(path) || path.length === 0) {\n return false\n }\n\n if (!isPath(path)) {\n return false\n }\n }\n\n return true\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/* eslint-disable max-lines -- lots of helper functions needed for autofill */\nimport BigNumber from 'bignumber.js'\nimport { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'\n\nimport { type Client } from '..'\nimport { ValidationError, XrplError } from '../errors'\nimport { AccountInfoRequest, AccountObjectsRequest } from '../models/methods'\nimport { Batch, Payment, Transaction } from '../models/transactions'\nimport { xrpToDrops } from '../utils'\n\nimport getFeeXrp from './getFeeXrp'\n\n// Expire unconfirmed transactions after 20 ledger versions, approximately 1 minute, by default\nconst LEDGER_OFFSET = 20\n// Sidechains are expected to have network IDs above this.\n// Networks with ID above this restricted number are expected specify an accurate NetworkID field\n// in every transaction to that chain to prevent replay attacks.\n// Mainnet and testnet are exceptions. More context: https://github.com/XRPLF/rippled/pull/4370\nconst RESTRICTED_NETWORKS = 1024\nconst REQUIRED_NETWORKID_VERSION = '1.11.0'\n\nconst MICRO_DROPS_PER_DROP = 1_000_000\n\n/**\n * Determines whether the source rippled version is not later than the target rippled version.\n * Example usage: isNotLaterRippledVersion('1.10.0', '1.11.0') returns true.\n * isNotLaterRippledVersion('1.10.0', '1.10.0-b1') returns false.\n *\n * @param source -- The source rippled version.\n * @param target -- The target rippled version.\n * @returns True if source is earlier than target, false otherwise.\n */\n// eslint-disable-next-line max-lines-per-function, max-statements -- Disable for this helper functions.\nfunction isNotLaterRippledVersion(source: string, target: string): boolean {\n if (source === target) {\n return true\n }\n const sourceDecomp = source.split('.')\n const targetDecomp = target.split('.')\n const sourceMajor = parseInt(sourceDecomp[0], 10)\n const sourceMinor = parseInt(sourceDecomp[1], 10)\n const targetMajor = parseInt(targetDecomp[0], 10)\n const targetMinor = parseInt(targetDecomp[1], 10)\n // Compare major version\n if (sourceMajor !== targetMajor) {\n return sourceMajor < targetMajor\n }\n // Compare minor version\n if (sourceMinor !== targetMinor) {\n return sourceMinor < targetMinor\n }\n const sourcePatch = sourceDecomp[2].split('-')\n const targetPatch = targetDecomp[2].split('-')\n\n const sourcePatchVersion = parseInt(sourcePatch[0], 10)\n const targetPatchVersion = parseInt(targetPatch[0], 10)\n\n // Compare patch version\n if (sourcePatchVersion !== targetPatchVersion) {\n return sourcePatchVersion < targetPatchVersion\n }\n\n // Compare release version\n if (sourcePatch.length !== targetPatch.length) {\n return sourcePatch.length > targetPatch.length\n }\n\n if (sourcePatch.length === 2) {\n // Compare different release types\n if (!sourcePatch[1][0].startsWith(targetPatch[1][0])) {\n return sourcePatch[1] < targetPatch[1]\n }\n // Compare beta version\n if (sourcePatch[1].startsWith('b')) {\n return (\n parseInt(sourcePatch[1].slice(1), 10) <\n parseInt(targetPatch[1].slice(1), 10)\n )\n }\n // Compare rc version\n return (\n parseInt(sourcePatch[1].slice(2), 10) <\n parseInt(targetPatch[1].slice(2), 10)\n )\n }\n\n return false\n}\n\n/**\n * Determine if the transaction required a networkID to be valid.\n * Transaction needs networkID if later than restricted ID and build version is >= 1.11.0\n *\n * @param client -- The connected client.\n * @returns True if required networkID, false otherwise.\n */\nexport function txNeedsNetworkID(client: Client): boolean {\n if (\n client.networkID !== undefined &&\n client.networkID > RESTRICTED_NETWORKS\n ) {\n if (\n client.buildVersion &&\n isNotLaterRippledVersion(REQUIRED_NETWORKID_VERSION, client.buildVersion)\n ) {\n return true\n }\n }\n return false\n}\n\ninterface ClassicAccountAndTag {\n classicAccount: string\n tag: number | false | undefined\n}\n\n/**\n * Sets valid addresses for the transaction.\n *\n * @param tx - The transaction object.\n */\nexport function setValidAddresses(tx: Transaction): void {\n validateAccountAddress(tx, 'Account', 'SourceTag')\n // eslint-disable-next-line @typescript-eslint/dot-notation -- Destination can exist on Transaction\n if (tx['Destination'] != null) {\n validateAccountAddress(tx, 'Destination', 'DestinationTag')\n }\n\n // DepositPreauth:\n convertToClassicAddress(tx, 'Authorize')\n convertToClassicAddress(tx, 'Unauthorize')\n // EscrowCancel, EscrowFinish:\n convertToClassicAddress(tx, 'Owner')\n // SetRegularKey:\n convertToClassicAddress(tx, 'RegularKey')\n}\n\n/**\n * Validates the account address in a transaction object.\n *\n * @param tx - The transaction object.\n * @param accountField - The field name for the account address in the transaction object.\n * @param tagField - The field name for the tag in the transaction object.\n * @throws {ValidationError} If the tag field does not match the tag of the account address.\n */\nfunction validateAccountAddress(\n tx: Transaction,\n accountField: string,\n tagField: string,\n): void {\n // if X-address is given, convert it to classic address\n const { classicAccount, tag } = getClassicAccountAndTag(\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- okay here\n tx[accountField] as string,\n )\n // eslint-disable-next-line no-param-reassign -- param reassign is safe\n tx[accountField] = classicAccount\n\n if (tag != null && tag !== false) {\n if (tx[tagField] && tx[tagField] !== tag) {\n throw new ValidationError(\n `The ${tagField}, if present, must match the tag of the ${accountField} X-address`,\n )\n }\n // eslint-disable-next-line no-param-reassign -- param reassign is safe\n tx[tagField] = tag\n }\n}\n\n/**\n * Retrieves the classic account and tag from an account address.\n *\n * @param account - The account address.\n * @param [expectedTag] - The expected tag for the account address.\n * @returns The classic account and tag.\n * @throws {ValidationError} If the address includes a tag that does not match the tag specified in the transaction.\n */\nfunction getClassicAccountAndTag(\n account: string,\n expectedTag?: number,\n): ClassicAccountAndTag {\n if (isValidXAddress(account)) {\n const classic = xAddressToClassicAddress(account)\n if (expectedTag != null && classic.tag !== expectedTag) {\n throw new ValidationError(\n 'address includes a tag that does not match the tag specified in the transaction',\n )\n }\n return {\n classicAccount: classic.classicAddress,\n tag: classic.tag,\n }\n }\n return {\n classicAccount: account,\n tag: expectedTag,\n }\n}\n\n/**\n * Converts the specified field of a transaction object to a classic address format.\n *\n * @param tx - The transaction object.\n * @param fieldName - The name of the field to convert.export\n */\nfunction convertToClassicAddress(tx: Transaction, fieldName: string): void {\n const account = tx[fieldName]\n if (typeof account === 'string') {\n const { classicAccount } = getClassicAccountAndTag(account)\n // eslint-disable-next-line no-param-reassign -- param reassign is safe\n tx[fieldName] = classicAccount\n }\n}\n\n// Helper function to get the next valid sequence number for an account.\nasync function getNextValidSequenceNumber(\n client: Client,\n account: string,\n): Promise<number> {\n const request: AccountInfoRequest = {\n command: 'account_info',\n account,\n ledger_index: 'current',\n }\n const data = await client.request(request)\n return data.result.account_data.Sequence\n}\n\n/**\n * Sets the next valid sequence number for a transaction.\n *\n * @param client - The client object used for making requests.\n * @param tx - The transaction object for which the sequence number needs to be set.\n * @returns A Promise that resolves when the sequence number is set.\n * @throws {Error} If there is an error retrieving the account information.\n */\nexport async function setNextValidSequenceNumber(\n client: Client,\n tx: Transaction,\n): Promise<void> {\n // eslint-disable-next-line no-param-reassign, require-atomic-updates -- param reassign is safe with no race condition\n tx.Sequence = await getNextValidSequenceNumber(client, tx.Account)\n}\n\n/**\n * Fetches the owner reserve fee from the server state using the provided client.\n *\n * @param client - The client object used to make the request.\n * @returns A Promise that resolves to the owner reserve fee as a BigNumber.\n * @throws {Error} Throws an error if the owner reserve fee cannot be fetched.\n */\nasync function fetchOwnerReserveFee(client: Client): Promise<BigNumber> {\n const response = await client.request({ command: 'server_state' })\n const fee = response.result.state.validated_ledger?.reserve_inc\n\n if (fee == null) {\n return Promise.reject(new Error('Could not fetch Owner Reserve.'))\n }\n\n return new BigNumber(fee)\n}\n\nasync function fetchGasPrice(client: Client): Promise<BigNumber> {\n const response = await client.request({ command: 'server_state' })\n const gasPrice = response.result.state.validated_ledger?.gas_price\n\n if (gasPrice == null) {\n return Promise.reject(new Error('Could not fetch Owner Reserve.'))\n }\n\n return new BigNumber(gasPrice)\n}\n\n/**\n * Calculates the fee per transaction type.\n *\n * @param client - The client object.\n * @param tx - The transaction object.\n * @param [signersCount=0] - The number of signers (default is 0). Only used for multisigning.\n * @returns A promise that returns the fee.\n */\n// eslint-disable-next-line max-lines-per-function -- needed here due to the complexity of the fee calculation\nasync function calculateFeePerTransactionType(\n client: Client,\n tx: Transaction,\n signersCount = 0,\n): Promise<BigNumber> {\n const netFeeXRP = await getFeeXrp(client)\n const netFeeDrops = new BigNumber(xrpToDrops(netFeeXRP))\n let baseFee = netFeeDrops\n\n const isSpecialTxCost = ['AccountDelete', 'AMMCreate'].includes(\n tx.TransactionType,\n )\n\n // EscrowCreate transaction with FinishFunction\n if (tx.TransactionType === 'EscrowCreate' && tx.FinishFunction != null) {\n baseFee = baseFee.plus(1000)\n } else if (tx.TransactionType === 'EscrowFinish') {\n // EscrowFinish Transaction with Fulfillment/ComputationAllowance\n if (tx.Fulfillment != null) {\n const fulfillmentBytesSize: number = Math.ceil(tx.Fulfillment.length / 2)\n // BaseFee × (33 + (Fulfillment size in bytes / 16))\n baseFee = netFeeDrops.multipliedBy(\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers -- expected use of magic numbers\n 33 + fulfillmentBytesSize / 16,\n )\n }\n if (tx.ComputationAllowance != null) {\n const gasPrice = await fetchGasPrice(client)\n const extraFee: BigNumber = gasPrice\n .multipliedBy(tx.ComputationAllowance)\n .dividedBy(MICRO_DROPS_PER_DROP)\n baseFee = baseFee.plus(extraFee)\n }\n } else if (tx.TransactionType === 'Batch') {\n const rawTxFees = await tx.RawTransactions.reduce(async (acc, rawTxn) => {\n const resolvedAcc = await acc\n const fee = await calculateFeePerTransactionType(\n client,\n rawTxn.RawTransaction,\n )\n return BigNumber.sum(resolvedAcc, fee)\n }, Promise.resolve(new BigNumber(0)))\n baseFee = BigNumber.sum(baseFee.times(2), rawTxFees)\n } else if (isSpecialTxCost) {\n baseFee = await fetchOwnerReserveFee(client)\n }\n\n /*\n * Multi-signed Transaction\n * BaseFee × (1 + Number of Signatures Provided)\n */\n if (signersCount > 0) {\n baseFee = BigNumber.sum(baseFee, netFeeDrops.multipliedBy(signersCount))\n }\n\n const maxFeeDrops = xrpToDrops(client.maxFeeXRP)\n const totalFee = isSpecialTxCost\n ? baseFee\n : BigNumber.min(baseFee, maxFeeDrops)\n\n // Round up baseFee and return it as a string\n return totalFee.dp(0, BigNumber.ROUND_CEIL)\n}\n\n/**\n * Calculates the fee per transaction type and sets it in the transaction.\n *\n * @param client - The client object.\n * @param tx - The transaction object.\n * @param [signersCount=0] - The number of signers (default is 0). Only used for multisigning.\n * @returns A promise that resolves with void. Modifies the `tx` parameter to give it the calculated fee.\n */\nexport async function getTransactionFee(\n client: Client,\n tx: Transaction,\n signersCount = 0,\n): Promise<void> {\n const fee = await calculateFeePerTransactionType(client, tx, signersCount)\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers, require-atomic-updates, no-param-reassign -- fine here\n tx.Fee = fee.toString(10)\n}\n\n/**\n * Sets the latest validated ledger sequence for the transaction.\n *\n * @param client - The client object.\n * @param tx - The transaction object.\n * @returns A promise that resolves with void. Modifies the `tx` parameter setting `LastLedgerSequence`.\n */\nexport async function setLatestValidatedLedgerSequence(\n client: Client,\n tx: Transaction,\n): Promise<void> {\n const ledgerSequence = await client.getLedgerIndex()\n // eslint-disable-next-line no-param-reassign -- param reassign is safe\n tx.LastLedgerSequence = ledgerSequence + LEDGER_OFFSET\n}\n\n/**\n * Checks for any blockers that prevent the deletion of an account.\n *\n * @param client - The client object.\n * @param tx - The transaction object.\n * @returns A promise that resolves with void if there are no blockers, or rejects with an XrplError if there are blockers.\n */\nexport async function checkAccountDeleteBlockers(\n client: Client,\n tx: Transaction,\n): Promise<void> {\n const request: AccountObjectsRequest = {\n command: 'account_objects',\n account: tx.Account,\n ledger_index: 'validated',\n deletion_blockers_only: true,\n }\n const response = await client.request(request)\n return new Promise((resolve, reject) => {\n if (response.result.account_objects.length > 0) {\n reject(\n new XrplError(\n `Account ${tx.Account} cannot be deleted; there are Escrows, PayChannels, RippleStates, or Checks associated with the account.`,\n response.result.account_objects,\n ),\n )\n }\n resolve()\n })\n}\n\n/**\n * Replaces Amount with DeliverMax if needed.\n *\n * @param tx - The transaction object.\n * @throws ValidationError if Amount and DeliverMax are both provided but do not match.\n */\nexport function handleDeliverMax(tx: Payment): void {\n if (tx.DeliverMax != null) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed here\n if (tx.Amount == null) {\n // If only DeliverMax is provided, use it to populate the Amount field\n // eslint-disable-next-line no-param-reassign -- known RPC-level property\n tx.Amount = tx.DeliverMax\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed here\n if (tx.Amount != null && tx.Amount !== tx.DeliverMax) {\n throw new ValidationError(\n 'PaymentTransaction: Amount and DeliverMax fields must be identical when both are provided',\n )\n }\n\n // eslint-disable-next-line no-param-reassign -- needed here\n delete tx.DeliverMax\n }\n}\n\n/**\n * Autofills all the relevant `x` fields.\n *\n * @param client - The client object.\n * @param tx - The transaction object.\n * @returns A promise that resolves with void if there are no blockers, or rejects with an XrplError if there are blockers.\n */\n// eslint-disable-next-line complexity, max-lines-per-function -- needed here, lots to check\nexport async function autofillBatchTxn(\n client: Client,\n tx: Batch,\n): Promise<void> {\n const accountSequences: Record<string, number> = {}\n\n for await (const rawTxn of tx.RawTransactions) {\n const txn = rawTxn.RawTransaction\n\n // Sequence processing\n if (txn.Sequence == null && txn.TicketSequence == null) {\n if (txn.Account in accountSequences) {\n txn.Sequence = accountSequences[txn.Account]\n accountSequences[txn.Account] += 1\n } else {\n const nextSequence = await getNextValidSequenceNumber(\n client,\n txn.Account,\n )\n const sequence =\n txn.Account === tx.Account ? nextSequence + 1 : nextSequence\n accountSequences[txn.Account] = sequence + 1\n txn.Sequence = sequence\n }\n }\n\n if (txn.Fee == null) {\n txn.Fee = '0'\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed for JS checks\n } else if (txn.Fee !== '0') {\n throw new XrplError('Must have `Fee of \"0\" in inner Batch transaction.')\n }\n\n if (txn.SigningPubKey == null) {\n txn.SigningPubKey = ''\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed for JS checks\n } else if (txn.SigningPubKey !== '') {\n throw new XrplError(\n 'Must have `SigningPubKey` of \"\" in inner Batch transaction.',\n )\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed for JS checks\n if (txn.TxnSignature != null) {\n throw new XrplError(\n 'Must not have `TxnSignature` in inner Batch transaction.',\n )\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- needed for JS checks\n if (txn.Signers != null) {\n throw new XrplError('Must not have `Signers` in inner Batch transaction.')\n }\n\n if (txn.NetworkID == null && txNeedsNetworkID(client)) {\n txn.NetworkID = client.networkID\n }\n }\n}\n","import { concatBytes } from '@noble/hashes/utils'\n\nexport const HEX_REGEX = /^[A-F0-9]*$/iu\n\nexport function concat(views: Uint8Array[]): Uint8Array {\n return concatBytes(...views)\n}\n\nexport function equal(buf1: Uint8Array, buf2: Uint8Array): boolean {\n if (buf1.byteLength !== buf2.byteLength) {\n return false\n }\n const dv1 = new Int8Array(buf1)\n const dv2 = new Int8Array(buf2)\n for (let i = 0; i !== buf1.byteLength; i++) {\n if (dv1[i] !== dv2[i]) {\n return false\n }\n }\n return true\n}\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder<F, T> {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder<Uint8Array, string> {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like <string, number>, <number, bytes>, <bytes, float>\ntype Chain = [Coder<any, any>, ...Coder<any, any>[]];\n// Extract info from Coder type\ntype Input<F> = F extends Coder<infer T, any> ? T : never;\ntype Output<F> = F extends Coder<any, infer T> ? T : never;\n// Generic function for arrays\ntype First<T> = T extends [infer U, ...any[]] ? U : never;\ntype Last<T> = T extends [...any[], infer U] ? U : never;\ntype Tail<T> = T extends [any, ...infer U] ? U : never;\n\ntype AsChain<C extends Chain, Rest = Tail<C>> = {\n // C[K] = Coder<Input<C[K]>, Input<Rest[k]>>\n [K in keyof C]: Coder<Input<C[K]>, Input<K extends keyof Rest ? Rest[K] : any>>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>, Output<Last<T>>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder<number[], string[]> {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder<string[], string> {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder<string[], string[]> {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize<T>(fn: (val: T) => T): Coder<T, T> {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder<Uint8Array, number[]> {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder<Uint8Array, number[]> {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper<T extends (...args: any) => any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes<T>): ReturnType<T> | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder<Uint8Array, Uint8Array> {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded<Prefix extends string = string> {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray<Prefix extends string = string> {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder<number[], string> = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode<Prefix extends string>(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase<Prefix>}1${string}`;\n decode<Prefix extends string>(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded<Prefix>;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode<Prefix extends string>(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase<Prefix>}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase<Prefix>}1${string}`;\n }\n\n function decode<Prefix extends string>(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded<Prefix>;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n","import { ripemd160 as nobleImpl } from '@noble/hashes/ripemd160'\n\nimport wrapNoble from '../internal/wrapNoble'\n\n/**\n * Wrap noble-libs's ripemd160 implementation in HashFn\n */\nexport const ripemd160 = wrapNoble(nobleImpl)\n","import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, validateBaseTransaction } from './common'\n\n/**\n * A SetRegularKey transaction assigns, changes, or removes the regular key\n * pair associated with an account.\n *\n * @category Transaction Models\n */\nexport interface SetRegularKey extends BaseTransaction {\n TransactionType: 'SetRegularKey'\n /**\n * A base-58-encoded Address that indicates the regular key pair to be\n * assigned to the account. If omitted, removes any existing regular key pair.\n * from the account. Must not match the master key pair for the address.\n */\n RegularKey?: string\n}\n\n/**\n * Verify the form and type of a SetRegularKey at runtime.\n *\n * @param tx - A SetRegularKey Transaction.\n * @throws When the SetRegularKey is malformed.\n */\nexport function validateSetRegularKey(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.RegularKey !== undefined && typeof tx.RegularKey !== 'string') {\n throw new ValidationError('SetRegularKey: RegularKey must be a string')\n }\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isNumber,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * Create a unidirectional channel and fund it with XRP. The address sending\n * this transaction becomes the \"source address\" of the payment channel.\n *\n * @category Transaction Models\n */\nexport interface PaymentChannelCreate extends BaseTransaction {\n TransactionType: 'PaymentChannelCreate'\n /**\n * Amount of XRP, in drops, to deduct from the sender's balance and set aside\n * in this channel. While the channel is open, the XRP can only go to the\n * Destination address. When the channel closes, any unclaimed XRP is returned\n * to the source address's balance.\n */\n Amount: string\n /**\n * Address to receive XRP claims against this channel. This is also known as\n * the \"destination address\" for the channel.\n */\n Destination: Account\n /**\n * Amount of time the source address must wait before closing the channel if\n * it has unclaimed XRP.\n */\n SettleDelay: number\n /**\n * The public key of the key pair the source will use to sign claims against\n * this channel in hexadecimal. This can be any secp256k1 or ed25519 public\n * key.\n */\n PublicKey: string\n /**\n * The time, in seconds since the Ripple Epoch, when this channel expires.\n * Any transaction that would modify the channel after this time closes the\n * channel without otherwise affecting it. This value is immutable; the\n * channel can be closed earlier than this time but cannot remain open after\n * this time.\n */\n CancelAfter?: number\n /**\n * Arbitrary tag to further specify the destination for this payment channel,\n * such as a hosted recipient at the destination address.\n */\n DestinationTag?: number\n}\n\n/**\n * Verify the form and type of an PaymentChannelCreate at runtime.\n *\n * @param tx - An PaymentChannelCreate Transaction.\n * @throws When the PaymentChannelCreate is Malformed.\n */\nexport function validatePaymentChannelCreate(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n if (tx.Amount === undefined) {\n throw new ValidationError('PaymentChannelCreate: missing Amount')\n }\n\n if (typeof tx.Amount !== 'string') {\n throw new ValidationError('PaymentChannelCreate: Amount must be a string')\n }\n\n validateRequiredField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n if (tx.SettleDelay === undefined) {\n throw new ValidationError('PaymentChannelCreate: missing SettleDelay')\n }\n\n if (typeof tx.SettleDelay !== 'number') {\n throw new ValidationError(\n 'PaymentChannelCreate: SettleDelay must be a number',\n )\n }\n\n if (tx.PublicKey === undefined) {\n throw new ValidationError('PaymentChannelCreate: missing PublicKey')\n }\n\n if (typeof tx.PublicKey !== 'string') {\n throw new ValidationError(\n 'PaymentChannelCreate: PublicKey must be a string',\n )\n }\n\n if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== 'number') {\n throw new ValidationError(\n 'PaymentChannelCreate: CancelAfter must be a number',\n )\n }\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.ts';\nimport { type Input, Hash, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { SignerEntry } from '../common'\n\nimport { BaseLedgerEntry, HasPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The SignerList object type represents a list of parties that, as a group,\n * are authorized to sign a transaction in place of an individual account. You\n * can create, replace, or remove a signer list using a SignerListSet\n * transaction.\n *\n * @category Ledger Entries\n */\nexport default interface SignerList extends BaseLedgerEntry, HasPreviousTxnID {\n LedgerEntryType: 'SignerList'\n /**\n * A bit-map of Boolean flags enabled for this signer list. For more\n * information, see SignerList Flags.\n */\n Flags: number\n /**\n * A hint indicating which page of the owner directory links to this object,\n * in case the directory consists of multiple pages.\n */\n OwnerNode: string\n /**\n * An array of Signer Entry objects representing the parties who are part of\n * this signer list.\n */\n SignerEntries: SignerEntry[]\n /**\n * An ID for this signer list. Currently always set to 0. If a future\n * amendment allows multiple signer lists for an account, this may change.\n */\n SignerListID: number\n /**\n * A target number for signer weights. To produce a valid signature for the\n * owner of this SignerList, the signers must provide valid signatures whose\n * weights sum to this value or more.\n */\n SignerQuorum: number\n}\n\nexport enum SignerListFlags {\n // True, uses only one OwnerCount\n lsfOneOwnerCount = 0x00010000,\n}\n","import type { Algorithm, HexString, KeyType } from '../types'\n\nenum Prefix {\n NONE = -1,\n ED25519 = 0xed,\n SECP256K1_PUB_X = 0x02,\n SECP256K1_PUB_X_ODD_Y = 0x03,\n SECP256K1_PUB_XY = 0x04,\n SECP256K1_PRIVATE = 0x00,\n}\n\ntype CompositeKey = `${KeyType}_${Prefix}_${number}`\n\n/**\n * | Curve | Type | Prefix | Length | Description | Algorithm |\n * |-----------|-------------|:------:|:------:|-------------------------------------------------------|----------------:|\n * | ed25519 | Private | 0xED | 33 | prefix + Uint256LE (0 < n < order ) | ed25519 |\n * | ed25519 | Public | 0xED | 33 | prefix + 32 y-bytes | ed25519 |\n * | secp256k1 | Public (1) | 0x02 | 33 | prefix + 32 x-bytes | ecdsa-secp256k1 |\n * | secp256k1 | Public (2) | 0x03 | 33 | prefix + 32 x-bytes (y is odd) | ecdsa-secp256k1 |\n * | secp256k1 | Public (3) | 0x04 | 65 | prefix + 32 x-bytes + 32 y-bytes | ecdsa-secp256k1 |\n * | secp256k1 | Private (1) | None | 32 | Uint256BE (0 < n < order) | ecdsa-secp256k1 |\n * | secp256k1 | Private (2) | 0x00 | 33 | prefix + Uint256BE (0 < n < order) | ecdsa-secp256k1 |\n *\n * Note: The 0x00 prefix for secpk256k1 Private (2) essentially 0 pads the number\n * and the interpreted number is the same as 32 bytes.\n */\nconst KEY_TYPES: Record<CompositeKey, Algorithm> = {\n [`private_${Prefix.NONE}_32`]: 'ecdsa-secp256k1',\n [`private_${Prefix.SECP256K1_PRIVATE}_33`]: 'ecdsa-secp256k1',\n [`private_${Prefix.ED25519}_33`]: 'ed25519',\n [`public_${Prefix.ED25519}_33`]: 'ed25519',\n [`public_${Prefix.SECP256K1_PUB_X}_33`]: 'ecdsa-secp256k1',\n [`public_${Prefix.SECP256K1_PUB_X_ODD_Y}_33`]: 'ecdsa-secp256k1',\n [`public_${Prefix.SECP256K1_PUB_XY}_65`]: 'ecdsa-secp256k1',\n}\n\nfunction getKeyInfo(key: HexString) {\n return {\n prefix: key.length < 2 ? Prefix.NONE : parseInt(key.slice(0, 2), 16),\n len: key.length / 2,\n }\n}\n\nfunction prefixRepr(prefix: Prefix): string {\n return prefix === Prefix.NONE\n ? 'None'\n : `0x${prefix.toString(16).padStart(2, '0')}`\n}\n\nfunction getValidFormatsTable(type: KeyType) {\n // No need overkill with renderTable method\n const padding = 2\n const colWidth = {\n algorithm: 'ecdsa-secp256k1'.length + padding,\n prefix: '0x00'.length + padding,\n }\n\n return Object.entries(KEY_TYPES)\n .filter(([key]) => key.startsWith(type))\n .map(([key, algorithm]) => {\n const [, prefix, length] = key.split('_')\n const paddedAlgo = algorithm.padEnd(colWidth.algorithm)\n const paddedPrefix = prefixRepr(Number(prefix)).padEnd(colWidth.prefix)\n return `${paddedAlgo} - Prefix: ${paddedPrefix} Length: ${length} bytes`\n })\n .join('\\n')\n}\n\nfunction keyError({\n key,\n type,\n prefix,\n len,\n}: {\n key: string\n type: KeyType\n prefix: number\n len: number\n}) {\n const validFormats = getValidFormatsTable(type)\n\n return `invalid_key:\n\nType: ${type}\nKey: ${key}\nPrefix: ${prefixRepr(prefix)} \nLength: ${len} bytes\n\nAcceptable ${type} formats are:\n${validFormats}\n`\n}\n\n/**\n * Determines the algorithm associated with a given key (public/private).\n *\n * @param key - hexadecimal string representation of the key.\n * @param type - whether expected key is public or private\n * @returns Algorithm algorithm for signing/verifying\n * @throws Error when key is invalid\n */\nexport function getAlgorithmFromKey(key: HexString, type: KeyType): Algorithm {\n const { prefix, len } = getKeyInfo(key)\n // Special case back compat support for no prefix\n const usedPrefix = type === 'private' && len === 32 ? Prefix.NONE : prefix\n const algorithm = KEY_TYPES[`${type}_${usedPrefix}_${len}`]\n\n if (!algorithm) {\n throw new Error(keyError({ key, type, len, prefix: usedPrefix }))\n }\n return algorithm\n}\n\nexport function getAlgorithmFromPublicKey(key: HexString): Algorithm {\n return getAlgorithmFromKey(key, 'public')\n}\n\nexport function getAlgorithmFromPrivateKey(key: HexString): Algorithm {\n return getAlgorithmFromKey(key, 'private')\n}\n","import { ValidationError } from '../../errors'\nimport { isHex } from '../utils'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n isString,\n VAULT_DATA_MAX_BYTE_LENGTH,\n XRPLNumber,\n isXRPLNumber,\n} from './common'\n\n/**\n * The VaultSet transaction modifies mutable fields on an existing Vault object.\n *\n * @category Transaction Models\n */\nexport interface VaultSet extends BaseTransaction {\n TransactionType: 'VaultSet'\n\n /**\n * The ID of the Vault to be modified. Must be included when updating the Vault.\n */\n VaultID: string\n\n /**\n * Arbitrary Vault metadata, limited to 256 bytes.\n */\n Data?: string\n\n /**\n * The maximum asset amount that can be held in a vault. The value cannot be lower than the\n * current AssetsTotal unless the value is 0.\n */\n AssetsMaximum?: XRPLNumber\n\n /**\n * The PermissionedDomain object ID associated with the shares of this Vault.\n */\n DomainID?: string\n}\n\n/**\n * Verify the form and type of a {@link VaultSet} at runtime.\n *\n * @param tx - A {@link VaultSet} Transaction.\n * @throws When the {@link VaultSet} is malformed.\n */\nexport function validateVaultSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'VaultID', isString)\n validateOptionalField(tx, 'Data', isString)\n validateOptionalField(tx, 'AssetsMaximum', isXRPLNumber)\n validateOptionalField(tx, 'DomainID', isString)\n\n if (tx.Data !== undefined) {\n const dataHex = tx.Data\n if (!isHex(dataHex)) {\n throw new ValidationError('VaultSet: Data must be a valid hex string')\n }\n const dataByteLength = dataHex.length / 2\n if (dataByteLength > VAULT_DATA_MAX_BYTE_LENGTH) {\n throw new ValidationError(\n `VaultSet: Data exceeds ${VAULT_DATA_MAX_BYTE_LENGTH} bytes (actual: ${dataByteLength})`,\n )\n }\n }\n}\n","import { concat } from '@xrplf/isomorphic/utils'\nimport { BinaryParser } from '../serdes/binary-parser'\n\nimport { AccountID } from './account-id'\nimport { Currency } from './currency'\nimport { JsonObject, SerializedType } from './serialized-type'\nimport { Hash192 } from './hash-192'\n\ninterface XRPIssue extends JsonObject {\n currency: string\n}\n\ninterface IOUIssue extends JsonObject {\n currency: string\n issuer: string\n}\ninterface MPTIssue extends JsonObject {\n mpt_issuance_id: string\n}\n/**\n * Interface for JSON objects that represent issues\n */\ntype IssueObject = XRPIssue | IOUIssue | MPTIssue\n\n/**\n * Type guard for Issue Object\n */\nfunction isIssueObject(arg): arg is IssueObject {\n const keys = Object.keys(arg).sort()\n const isXRP = keys.length === 1 && keys[0] === 'currency'\n const isIOU =\n keys.length === 2 && keys[0] === 'currency' && keys[1] === 'issuer'\n const isMPT = keys.length === 1 && keys[0] === 'mpt_issuance_id'\n\n return isXRP || isIOU || isMPT\n}\n\n/**\n * Class for serializing/Deserializing Amounts\n */\nclass Issue extends SerializedType {\n static readonly ZERO_ISSUED_CURRENCY: Issue = new Issue(new Uint8Array(20))\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? Issue.ZERO_ISSUED_CURRENCY.bytes)\n }\n\n /**\n * Construct an amount from an IOU or string amount\n *\n * @param value An Amount, object representing an IOU, MPTAmount, or a string\n * representing an integer amount\n * @returns An Issue object\n */\n static from<T extends Issue | IssueObject>(value: T): Issue {\n if (value instanceof Issue) {\n return value\n }\n\n if (isIssueObject(value)) {\n if (value.currency) {\n const currency = Currency.from(value.currency.toString()).toBytes()\n\n //IOU case\n if (value.issuer) {\n const issuer = AccountID.from(value.issuer.toString()).toBytes()\n return new Issue(concat([currency, issuer]))\n }\n\n //XRP case\n return new Issue(currency)\n }\n\n // MPT case\n if (value.mpt_issuance_id) {\n const mptIssuanceIdBytes = Hash192.from(\n value.mpt_issuance_id.toString(),\n ).toBytes()\n return new Issue(mptIssuanceIdBytes)\n }\n }\n\n throw new Error('Invalid type to construct an Amount')\n }\n\n /**\n * Read an amount from a BinaryParser\n *\n * @param parser BinaryParser to read the Amount from\n * @param hint The number of bytes to consume from the parser.\n * For an MPT amount, pass 24 (the fixed length for Hash192).\n *\n * @returns An Issue object\n */\n static fromParser(parser: BinaryParser, hint?: number): Issue {\n if (hint === Hash192.width) {\n const mptBytes = parser.read(Hash192.width)\n return new Issue(mptBytes)\n }\n const currency = parser.read(20)\n if (new Currency(currency).toJSON() === 'XRP') {\n return new Issue(currency)\n }\n const currencyAndIssuer = [currency, parser.read(20)]\n return new Issue(concat(currencyAndIssuer))\n }\n\n /**\n * Get the JSON representation of this Amount\n *\n * @returns the JSON interpretation of this.bytes\n */\n toJSON(): IssueObject {\n // If the buffer is exactly 24 bytes, treat it as an MPT amount.\n if (this.toBytes().length === Hash192.width) {\n return {\n mpt_issuance_id: this.toHex().toUpperCase(),\n }\n }\n\n const parser = new BinaryParser(this.toString())\n\n const currency = Currency.fromParser(parser) as Currency\n if (currency.toJSON() === 'XRP') {\n return { currency: currency.toJSON() }\n }\n const issuer = AccountID.fromParser(parser) as AccountID\n\n return {\n currency: currency.toJSON(),\n issuer: issuer.toJSON(),\n }\n }\n}\n\nexport { Issue, IssueObject }\n","/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import { Input } from './types'\n\n/**\n * Normalize a string, number array, or Uint8Array to a string or Uint8Array.\n * Both node and noble lib functions accept these types.\n *\n * @param input - value to normalize\n */\nexport default function normalizeInput(input: Input): string | Uint8Array {\n return Array.isArray(input) ? new Uint8Array(input) : input\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isAmount,\n isNumber,\n isString,\n isXChainBridge,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainAddClaimAttestation transaction provides proof from a witness server,\n * attesting to an {@link XChainCommit} transaction.\n *\n * @category Transaction Models\n */\nexport interface XChainAddClaimAttestation extends BaseTransaction {\n TransactionType: 'XChainAddClaimAttestation'\n\n /**\n * The amount committed by the {@link XChainCommit} transaction on the source chain.\n */\n Amount: Amount\n\n /**\n * The account that should receive this signer's share of the SignatureReward.\n */\n AttestationRewardAccount: Account\n\n /**\n * The account on the door account's signer list that is signing the transaction.\n */\n AttestationSignerAccount: Account\n\n /**\n * The destination account for the funds on the destination chain (taken from\n * the {@link XChainCommit} transaction).\n */\n Destination?: Account\n\n /**\n * The account on the source chain that submitted the {@link XChainCommit}\n * transaction that triggered the event associated with the attestation.\n */\n OtherChainSource: Account\n\n /**\n * The public key used to verify the attestation signature.\n */\n PublicKey: string\n\n /**\n * The signature attesting to the event on the other chain.\n */\n Signature: string\n\n /**\n * A boolean representing the chain where the event occurred.\n */\n WasLockingChainSend: 0 | 1\n\n /**\n * The bridge to use to transfer funds.\n */\n XChainBridge: XChainBridge\n\n /**\n * The XChainClaimID associated with the transfer, which was included in the\n * {@link XChainCommit} transaction.\n */\n XChainClaimID: number | string\n}\n\n/**\n * Verify the form and type of an XChainAddClaimAttestation at runtime.\n *\n * @param tx - An XChainAddClaimAttestation Transaction.\n * @throws When the XChainAddClaimAttestation is malformed.\n */\nexport function validateXChainAddClaimAttestation(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Amount', isAmount)\n\n validateRequiredField(tx, 'AttestationRewardAccount', isAccount)\n\n validateRequiredField(tx, 'AttestationSignerAccount', isAccount)\n\n validateOptionalField(tx, 'Destination', isAccount)\n\n validateRequiredField(tx, 'OtherChainSource', isAccount)\n\n validateRequiredField(tx, 'PublicKey', isString)\n\n validateRequiredField(tx, 'Signature', isString)\n\n validateRequiredField(\n tx,\n 'WasLockingChainSend',\n (inp: unknown): inp is 0 | 1 => inp === 0 || inp === 1,\n )\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(\n tx,\n 'XChainClaimID',\n (inp: unknown): inp is number | string => isNumber(inp) || isString(inp),\n )\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.js';\nimport { type Input, Hash, createView, toBytes } from './utils.js';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n validateBaseTransaction,\n validateCredentialsList,\n MAX_AUTHORIZED_CREDENTIALS,\n} from './common'\n\n/**\n * Enum representing values for PaymentChannelClaim transaction flags.\n *\n * @category Transaction Flags\n */\nexport enum PaymentChannelClaimFlags {\n /**\n * Clear the channel's Expiration time. (Expiration is different from the\n * channel's immutable CancelAfter time.) Only the source address of the\n * payment channel can use this flag.\n */\n tfRenew = 0x00010000,\n /**\n * Request to close the channel. Only the channel source and destination\n * addresses can use this flag. This flag closes the channel immediately if it\n * has no more XRP allocated to it after processing the current claim, or if\n * the destination address uses it. If the source address uses this flag when\n * the channel still holds XRP, this schedules the channel to close after\n * SettleDelay seconds have passed. (Specifically, this sets the Expiration of\n * the channel to the close time of the previous ledger plus the channel's\n * SettleDelay time, unless the channel already has an earlier Expiration\n * time.) If the destination address uses this flag when the channel still\n * holds XRP, any XRP that remains after processing the claim is returned to\n * the source address.\n */\n tfClose = 0x00020000,\n}\n\n/**\n * Map of flags to boolean values representing {@link PaymentChannelClaim}\n * transaction flags.\n *\n * @category Transaction Flags\n *\n * @example\n * ```typescript\n * const paymentChannelClaim: PaymentChannelClaim = {\n * Account: 'rMpxZpuy5RBSP47oK2hDWUtk3B5BNQHfGj,\n * TransactionType: 'PaymentChannelClaim',\n * Channel: hashes.hashPaymentChannel(\n * 'rMpxZpuy5RBSP47oK2hDWUtk3B5BNQHfGj',\n * 'rQGYqiyH5Ue9J96p4E6Qt6AvqxK4sDhnS5',\n * 21970712,\n * ),\n * Amount: '100',\n * Flags: {\n * tfClose: true\n * }\n *}\n *\n * // Autofill the tx to see how flags actually look compared to the interface usage.\n * const autofilledTx = await client.autofill(paymentChannelClaim)\n * console.log(autofilledTx)\n * // {\n * // Account: 'rMpxZpuy5RBSP47oK2hDWUtk3B5BNQHfGj',\n * // TransactionType: 'PaymentChannelClaim',\n * // Channel: 'FC14BF9245D731DC1749EE0F070765E4EB4E993F8ECEE3D00F7E6E26D6EF98CF',\n * // Amount: '100',\n * // Flags: 131072,\n * // Sequence: 21970713,\n * // Fee: '12',\n * // LastLedgerSequence: 21970658\n * // }\n * ```\n */\nexport interface PaymentChannelClaimFlagsInterface\n extends GlobalFlagsInterface {\n /**\n * Clear the channel's Expiration time. (Expiration is different from the\n * channel's immutable CancelAfter time.) Only the source address of the\n * payment channel can use this flag.\n */\n tfRenew?: boolean\n /**\n * Request to close the channel. Only the channel source and destination\n * addresses can use this flag. This flag closes the channel immediately if it\n * has no more XRP allocated to it after processing the current claim, or if\n * the destination address uses it. If the source address uses this flag when\n * the channel still holds XRP, this schedules the channel to close after\n * SettleDelay seconds have passed. (Specifically, this sets the Expiration of\n * the channel to the close time of the previous ledger plus the channel's\n * SettleDelay time, unless the channel already has an earlier Expiration\n * time.) If the destination address uses this flag when the channel still\n * holds XRP, any XRP that remains after processing the claim is returned to\n * the source address.\n */\n tfClose?: boolean\n}\n\n/**\n * Claim XRP from a payment channel, adjust the payment channel's expiration,\n * or both.\n *\n * @category Transaction Models\n */\nexport interface PaymentChannelClaim extends BaseTransaction {\n TransactionType: 'PaymentChannelClaim'\n Flags?: number | PaymentChannelClaimFlagsInterface\n /** The unique ID of the channel as a 64-character hexadecimal string. */\n Channel: string\n /**\n * Total amount of XRP, in drops, delivered by this channel after processing\n * this claim. Required to deliver XRP. Must be more than the total amount\n * delivered by the channel so far, but not greater than the Amount of the\n * signed claim. Must be provided except when closing the channel.\n */\n Balance?: string\n /**\n * The amount of XRP, in drops, authorized by the Signature. This must match\n * the amount in the signed message. This is the cumulative amount of XRP that\n * can be dispensed by the channel, including XRP previously redeemed.\n */\n Amount?: string\n /**\n * The signature of this claim, as hexadecimal. The signed message contains\n * the channel ID and the amount of the claim. Required unless the sender of\n * the transaction is the source address of the channel.\n */\n Signature?: string\n /**\n * The public key used for the signature, as hexadecimal. This must match the\n * PublicKey stored in the ledger for the channel. Required unless the sender\n * of the transaction is the source address of the channel and the Signature\n * field is omitted.\n */\n PublicKey?: string\n /**\n * Credentials associated with the sender of this transaction.\n * The credentials included must not be expired.\n */\n CredentialIDs?: string[]\n}\n\n/**\n * Verify the form and type of an PaymentChannelClaim at runtime.\n *\n * @param tx - An PaymentChannelClaim Transaction.\n * @throws When the PaymentChannelClaim is Malformed.\n */\nexport function validatePaymentChannelClaim(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateCredentialsList(\n tx.CredentialIDs,\n tx.TransactionType,\n true,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n\n if (tx.Channel === undefined) {\n throw new ValidationError('PaymentChannelClaim: missing Channel')\n }\n\n if (typeof tx.Channel !== 'string') {\n throw new ValidationError('PaymentChannelClaim: Channel must be a string')\n }\n\n if (tx.Balance !== undefined && typeof tx.Balance !== 'string') {\n throw new ValidationError('PaymentChannelClaim: Balance must be a string')\n }\n\n if (tx.Amount !== undefined && typeof tx.Amount !== 'string') {\n throw new ValidationError('PaymentChannelClaim: Amount must be a string')\n }\n\n if (tx.Signature !== undefined && typeof tx.Signature !== 'string') {\n throw new ValidationError('PaymentChannelClaim: Signature must be a string')\n }\n\n if (tx.PublicKey !== undefined && typeof tx.PublicKey !== 'string') {\n throw new ValidationError('PaymentChannelClaim: PublicKey must be a string')\n }\n}\n","import { ValidationError } from '../../errors'\nimport { Currency } from '../common'\n\nimport { AMM_MAX_TRADING_FEE } from './AMMCreate'\nimport {\n BaseTransaction,\n isIssuedCurrency,\n validateBaseTransaction,\n} from './common'\n\n/**\n * Vote on the trading fee for an Automated Market Maker (AMM) instance.\n *\n * Up to 8 accounts can vote in proportion to the amount of the AMM's LP Tokens they hold.\n * Each new vote re-calculates the AMM's trading fee based on a weighted average of the votes.\n */\nexport interface AMMVote extends BaseTransaction {\n TransactionType: 'AMMVote'\n\n /**\n * The definition for one of the assets in the AMM's pool.\n */\n Asset: Currency\n\n /**\n * The definition for the other asset in the AMM's pool.\n */\n Asset2: Currency\n\n /**\n * The proposed fee to vote for, in units of 1/100,000; a value of 1 is equivalent to 0.001%.\n * The maximum value is 1000, indicating a 1% fee.\n */\n TradingFee: number\n}\n\n/**\n * Verify the form and type of an AMMVote at runtime.\n *\n * @param tx - An AMMVote Transaction.\n * @throws When the AMMVote is Malformed.\n */\nexport function validateAMMVote(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Asset == null) {\n throw new ValidationError('AMMVote: missing field Asset')\n }\n\n if (!isIssuedCurrency(tx.Asset)) {\n throw new ValidationError('AMMVote: Asset must be a Currency')\n }\n\n if (tx.Asset2 == null) {\n throw new ValidationError('AMMVote: missing field Asset2')\n }\n\n if (!isIssuedCurrency(tx.Asset2)) {\n throw new ValidationError('AMMVote: Asset2 must be a Currency')\n }\n\n if (tx.TradingFee == null) {\n throw new ValidationError('AMMVote: missing field TradingFee')\n }\n\n if (typeof tx.TradingFee !== 'number') {\n throw new ValidationError('AMMVote: TradingFee must be a number')\n }\n\n if (tx.TradingFee < 0 || tx.TradingFee > AMM_MAX_TRADING_FEE) {\n throw new ValidationError(\n `AMMVote: TradingFee must be between 0 and ${AMM_MAX_TRADING_FEE}`,\n )\n }\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, rotr, wrapConstructor } from './utils.ts';\n\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n SHA256_W.fill(0);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n protected A = 0xc1059ed8 | 0;\n protected B = 0x367cd507 | 0;\n protected C = 0x3070dd17 | 0;\n protected D = 0xf70e5939 | 0;\n protected E = 0xffc00b31 | 0;\n protected F = 0x68581511 | 0;\n protected G = 0x64f98fa7 | 0;\n protected H = 0xbefa4fa4 | 0;\n constructor() {\n super(28);\n }\n}\n\n/** SHA2-256 hash function */\nexport const sha256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","const RIPPLE_EPOCH_DIFF = 0x386d4380\n\n/**\n * Convert a ripple timestamp to a unix timestamp.\n *\n * @param rpepoch - (seconds since 1/1/2000 GMT).\n * @returns Milliseconds since unix epoch.\n * @category Utilities\n */\nfunction rippleTimeToUnixTime(rpepoch: number): number {\n return (rpepoch + RIPPLE_EPOCH_DIFF) * 1000\n}\n\n/**\n * Convert a unix timestamp to a ripple timestamp.\n *\n * @param timestamp - (ms since unix epoch).\n * @returns Seconds since Ripple Epoch (1/1/2000 GMT).\n * @category Utilities\n */\nfunction unixTimeToRippleTime(timestamp: number): number {\n return Math.round(timestamp / 1000) - RIPPLE_EPOCH_DIFF\n}\n\n/**\n * Convert a ripple timestamp to an Iso8601 timestamp.\n *\n * @param rippleTime - Is the number of seconds since Ripple Epoch (1/1/2000 GMT).\n * @returns Iso8601 international standard date format.\n * @category Utilities\n */\nfunction rippleTimeToISOTime(rippleTime: number): string {\n return new Date(rippleTimeToUnixTime(rippleTime)).toISOString()\n}\n\n/**\n * Convert an ISO8601 timestmap to a ripple timestamp.\n *\n * @param iso8601 - International standard date format.\n * @returns Seconds since ripple epoch (1/1/2000 GMT).\n * @category Utilities\n */\nfunction isoTimeToRippleTime(iso8601: string | Date): number {\n const isoDate = typeof iso8601 === 'string' ? new Date(iso8601) : iso8601\n return unixTimeToRippleTime(isoDate.getTime())\n}\n\nexport {\n rippleTimeToUnixTime,\n unixTimeToRippleTime,\n rippleTimeToISOTime,\n isoTimeToRippleTime,\n}\n","import {\n BaseTransaction,\n validateBaseTransaction,\n validateRequiredField,\n isString,\n} from './common'\n\n/**\n * The VaultDelete transaction deletes an existing vault object.\n *\n * @category Transaction Models\n */\nexport interface VaultDelete extends BaseTransaction {\n TransactionType: 'VaultDelete'\n\n /**\n * The ID of the vault to be deleted.\n */\n VaultID: string\n}\n\n/**\n * Verify the form and type of a {@link VaultDelete} at runtime.\n *\n * @param tx - A {@link VaultDelete} Transaction.\n * @throws When the {@link VaultDelete} is malformed.\n */\nexport function validateVaultDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'VaultID', isString)\n}\n","import { ShaMap, ShaMapNode, ShaMapLeaf } from './shamap'\nimport { HashPrefix } from './hash-prefixes'\nimport { Sha512Half } from './hashes'\nimport { BinarySerializer, serializeObject } from './binary'\nimport { Hash256 } from './types/hash-256'\nimport { STObject } from './types/st-object'\nimport { UInt64 } from './types/uint-64'\nimport { UInt32 } from './types/uint-32'\nimport { UInt8 } from './types/uint-8'\nimport { BinaryParser } from './serdes/binary-parser'\nimport { JsonObject } from './types/serialized-type'\nimport { XrplDefinitionsBase } from './enums'\n\n/**\n * Computes the hash of a list of objects\n *\n * @param itemizer Converts an item into a format that can be added to SHAMap\n * @param itemsJson Array of items to add to a SHAMap\n * @returns the hash of the SHAMap\n */\nfunction computeHash(\n itemizer: (item: JsonObject) => [Hash256?, ShaMapNode?, ShaMapLeaf?],\n itemsJson: Array<JsonObject>,\n): Hash256 {\n const map = new ShaMap()\n itemsJson.forEach((item) => map.addItem(...itemizer(item)))\n return map.hash()\n}\n\n/**\n * Interface describing a transaction item\n */\ninterface transactionItemObject extends JsonObject {\n hash: string\n metaData: JsonObject\n}\n\n/**\n * Convert a transaction into an index and an item\n *\n * @param json transaction with metadata\n * @returns a tuple of index and item to be added to SHAMap\n */\nfunction transactionItemizer(\n json: transactionItemObject,\n): [Hash256, ShaMapNode, undefined] {\n if (!json.hash) {\n throw new Error()\n }\n const index = Hash256.from(json.hash)\n const item = {\n hashPrefix() {\n return HashPrefix.transaction\n },\n toBytesSink(sink) {\n const serializer = new BinarySerializer(sink)\n serializer.writeLengthEncoded(STObject.from(json))\n serializer.writeLengthEncoded(STObject.from(json.metaData))\n },\n } as ShaMapNode\n return [index, item, undefined]\n}\n\n/**\n * Interface describing an entry item\n */\ninterface entryItemObject extends JsonObject {\n index: string\n}\n\n/**\n * Convert an entry to a pair Hash256 and ShaMapNode\n *\n * @param json JSON describing a ledger entry item\n * @returns a tuple of index and item to be added to SHAMap\n */\nfunction entryItemizer(\n json: entryItemObject,\n): [Hash256, ShaMapNode, undefined] {\n const index = Hash256.from(json.index)\n const bytes = serializeObject(json)\n const item = {\n hashPrefix() {\n return HashPrefix.accountStateEntry\n },\n toBytesSink(sink) {\n sink.put(bytes)\n },\n } as ShaMapNode\n return [index, item, undefined]\n}\n\n/**\n * Function computing the hash of a transaction tree\n *\n * @param param An array of transaction objects to hash\n * @returns A Hash256 object\n */\nfunction transactionTreeHash(param: Array<JsonObject>): Hash256 {\n const itemizer = transactionItemizer as (\n json: JsonObject,\n ) => [Hash256, ShaMapNode, undefined]\n return computeHash(itemizer, param)\n}\n\n/**\n * Function computing the hash of accountState\n *\n * @param param A list of accountStates hash\n * @returns A Hash256 object\n */\nfunction accountStateHash(param: Array<JsonObject>): Hash256 {\n const itemizer = entryItemizer as (\n json: JsonObject,\n ) => [Hash256, ShaMapNode, undefined]\n return computeHash(itemizer, param)\n}\n\n/**\n * Interface describing a ledger header\n */\ninterface ledgerObject {\n ledger_index: number\n total_coins: string | number | bigint\n parent_hash: string\n transaction_hash: string\n account_hash: string\n parent_close_time: number\n close_time: number\n close_time_resolution: number\n close_flags: number\n}\n\n/**\n * Serialize and hash a ledger header\n *\n * @param header a ledger header\n * @returns the hash of header\n */\nfunction ledgerHash(header: ledgerObject): Hash256 {\n const hash = new Sha512Half()\n hash.put(HashPrefix.ledgerHeader)\n if (\n header.parent_close_time === undefined ||\n header.close_flags === undefined\n ) {\n throw new Error()\n }\n\n UInt32.from<number>(header.ledger_index).toBytesSink(hash)\n UInt64.from<bigint>(BigInt(String(header.total_coins))).toBytesSink(hash)\n Hash256.from<string>(header.parent_hash).toBytesSink(hash)\n Hash256.from<string>(header.transaction_hash).toBytesSink(hash)\n Hash256.from<string>(header.account_hash).toBytesSink(hash)\n UInt32.from<number>(header.parent_close_time).toBytesSink(hash)\n UInt32.from<number>(header.close_time).toBytesSink(hash)\n UInt8.from<number>(header.close_time_resolution).toBytesSink(hash)\n UInt8.from<number>(header.close_flags).toBytesSink(hash)\n return hash.finish()\n}\n\n/**\n * Decodes a serialized ledger header\n *\n * @param binary A serialized ledger header\n * @param definitions Type definitions to parse the ledger objects.\n * Used if there are non-default ledger objects to decode.\n * @returns A JSON object describing a ledger header\n */\nfunction decodeLedgerData(\n binary: string,\n definitions?: XrplDefinitionsBase,\n): object {\n if (typeof binary !== 'string') {\n throw new Error('binary must be a hex string')\n }\n const parser = new BinaryParser(binary, definitions)\n return {\n ledger_index: parser.readUInt32(),\n total_coins: parser.readType(UInt64).valueOf().toString(),\n parent_hash: parser.readType(Hash256).toHex(),\n transaction_hash: parser.readType(Hash256).toHex(),\n account_hash: parser.readType(Hash256).toHex(),\n parent_close_time: parser.readUInt32(),\n close_time: parser.readUInt32(),\n close_time_resolution: parser.readUInt8(),\n close_flags: parser.readUInt8(),\n }\n}\n\nexport { accountStateHash, transactionTreeHash, ledgerHash, decodeLedgerData }\n","import { numberToBytesBE } from '@noble/curves/abstract/utils'\nimport { secp256k1 as nobleSecp256k1 } from '@noble/curves/secp256k1'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\nimport type {\n DeriveKeyPairOptions,\n HexString,\n SigningScheme,\n} from '../../types'\n\nimport { derivePrivateKey } from './utils'\nimport assert from '../../utils/assert'\nimport Sha512 from '../../utils/Sha512'\n\nconst SECP256K1_PREFIX = '00'\n\nconst secp256k1: SigningScheme = {\n deriveKeypair(\n entropy: Uint8Array,\n options?: DeriveKeyPairOptions,\n ): {\n privateKey: string\n publicKey: string\n } {\n const derived = derivePrivateKey(entropy, options)\n const privateKey =\n SECP256K1_PREFIX + bytesToHex(numberToBytesBE(derived, 32))\n\n const publicKey = bytesToHex(nobleSecp256k1.getPublicKey(derived, true))\n return { privateKey, publicKey }\n },\n\n sign(message: Uint8Array, privateKey: HexString): string {\n // Some callers pass the privateKey with the prefix, others without.\n // @noble/curves will throw if the key is not exactly 32 bytes, so we\n // normalize it before passing to the sign method.\n assert.ok(\n (privateKey.length === 66 && privateKey.startsWith(SECP256K1_PREFIX)) ||\n privateKey.length === 64,\n )\n const normedPrivateKey =\n privateKey.length === 66 ? privateKey.slice(2) : privateKey\n return nobleSecp256k1\n .sign(Sha512.half(message), normedPrivateKey, {\n // \"Canonical\" signatures\n lowS: true,\n // Would fail tests if signatures aren't deterministic\n extraEntropy: undefined,\n })\n .toDERHex(true)\n .toUpperCase()\n },\n\n verify(\n message: Uint8Array,\n signature: HexString,\n publicKey: HexString,\n ): boolean {\n const decoded = nobleSecp256k1.Signature.fromDER(signature)\n return nobleSecp256k1.verify(decoded, Sha512.half(message), publicKey)\n },\n}\n\nexport default secp256k1\n","import { sha512 } from '@xrplf/isomorphic/sha512'\nimport { bytesToHex, hexToBytes } from '@xrplf/isomorphic/utils'\n\nconst HASH_BYTES = 32\n\n/**\n * Compute a sha512Half Hash of a hex string.\n *\n * @param hex - Hex string to hash.\n * @returns Hash of hex.\n */\nfunction sha512Half(hex: string): string {\n return bytesToHex(sha512(hexToBytes(hex)).slice(0, HASH_BYTES))\n}\n\nexport default sha512Half\n","import { deriveAddress, deriveKeypair, generateSeed } from 'ripple-keypairs'\n\nimport {\n entropyToSecret,\n parseSecretString,\n randomSecret,\n secretToEntropy,\n} from '../utils'\n\n/* Types ==================================================================== */\n\nexport interface Keypair {\n publicKey: string\n privateKey: string\n}\n\ninterface AccountData {\n familySeed: string\n address: string\n keypair: Keypair\n}\n\n/* Class ==================================================================== */\n\nexport class Account {\n private readonly _secret: string[]\n private readonly _account: AccountData = {\n familySeed: '',\n address: '',\n keypair: {\n publicKey: '',\n privateKey: '',\n },\n }\n\n constructor(secretNumbers?: string[] | string | Uint8Array) {\n if (typeof secretNumbers === 'string') {\n this._secret = parseSecretString(secretNumbers)\n } else if (Array.isArray(secretNumbers)) {\n this._secret = secretNumbers\n } else if (secretNumbers instanceof Uint8Array) {\n this._secret = entropyToSecret(secretNumbers)\n } else {\n this._secret = randomSecret()\n }\n\n validateLengths(this._secret)\n this.derive()\n }\n\n getSecret(): string[] {\n return this._secret\n }\n\n getSecretString(): string {\n return this._secret.join(' ')\n }\n\n getAddress(): string {\n return this._account.address\n }\n\n getFamilySeed(): string {\n return this._account.familySeed\n }\n\n getKeypair(): Keypair {\n return this._account.keypair\n }\n\n toString(): string {\n return this.getSecretString()\n }\n\n private derive(): void {\n try {\n const entropy = secretToEntropy(this._secret)\n this._account.familySeed = generateSeed({ entropy })\n this._account.keypair = deriveKeypair(this._account.familySeed)\n this._account.address = deriveAddress(this._account.keypair.publicKey)\n } catch (error) {\n let message = 'Unknown Error'\n if (error instanceof Error) {\n message = error.message\n }\n // we'll proceed, but let's report it\n throw new Error(message)\n }\n }\n}\n\nfunction validateLengths(secretNumbers: string[]): void {\n if (secretNumbers.length !== 8) {\n throw new Error('Secret must have 8 numbers')\n }\n secretNumbers.forEach((num) => {\n if (num.length !== 6) {\n throw new Error('Each secret number must be 6 digits')\n }\n })\n}\n","import { CHash } from '@noble/hashes/utils'\nimport { Hash, HashFn, Input } from './types'\nimport normalizeInput from './normalizeInput'\n\n/**\n * Wrap a CHash object from @noble/hashes to provide a interface that is isomorphic\n *\n * @param chash - {CHash} hash function to wrap\n */\nexport default function wrapNoble(chash: CHash): HashFn {\n function wrapped(input: Input): Uint8Array {\n return chash(normalizeInput(input))\n }\n\n wrapped.create = (): Hash => {\n const hash = chash.create()\n return {\n update(input: Input): Hash {\n hash.update(normalizeInput(input))\n return this\n },\n digest(): Uint8Array {\n return hash.digest()\n },\n }\n }\n return wrapped\n}\n","import BigNumber from 'bignumber.js'\n\nimport { ValidationError } from '../errors'\n\nconst DROPS_PER_XRP = 1000000.0\nconst MAX_FRACTION_LENGTH = 6\nconst BASE_TEN = 10\nconst SANITY_CHECK = /^-?[0-9.]+$/u\n\n/**\n * Convert Drops to XRP.\n *\n * @param dropsToConvert - Drops to convert to XRP. This can be a string, number, or BigNumber.\n * @returns Amount in XRP.\n * @throws When drops amount is invalid.\n * @category Utilities\n */\nexport function dropsToXrp(dropsToConvert: BigNumber.Value): number {\n /*\n * Converting to BigNumber and then back to string should remove any\n * decimal point followed by zeros, e.g. '1.00'.\n * Important: specify base BASE_10 to avoid exponential notation, e.g. '1e-7'.\n */\n const drops = new BigNumber(dropsToConvert).toString(BASE_TEN)\n\n // check that the value is valid and actually a number\n if (typeof dropsToConvert === 'string' && drops === 'NaN') {\n throw new ValidationError(\n `dropsToXrp: invalid value '${dropsToConvert}', should be a BigNumber or string-encoded number.`,\n )\n }\n\n // drops are only whole units\n if (drops.includes('.')) {\n throw new ValidationError(\n `dropsToXrp: value '${drops}' has too many decimal places.`,\n )\n }\n\n /*\n * This should never happen; the value has already been\n * validated above. This just ensures BigNumber did not do\n * something unexpected.\n */\n if (!SANITY_CHECK.exec(drops)) {\n throw new ValidationError(\n `dropsToXrp: failed sanity check -` +\n ` value '${drops}',` +\n ` does not match (^-?[0-9]+$).`,\n )\n }\n\n return new BigNumber(drops).dividedBy(DROPS_PER_XRP).toNumber()\n}\n\n/**\n * Convert an amount in XRP to an amount in drops.\n *\n * @param xrpToConvert - Amount in XRP.\n * @returns Amount in drops.\n * @throws When amount in xrp is invalid.\n * @category Utilities\n */\nexport function xrpToDrops(xrpToConvert: BigNumber.Value): string {\n // Important: specify base BASE_TEN to avoid exponential notation, e.g. '1e-7'.\n const xrp = new BigNumber(xrpToConvert).toString(BASE_TEN)\n\n // check that the value is valid and actually a number\n if (typeof xrpToConvert === 'string' && xrp === 'NaN') {\n throw new ValidationError(\n `xrpToDrops: invalid value '${xrpToConvert}', should be a BigNumber or string-encoded number.`,\n )\n }\n\n /*\n * This should never happen; the value has already been\n * validated above. This just ensures BigNumber did not do\n * something unexpected.\n */\n if (!SANITY_CHECK.exec(xrp)) {\n throw new ValidationError(\n `xrpToDrops: failed sanity check - value '${xrp}', does not match (^-?[0-9.]+$).`,\n )\n }\n\n const components = xrp.split('.')\n if (components.length > 2) {\n throw new ValidationError(\n `xrpToDrops: failed sanity check - value '${xrp}' has too many decimal points.`,\n )\n }\n\n const fraction = components[1] || '0'\n if (fraction.length > MAX_FRACTION_LENGTH) {\n throw new ValidationError(\n `xrpToDrops: value '${xrp}' has too many decimal places.`,\n )\n }\n\n return new BigNumber(xrp)\n .times(DROPS_PER_XRP)\n .integerValue(BigNumber.ROUND_FLOOR)\n .toString(BASE_TEN)\n}\n","/* eslint-disable max-lines -- common utility file */\nimport { HEX_REGEX } from '@xrplf/isomorphic/utils'\nimport { isValidClassicAddress, isValidXAddress } from 'ripple-address-codec'\nimport { TRANSACTION_TYPES } from 'ripple-binary-codec'\n\nimport { ValidationError } from '../../errors'\nimport {\n Amount,\n AuthorizeCredential,\n ClawbackAmount,\n Currency,\n IssuedCurrency,\n IssuedCurrencyAmount,\n MPTAmount,\n Memo,\n Signer,\n XChainBridge,\n} from '../common'\nimport { isHex, onlyHasFields } from '../utils'\n\nconst MEMO_SIZE = 3\nexport const MAX_AUTHORIZED_CREDENTIALS = 8\nconst MAX_CREDENTIAL_BYTE_LENGTH = 64\nconst MAX_CREDENTIAL_TYPE_LENGTH = MAX_CREDENTIAL_BYTE_LENGTH * 2\n\n// Used for Vault transactions\nexport const VAULT_DATA_MAX_BYTE_LENGTH = 256\n\nfunction isMemo(obj: unknown): obj is Memo {\n if (!isRecord(obj)) {\n return false\n }\n\n const memo = obj.Memo\n if (!isRecord(memo)) {\n return false\n }\n const size = Object.keys(memo).length\n const validData =\n memo.MemoData == null || (isString(memo.MemoData) && isHex(memo.MemoData))\n const validFormat =\n memo.MemoFormat == null ||\n (isString(memo.MemoFormat) && isHex(memo.MemoFormat))\n const validType =\n memo.MemoType == null || (isString(memo.MemoType) && isHex(memo.MemoType))\n\n return (\n size >= 1 &&\n size <= MEMO_SIZE &&\n validData &&\n validFormat &&\n validType &&\n onlyHasFields(memo, ['MemoFormat', 'MemoData', 'MemoType'])\n )\n}\n\nconst SIGNER_SIZE = 3\n\nfunction isSigner(obj: unknown): obj is Signer {\n if (!isRecord(obj)) {\n return false\n }\n\n const signer = obj.Signer\n if (!isRecord(signer)) {\n return false\n }\n\n return (\n Object.keys(signer).length === SIGNER_SIZE &&\n isString(signer.Account) &&\n isString(signer.TxnSignature) &&\n isString(signer.SigningPubKey)\n )\n}\n\nconst XRP_CURRENCY_SIZE = 1\nconst ISSUE_SIZE = 2\nconst ISSUED_CURRENCY_SIZE = 3\nconst XCHAIN_BRIDGE_SIZE = 4\nconst MPTOKEN_SIZE = 2\nconst AUTHORIZE_CREDENTIAL_SIZE = 1\n\n/**\n * Verify the form and type of a Record/Object at runtime.\n *\n * @param value - The object to check the form and type of.\n * @returns Whether the Record/Object is properly formed.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Verify the form and type of a string at runtime.\n *\n * @param str - The object to check the form and type of.\n * @returns Whether the string is properly formed.\n */\nexport function isString(str: unknown): str is string {\n return typeof str === 'string'\n}\n\n/**\n * Verify the form and type of a number at runtime.\n *\n * @param num - The object to check the form and type of.\n * @returns Whether the number is properly formed.\n */\nexport function isNumber(num: unknown): num is number {\n return typeof num === 'number'\n}\n\n/**\n * Checks whether the given value is a valid XRPL number string.\n * Accepts integer, decimal, or scientific notation strings.\n *\n * Examples of valid input:\n * - \"123\"\n * - \"-987.654\"\n * - \"+3.14e10\"\n * - \"-7.2e-9\"\n *\n * @param value - The value to check.\n * @returns True if value is a string that matches the XRPL number format, false otherwise.\n */\nexport function isXRPLNumber(value: unknown): value is XRPLNumber {\n // Matches optional sign, digits, optional decimal, optional exponent (scientific)\n // Allows leading zeros, but not empty string, lone sign, or missing digits\n return (\n typeof value === 'string' &&\n /^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?$/u.test(value.trim())\n )\n}\n\n/**\n * Verify the form and type of a Currency at runtime.\n *\n * @param input - The input to check the form and type of.\n * @returns Whether the Currency is properly formed.\n */\nexport function isCurrency(input: unknown): input is Currency {\n return isString(input) || isIssuedCurrency(input)\n}\n\n/**\n * Verify the form and type of an IssuedCurrency at runtime.\n *\n * @param input - The input to check the form and type of.\n * @returns Whether the IssuedCurrency is properly formed.\n */\nexport function isIssuedCurrency(input: unknown): input is IssuedCurrency {\n return (\n isRecord(input) &&\n ((Object.keys(input).length === ISSUE_SIZE &&\n isString(input.issuer) &&\n isString(input.currency)) ||\n (Object.keys(input).length === XRP_CURRENCY_SIZE &&\n input.currency === 'XRP'))\n )\n}\n\n/**\n * Verify the form and type of an IssuedCurrencyAmount at runtime.\n *\n * @param input - The input to check the form and type of.\n * @returns Whether the IssuedCurrencyAmount is properly formed.\n */\nexport function isIssuedCurrencyAmount(\n input: unknown,\n): input is IssuedCurrencyAmount {\n return (\n isRecord(input) &&\n Object.keys(input).length === ISSUED_CURRENCY_SIZE &&\n isString(input.value) &&\n isString(input.issuer) &&\n isString(input.currency)\n )\n}\n\n/**\n * Verify the form and type of an AuthorizeCredential at runtime\n *\n * @param input - The input to check the form and type of\n * @returns Whether the AuthorizeCredential is properly formed\n */\nexport function isAuthorizeCredential(\n input: unknown,\n): input is AuthorizeCredential {\n return (\n isRecord(input) &&\n isRecord(input.Credential) &&\n Object.keys(input).length === AUTHORIZE_CREDENTIAL_SIZE &&\n typeof input.Credential.CredentialType === 'string' &&\n typeof input.Credential.Issuer === 'string'\n )\n}\n\n/**\n * Verify the form and type of an MPT at runtime.\n *\n * @param input - The input to check the form and type of.\n * @returns Whether the MPTAmount is properly formed.\n */\nexport function isMPTAmount(input: unknown): input is MPTAmount {\n return (\n isRecord(input) &&\n Object.keys(input).length === MPTOKEN_SIZE &&\n typeof input.value === 'string' &&\n typeof input.mpt_issuance_id === 'string'\n )\n}\n\n/**\n * Type guard to verify if the input is a valid ClawbackAmount.\n *\n * A ClawbackAmount can be either an {@link IssuedCurrencyAmount} or an {@link MPTAmount}.\n * This function checks if the input matches either type.\n *\n * @param input - The value to check for ClawbackAmount structure.\n * @returns True if the input is an IssuedCurrencyAmount or MPTAmount, otherwise false.\n */\nexport function isClawbackAmount(input: unknown): input is ClawbackAmount {\n return isIssuedCurrencyAmount(input) || isMPTAmount(input)\n}\n\n/**\n * Must be a valid account address\n */\nexport type Account = string\n\n/**\n * XRPL Number type represented as a string.\n *\n * This string can be an integer (e.g., \"123\"), a decimal (e.g., \"123.45\"),\n * or in scientific notation (e.g., \"1.23e5\", \"-4.56e-7\").\n * Used for fields that accept arbitrary-precision numbers in XRPL transactions and ledger objects.\n */\nexport type XRPLNumber = string\n\n/**\n * Verify a string is in fact a valid account address.\n *\n * @param account - The object to check the form and type of.\n * @returns Whether the account is properly formed account for a transaction.\n */\nexport function isAccount(account: unknown): account is Account {\n return (\n typeof account === 'string' &&\n (isValidClassicAddress(account) || isValidXAddress(account))\n )\n}\n\n/**\n * Verify the form and type of an Amount at runtime.\n *\n * @param amount - The object to check the form and type of.\n * @returns Whether the Amount is properly formed.\n */\nexport function isAmount(amount: unknown): amount is Amount {\n return (\n typeof amount === 'string' ||\n isIssuedCurrencyAmount(amount) ||\n isMPTAmount(amount)\n )\n}\n\n/**\n * Verify the form and type of an XChainBridge at runtime.\n *\n * @param input - The input to check the form and type of.\n * @returns Whether the XChainBridge is properly formed.\n */\nexport function isXChainBridge(input: unknown): input is XChainBridge {\n return (\n isRecord(input) &&\n Object.keys(input).length === XCHAIN_BRIDGE_SIZE &&\n typeof input.LockingChainDoor === 'string' &&\n isIssuedCurrency(input.LockingChainIssue) &&\n typeof input.IssuingChainDoor === 'string' &&\n isIssuedCurrency(input.IssuingChainIssue)\n )\n}\n\n/**\n * Verify the form and type of an Array at runtime.\n *\n * @param input - The object to check the form and type of.\n * @returns Whether the Array is properly formed.\n */\nexport function isArray<T = unknown>(input: unknown): input is T[] {\n return input != null && Array.isArray(input)\n}\n\n/* eslint-disable @typescript-eslint/restrict-template-expressions -- tx.TransactionType is checked before any calls */\n\n/**\n * Verify the form and type of a required type for a transaction at runtime.\n *\n * @param tx - The object input to check the form and type of.\n * @param param - The object parameter.\n * @param checkValidity - The function to use to check the type.\n * @param errorOpts - Extra values to make the error message easier to understand.\n * @param errorOpts.txType - The transaction type throwing the error.\n * @param errorOpts.paramName - The name of the parameter in the transaction with the error.\n * @throws ValidationError if the parameter is missing or invalid.\n */\n// eslint-disable-next-line max-params -- helper function\nexport function validateRequiredField<\n T extends Record<string, unknown>,\n K extends keyof T,\n V,\n>(\n tx: T,\n param: K,\n checkValidity: (inp: unknown) => inp is V,\n errorOpts: {\n txType?: string\n paramName?: string\n } = {},\n): asserts tx is T & { [P in K]: V } {\n const paramNameStr = errorOpts.paramName ?? param\n const txType = errorOpts.txType ?? tx.TransactionType\n if (tx[param] == null) {\n throw new ValidationError(\n `${txType}: missing field ${String(paramNameStr)}`,\n )\n }\n\n if (!checkValidity(tx[param])) {\n throw new ValidationError(\n `${txType}: invalid field ${String(paramNameStr)}`,\n )\n }\n}\n\n/**\n * Verify the form and type of an optional type for a transaction at runtime.\n *\n * @param tx - The transaction input to check the form and type of.\n * @param param - The object parameter.\n * @param checkValidity - The function to use to check the type.\n * @param errorOpts - Extra values to make the error message easier to understand.\n * @param errorOpts.txType - The transaction type throwing the error.\n * @param errorOpts.paramName - The name of the parameter in the transaction with the error.\n * @throws ValidationError if the parameter is invalid.\n */\n// eslint-disable-next-line max-params -- helper function\nexport function validateOptionalField<\n T extends Record<string, unknown>,\n K extends keyof T,\n V,\n>(\n tx: T,\n param: K,\n checkValidity: (inp: unknown) => inp is V,\n errorOpts: {\n txType?: string\n paramName?: string\n } = {},\n): asserts tx is T & { [P in K]: V | undefined } {\n const paramNameStr = errorOpts.paramName ?? param\n const txType = errorOpts.txType ?? tx.TransactionType\n if (tx[param] !== undefined && !checkValidity(tx[param])) {\n throw new ValidationError(\n `${txType}: invalid field ${String(paramNameStr)}`,\n )\n }\n}\n\n/* eslint-enable @typescript-eslint/restrict-template-expressions -- checked before */\n\nexport enum GlobalFlags {\n tfInnerBatchTxn = 0x40000000,\n}\n\nexport interface GlobalFlagsInterface {\n tfInnerBatchTxn?: boolean\n}\n\n/**\n * Every transaction has the same set of common fields.\n */\nexport interface BaseTransaction extends Record<string, unknown> {\n /** The unique address of the transaction sender. */\n Account: Account\n /**\n * The type of transaction. Valid types include: `Payment`, `OfferCreate`,\n * `TrustSet`, and many others.\n */\n TransactionType: string\n /**\n * Integer amount of XRP, in drops, to be destroyed as a cost for\n * distributing this transaction to the network. Some transaction types have\n * different minimum requirements.\n */\n Fee?: string\n /**\n * The sequence number of the account sending the transaction. A transaction\n * is only valid if the Sequence number is exactly 1 greater than the previous\n * transaction from the same account. The special case 0 means the transaction\n * is using a Ticket instead.\n */\n Sequence?: number\n /**\n * Hash value identifying another transaction. If provided, this transaction\n * is only valid if the sending account's previously-sent transaction matches\n * the provided hash.\n */\n AccountTxnID?: string\n /** Set of bit-flags for this transaction. */\n Flags?: number | GlobalFlagsInterface\n /**\n * Highest ledger index this transaction can appear in. Specifying this field\n * places a strict upper limit on how long the transaction can wait to be\n * validated or rejected.\n */\n LastLedgerSequence?: number\n /**\n * Additional arbitrary information used to identify this transaction.\n */\n Memos?: Memo[]\n /**\n * Array of objects that represent a multi-signature which authorizes this\n * transaction.\n */\n Signers?: Signer[]\n /**\n * Arbitrary integer used to identify the reason for this payment, or a sender\n * on whose behalf this transaction is made. Conventionally, a refund should\n * specify the initial payment's SourceTag as the refund payment's\n * DestinationTag.\n */\n SourceTag?: number\n /**\n * Hex representation of the public key that corresponds to the private key\n * used to sign this transaction. If an empty string, indicates a\n * multi-signature is present in the Signers field instead.\n */\n SigningPubKey?: string\n /**\n * The sequence number of the ticket to use in place of a Sequence number. If\n * this is provided, Sequence must be 0. Cannot be used with AccountTxnID.\n */\n TicketSequence?: number\n /**\n * The signature that verifies this transaction as originating from the\n * account it says it is from.\n */\n TxnSignature?: string\n /**\n * The network id of the transaction.\n */\n NetworkID?: number\n /**\n * The delegate account that is sending the transaction.\n */\n Delegate?: Account\n}\n\n/**\n * Verify the common fields of a transaction. The validate functionality will be\n * optional, and will check transaction form at runtime. This should be called\n * any time a transaction will be verified.\n *\n * @param common - An interface w/ common transaction fields.\n * @throws When the common param is malformed.\n */\n// eslint-disable-next-line max-statements, max-lines-per-function -- lines required for validation\nexport function validateBaseTransaction(\n common: unknown,\n): asserts common is BaseTransaction {\n if (!isRecord(common)) {\n throw new ValidationError(\n 'BaseTransaction: invalid, expected a valid object',\n )\n }\n\n if (common.TransactionType === undefined) {\n throw new ValidationError('BaseTransaction: missing field TransactionType')\n }\n\n if (typeof common.TransactionType !== 'string') {\n throw new ValidationError('BaseTransaction: TransactionType not string')\n }\n\n if (!TRANSACTION_TYPES.includes(common.TransactionType)) {\n throw new ValidationError(\n `BaseTransaction: Unknown TransactionType ${common.TransactionType}`,\n )\n }\n\n validateRequiredField(common, 'Account', isString)\n\n validateOptionalField(common, 'Fee', isString)\n\n validateOptionalField(common, 'Sequence', isNumber)\n\n validateOptionalField(common, 'AccountTxnID', isString)\n\n validateOptionalField(common, 'LastLedgerSequence', isNumber)\n\n const memos = common.Memos\n if (memos != null && (!isArray(memos) || !memos.every(isMemo))) {\n throw new ValidationError('BaseTransaction: invalid Memos')\n }\n\n const signers = common.Signers\n\n if (\n signers != null &&\n (!isArray(signers) || signers.length === 0 || !signers.every(isSigner))\n ) {\n throw new ValidationError('BaseTransaction: invalid Signers')\n }\n\n validateOptionalField(common, 'SourceTag', isNumber)\n\n validateOptionalField(common, 'SigningPubKey', isString)\n\n validateOptionalField(common, 'TicketSequence', isNumber)\n\n validateOptionalField(common, 'TxnSignature', isString)\n\n validateOptionalField(common, 'NetworkID', isNumber)\n\n validateOptionalField(common, 'Delegate', isAccount)\n\n const delegate = common.Delegate\n if (delegate != null && delegate === common.Account) {\n throw new ValidationError(\n 'BaseTransaction: Account and Delegate addresses cannot be the same',\n )\n }\n}\n\n/**\n * Parse the value of an amount, expressed either in XRP or as an Issued Currency, into a number.\n *\n * @param amount - An Amount to parse for its value.\n * @returns The parsed amount value, or NaN if the amount count not be parsed.\n */\nexport function parseAmountValue(amount: unknown): number {\n if (!isAmount(amount)) {\n return NaN\n }\n if (typeof amount === 'string') {\n return parseFloat(amount)\n }\n return parseFloat(amount.value)\n}\n\n/**\n * Verify the form and type of a CredentialType at runtime.\n *\n * @param tx A CredentialType Transaction.\n * @throws when the CredentialType is malformed.\n */\nexport function validateCredentialType<\n T extends BaseTransaction & Record<string, unknown>,\n>(tx: T): void {\n if (typeof tx.TransactionType !== 'string') {\n throw new ValidationError('Invalid TransactionType')\n }\n if (tx.CredentialType === undefined) {\n throw new ValidationError(\n `${tx.TransactionType}: missing field CredentialType`,\n )\n }\n\n if (!isString(tx.CredentialType)) {\n throw new ValidationError(\n `${tx.TransactionType}: CredentialType must be a string`,\n )\n }\n if (tx.CredentialType.length === 0) {\n throw new ValidationError(\n `${tx.TransactionType}: CredentialType cannot be an empty string`,\n )\n } else if (tx.CredentialType.length > MAX_CREDENTIAL_TYPE_LENGTH) {\n throw new ValidationError(\n `${tx.TransactionType}: CredentialType length cannot be > ${MAX_CREDENTIAL_TYPE_LENGTH}`,\n )\n }\n\n if (!HEX_REGEX.test(tx.CredentialType)) {\n throw new ValidationError(\n `${tx.TransactionType}: CredentialType must be encoded in hex`,\n )\n }\n}\n\n/**\n * Check a CredentialAuthorize array for parameter errors\n *\n * @param credentials An array of credential IDs to check for errors\n * @param transactionType The transaction type to include in error messages\n * @param isStringID Toggle for if array contains IDs instead of AuthorizeCredential objects\n * @param maxCredentials The maximum length of the credentials array.\n * PermissionedDomainSet transaction uses 10, other transactions use 8.\n * @throws Validation Error if the formatting is incorrect\n */\n// eslint-disable-next-line max-params, max-lines-per-function -- separating logic further will add unnecessary complexity\nexport function validateCredentialsList(\n credentials: unknown,\n transactionType: string,\n isStringID: boolean,\n maxCredentials: number,\n): void {\n if (credentials == null) {\n return\n }\n if (!isArray(credentials)) {\n throw new ValidationError(\n `${transactionType}: Credentials must be an array`,\n )\n }\n if (credentials.length > maxCredentials) {\n throw new ValidationError(\n `${transactionType}: Credentials length cannot exceed ${maxCredentials} elements`,\n )\n } else if (credentials.length === 0) {\n throw new ValidationError(\n `${transactionType}: Credentials cannot be an empty array`,\n )\n }\n credentials.forEach((credential) => {\n if (isStringID) {\n if (!isString(credential)) {\n throw new ValidationError(\n `${transactionType}: Invalid Credentials ID list format`,\n )\n }\n } else if (!isAuthorizeCredential(credential)) {\n throw new ValidationError(\n `${transactionType}: Invalid Credentials format`,\n )\n }\n })\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- checked above\n if (containsDuplicates(credentials as string[] | AuthorizeCredential[])) {\n throw new ValidationError(\n `${transactionType}: Credentials cannot contain duplicate elements`,\n )\n }\n}\n\n// Type guard to ensure we're working with AuthorizeCredential[]\n// Note: This is not a rigorous type-guard. A more thorough solution would be to iterate over the array and check each item.\nfunction isAuthorizeCredentialArray(\n list: AuthorizeCredential[] | string[],\n): list is AuthorizeCredential[] {\n return typeof list[0] !== 'string'\n}\n\n/**\n * Check if an array of objects contains any duplicates.\n *\n * @param objectList - Array of objects to check for duplicates\n * @returns True if duplicates exist, false otherwise\n */\nexport function containsDuplicates(\n objectList: AuthorizeCredential[] | string[],\n): boolean {\n // Case-1: Process a list of string-IDs\n if (typeof objectList[0] === 'string') {\n const objSet = new Set(objectList.map((obj) => JSON.stringify(obj)))\n return objSet.size !== objectList.length\n }\n\n // Case-2: Process a list of nested objects\n const seen = new Set<string>()\n\n if (isAuthorizeCredentialArray(objectList)) {\n for (const item of objectList) {\n const key = `${item.Credential.Issuer}-${item.Credential.CredentialType}`\n if (seen.has(key)) {\n return true\n }\n seen.add(key)\n }\n }\n\n return false\n}\n","export type ByteArray = number[] | Uint8Array\n\n/**\n * Check whether two sequences (e.g. Arrays of numbers) are equal.\n *\n * @param arr1 - One of the arrays to compare.\n * @param arr2 - The other array to compare.\n */\nexport function arrayEqual(arr1: ByteArray, arr2: ByteArray): boolean {\n if (arr1.length !== arr2.length) {\n return false\n }\n return arr1.every((value, index) => value === arr2[index])\n}\n\n/**\n * Check whether a value is a scalar\n *\n * @param val - The value to check.\n */\nfunction isScalar(val: ByteArray | number): val is number {\n return typeof val === 'number'\n}\n\n/**\n * Concatenate all `arguments` into a single array. Each argument can be either\n * a single element or a sequence, which has a `length` property and supports\n * element retrieval via sequence[ix].\n *\n * > concatArgs(1, [2, 3], Uint8Array.from([4,5]), new Uint8Array([6, 7]));\n * [1,2,3,4,5,6,7]\n *\n * @param args - Concatenate of these args into a single array.\n * @returns Array of concatenated arguments\n */\n\nexport function concatArgs(...args: Array<number | ByteArray>): number[] {\n return args.flatMap((arg) => {\n return isScalar(arg) ? [arg] : Array.from(arg)\n })\n}\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n isIssuedCurrencyAmount,\n isAccount,\n validateRequiredField,\n validateOptionalField,\n isNumber,\n Account,\n} from './common'\n\n/**\n * Create a Check object in the ledger, which is a deferred payment that can be\n * cashed by its intended destination. The sender of this transaction is the\n * sender of the Check.\n *\n * @category Transaction Models\n */\nexport interface CheckCreate extends BaseTransaction {\n TransactionType: 'CheckCreate'\n /** The unique address of the account that can cash the Check. */\n Destination: Account\n /**\n * Maximum amount of source currency the Check is allowed to debit the\n * sender, including transfer fees on non-XRP currencies. The Check can only\n * credit the destination with the same currency (from the same issuer, for\n * non-XRP currencies). For non-XRP amounts, the nested field names MUST be.\n * lower-case.\n */\n SendMax: Amount\n /**\n * Arbitrary tag that identifies the reason for the Check, or a hosted.\n * recipient to pay.\n */\n DestinationTag?: number\n /**\n * Time after which the Check is no longer valid, in seconds since the Ripple.\n * Epoch.\n */\n Expiration?: number\n /**\n * Arbitrary 256-bit hash representing a specific reason or identifier for.\n * this Check.\n */\n InvoiceID?: string\n}\n\n/**\n * Verify the form and type of an CheckCreate at runtime.\n *\n * @param tx - An CheckCreate Transaction.\n * @throws When the CheckCreate is Malformed.\n */\nexport function validateCheckCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.SendMax === undefined) {\n throw new ValidationError('CheckCreate: missing field SendMax')\n }\n\n validateRequiredField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n if (typeof tx.SendMax !== 'string' && !isIssuedCurrencyAmount(tx.SendMax)) {\n throw new ValidationError('CheckCreate: invalid SendMax')\n }\n\n if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') {\n throw new ValidationError('CheckCreate: invalid Expiration')\n }\n\n if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== 'string') {\n throw new ValidationError('CheckCreate: invalid InvoiceID')\n }\n}\n","import { sha512 as nobleImpl } from '@noble/hashes/sha512'\n\nimport wrapNoble from '../internal/wrapNoble'\n\n/**\n * Wrap noble-libs's sha512 implementation in HashFn\n */\nexport const sha512 = wrapNoble(nobleImpl)\n","import { ValidationError } from '../../errors'\nimport { SignerEntry } from '../common'\n\nimport {\n BaseTransaction,\n isArray,\n isNumber,\n isRecord,\n isString,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * The SignerListSet transaction creates, replaces, or removes a list of\n * signers that can be used to multi-sign a transaction.\n *\n * @category Transaction Models\n */\nexport interface SignerListSet extends BaseTransaction {\n TransactionType: 'SignerListSet'\n /**\n * A target number for the signer weights. A multi-signature from this list\n * is valid only if the sum weights of the signatures provided is greater than\n * or equal to this value. To delete a signer list, use the value 0.\n */\n SignerQuorum: number\n /**\n * Array of SignerEntry objects, indicating the addresses and weights of\n * signers in this list. This signer list must have at least 1 member and no\n * more than 32 members. No address may appear more than once in the list, nor\n * may the Account submitting the transaction appear in the list.\n */\n SignerEntries?: SignerEntry[]\n}\n\nconst MAX_SIGNERS = 32\n\nconst HEX_WALLET_LOCATOR_REGEX = /^[0-9A-Fa-f]{64}$/u\n\n/**\n * Verify the form and type of an SignerListSet at runtime.\n *\n * @param tx - An SignerListSet Transaction.\n * @throws When the SignerListSet is Malformed.\n */\nexport function validateSignerListSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'SignerQuorum', isNumber)\n\n // All other checks are for if SignerQuorum is greater than 0\n if (tx.SignerQuorum === 0) {\n return\n }\n\n validateRequiredField(tx, 'SignerEntries', isArray)\n if (tx.SignerEntries.length === 0) {\n throw new ValidationError(\n 'SignerListSet: need at least 1 member in SignerEntries',\n )\n }\n\n if (tx.SignerEntries.length > MAX_SIGNERS) {\n throw new ValidationError(\n `SignerListSet: maximum of ${MAX_SIGNERS} members allowed in SignerEntries`,\n )\n }\n\n for (const entry of tx.SignerEntries) {\n if (!isRecord(entry) || !isRecord(entry.SignerEntry)) {\n throw new ValidationError(\n 'SignerListSet: SignerEntries must be an array of SignerEntry objects',\n )\n }\n const signerEntry = entry.SignerEntry\n const { WalletLocator } = signerEntry\n if (\n WalletLocator != null &&\n (!isString(WalletLocator) ||\n !HEX_WALLET_LOCATOR_REGEX.test(WalletLocator))\n ) {\n throw new ValidationError(\n `SignerListSet: WalletLocator in SignerEntry must be a 256-bit (32-byte) hexadecimal value`,\n )\n }\n }\n}\n","import { BinaryParser } from '../serdes/binary-parser'\n\nimport { AccountID } from './account-id'\nimport { JsonObject, SerializedType } from './serialized-type'\nimport { Issue, IssueObject } from './issue'\nimport { concat } from '@xrplf/isomorphic/utils'\n\n/**\n * Interface for JSON objects that represent cross-chain bridges\n */\ninterface XChainBridgeObject extends JsonObject {\n LockingChainDoor: string\n LockingChainIssue: IssueObject | string\n IssuingChainDoor: string\n IssuingChainIssue: IssueObject | string\n}\n\n/**\n * Type guard for XChainBridgeObject\n */\nfunction isXChainBridgeObject(arg): arg is XChainBridgeObject {\n const keys = Object.keys(arg).sort()\n return (\n keys.length === 4 &&\n keys[0] === 'IssuingChainDoor' &&\n keys[1] === 'IssuingChainIssue' &&\n keys[2] === 'LockingChainDoor' &&\n keys[3] === 'LockingChainIssue'\n )\n}\n\n/**\n * Class for serializing/deserializing XChainBridges\n */\nclass XChainBridge extends SerializedType {\n static readonly ZERO_XCHAIN_BRIDGE: XChainBridge = new XChainBridge(\n concat([\n Uint8Array.from([0x14]),\n new Uint8Array(40),\n Uint8Array.from([0x14]),\n new Uint8Array(40),\n ]),\n )\n\n static readonly TYPE_ORDER: { name: string; type: typeof SerializedType }[] =\n [\n { name: 'LockingChainDoor', type: AccountID },\n { name: 'LockingChainIssue', type: Issue },\n { name: 'IssuingChainDoor', type: AccountID },\n { name: 'IssuingChainIssue', type: Issue },\n ]\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? XChainBridge.ZERO_XCHAIN_BRIDGE.bytes)\n }\n\n /**\n * Construct a cross-chain bridge from a JSON\n *\n * @param value XChainBridge or JSON to parse into an XChainBridge\n * @returns An XChainBridge object\n */\n static from<T extends XChainBridge | XChainBridgeObject>(\n value: T,\n ): XChainBridge {\n if (value instanceof XChainBridge) {\n return value\n }\n\n if (!isXChainBridgeObject(value)) {\n throw new Error('Invalid type to construct an XChainBridge')\n }\n\n const bytes: Array<Uint8Array> = []\n this.TYPE_ORDER.forEach((item) => {\n const { name, type } = item\n if (type === AccountID) {\n bytes.push(Uint8Array.from([0x14]))\n }\n const object = type.from(value[name])\n bytes.push(object.toBytes())\n })\n return new XChainBridge(concat(bytes))\n }\n\n /**\n * Read an XChainBridge from a BinaryParser\n *\n * @param parser BinaryParser to read the XChainBridge from\n * @returns An XChainBridge object\n */\n static fromParser(parser: BinaryParser): XChainBridge {\n const bytes: Array<Uint8Array> = []\n\n this.TYPE_ORDER.forEach((item) => {\n const { type } = item\n if (type === AccountID) {\n parser.skip(1)\n bytes.push(Uint8Array.from([0x14]))\n }\n const object = type.fromParser(parser)\n bytes.push(object.toBytes())\n })\n\n return new XChainBridge(concat(bytes))\n }\n\n /**\n * Get the JSON representation of this XChainBridge\n *\n * @returns the JSON interpretation of this.bytes\n */\n toJSON(): XChainBridgeObject {\n const parser = new BinaryParser(this.toString())\n const json = {}\n XChainBridge.TYPE_ORDER.forEach((item) => {\n const { name, type } = item\n if (type === AccountID) {\n parser.skip(1)\n }\n const object = type.fromParser(parser).toJSON()\n json[name] = object\n })\n return json as XChainBridgeObject\n }\n}\n\nexport { XChainBridge, XChainBridgeObject }\n","import { BytesList, BinaryParser } from '../binary'\n\n/*\n * @brief: Bytes, name, and ordinal representing one type, ledger_type, transaction type, or result\n */\nexport class Bytes {\n readonly bytes: Uint8Array\n\n constructor(\n readonly name: string,\n readonly ordinal: number,\n readonly ordinalWidth: number,\n ) {\n this.bytes = new Uint8Array(ordinalWidth)\n for (let i = 0; i < ordinalWidth; i++) {\n this.bytes[ordinalWidth - i - 1] = (ordinal >>> (i * 8)) & 0xff\n }\n }\n\n toJSON(): string {\n return this.name\n }\n\n toBytesSink(sink: BytesList): void {\n sink.put(this.bytes)\n }\n\n toBytes(): Uint8Array {\n return this.bytes\n }\n}\n\n/*\n * @brief: Collection of Bytes objects, mapping bidirectionally\n */\nexport class BytesLookup {\n constructor(types: Record<string, number>, readonly ordinalWidth: number) {\n Object.entries(types).forEach(([k, v]) => {\n this.add(k, v)\n })\n }\n\n /**\n * Add a new name value pair to the BytesLookup.\n *\n * @param name - A human readable name for the field.\n * @param value - The numeric value for the field.\n * @throws if the name or value already exist in the lookup because it's unclear how to decode.\n */\n add(name: string, value: number): void {\n if (this[name]) {\n throw new SyntaxError(\n `Attempted to add a value with a duplicate name \"${name}\". This is not allowed because it is unclear how to decode.`,\n )\n }\n if (this[value.toString()]) {\n throw new SyntaxError(\n `Attempted to add a duplicate value under a different name (Given name: \"${name}\" and previous name: \"${\n this[value.toString()]\n }. This is not allowed because it is unclear how to decode.\\nGiven value: ${value.toString()}`,\n )\n }\n this[name] = new Bytes(name, value, this.ordinalWidth)\n this[value.toString()] = this[name]\n }\n\n from(value: Bytes | string): Bytes {\n return value instanceof Bytes ? value : (this[value] as Bytes)\n }\n\n fromParser(parser: BinaryParser): Bytes {\n return this.from(parser.readUIntN(this.ordinalWidth).toString())\n }\n}\n","import BigNumber from 'bignumber.js'\n\nimport {\n Amount,\n Balance,\n IssuedCurrencyAmount,\n TransactionMetadata,\n Node,\n} from '../models'\n\nimport { groupBy } from './collections'\nimport { dropsToXrp } from './xrpConversion'\n\ninterface BalanceChange {\n account: string\n balance: Balance\n}\ninterface Fields {\n Account?: string\n Balance?: Amount\n LowLimit?: IssuedCurrencyAmount\n HighLimit?: IssuedCurrencyAmount\n // eslint-disable-next-line @typescript-eslint/member-ordering -- okay here, just some of the fields are typed to make it easier\n [field: string]: unknown\n}\n\ninterface NormalizedNode {\n // 'CreatedNode' | 'ModifiedNode' | 'DeletedNode'\n NodeType: string\n LedgerEntryType: string\n LedgerIndex: string\n NewFields?: Fields\n FinalFields?: Fields\n PreviousFields?: Fields\n PreviousTxnID?: string\n PreviousTxnLgrSeq?: number\n}\n\nfunction normalizeNode(affectedNode: Node): NormalizedNode {\n const diffType = Object.keys(affectedNode)[0]\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- not quite right, but close enough\n const node = affectedNode[diffType] as NormalizedNode\n return {\n ...node,\n NodeType: diffType,\n LedgerEntryType: node.LedgerEntryType,\n LedgerIndex: node.LedgerIndex,\n NewFields: node.NewFields,\n FinalFields: node.FinalFields,\n PreviousFields: node.PreviousFields,\n }\n}\n\nfunction normalizeNodes(metadata: TransactionMetadata): NormalizedNode[] {\n if (metadata.AffectedNodes.length === 0) {\n return []\n }\n return metadata.AffectedNodes.map(normalizeNode)\n}\n\nfunction groupByAccount(balanceChanges: BalanceChange[]): Array<{\n account: string\n balances: Balance[]\n}> {\n const grouped = groupBy(balanceChanges, (node) => node.account)\n return Object.entries(grouped).map(([account, items]) => {\n return { account, balances: items.map((item) => item.balance) }\n })\n}\n\nfunction getValue(balance: Amount): BigNumber {\n if (typeof balance === 'string') {\n return new BigNumber(balance)\n }\n return new BigNumber(balance.value)\n}\n\nfunction computeBalanceChange(node: NormalizedNode): BigNumber | null {\n let value: BigNumber | null = null\n if (node.NewFields?.Balance) {\n value = getValue(node.NewFields.Balance)\n } else if (node.PreviousFields?.Balance && node.FinalFields?.Balance) {\n value = getValue(node.FinalFields.Balance).minus(\n getValue(node.PreviousFields.Balance),\n )\n }\n if (value === null || value.isZero()) {\n return null\n }\n return value\n}\n\nfunction getXRPQuantity(\n node: NormalizedNode,\n): { account: string; balance: Balance } | null {\n const value = computeBalanceChange(node)\n\n if (value === null) {\n return null\n }\n\n return {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- okay here\n account: (node.FinalFields?.Account ?? node.NewFields?.Account) as string,\n balance: {\n currency: 'XRP',\n value: dropsToXrp(value).toString(),\n },\n }\n}\n\nfunction flipTrustlinePerspective(balanceChange: BalanceChange): BalanceChange {\n const negatedBalance = new BigNumber(balanceChange.balance.value).negated()\n return {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- we know this is true\n account: balanceChange.balance.issuer as string,\n balance: {\n issuer: balanceChange.account,\n currency: balanceChange.balance.currency,\n value: negatedBalance.toString(),\n },\n }\n}\n\nfunction getTrustlineQuantity(node: NormalizedNode): BalanceChange[] | null {\n const value = computeBalanceChange(node)\n\n if (value === null) {\n return null\n }\n\n /*\n * A trustline can be created with a non-zero starting balance.\n * If an offer is placed to acquire an asset with no existing trustline,\n * the trustline can be created when the offer is taken.\n */\n const fields = node.NewFields == null ? node.FinalFields : node.NewFields\n\n // the balance is always from low node's perspective\n const result = {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- we know that this is true\n account: fields?.LowLimit?.issuer as string,\n balance: {\n issuer: fields?.HighLimit?.issuer,\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- we know that this is true\n currency: (fields?.Balance as IssuedCurrencyAmount).currency,\n value: value.toString(),\n },\n }\n return [result, flipTrustlinePerspective(result)]\n}\n\n/**\n * Computes the complete list of every balance that changed in the ledger\n * as a result of the given transaction.\n *\n * @param metadata - Transaction metadata.\n * @returns Parsed balance changes.\n * @category Utilities\n */\nexport default function getBalanceChanges(\n metadata: TransactionMetadata,\n): Array<{\n account: string\n balances: Balance[]\n}> {\n const quantities = normalizeNodes(metadata).map((node) => {\n if (node.LedgerEntryType === 'AccountRoot') {\n const xrpQuantity = getXRPQuantity(node)\n if (xrpQuantity == null) {\n return []\n }\n return [xrpQuantity]\n }\n if (node.LedgerEntryType === 'RippleState') {\n const trustlineQuantity = getTrustlineQuantity(node)\n if (trustlineQuantity == null) {\n return []\n }\n return trustlineQuantity\n }\n return []\n })\n return groupByAccount(quantities.flat())\n}\n","import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, validateBaseTransaction } from './common'\n\n/**\n * A TicketCreate transaction sets aside one or more sequence numbers as\n * Tickets.\n *\n * @category Transaction Models\n */\nexport interface TicketCreate extends BaseTransaction {\n TransactionType: 'TicketCreate'\n /**\n * How many Tickets to create. This must be a positive number and cannot\n * cause the account to own more than 250 Tickets after executing this\n * transaction.\n */\n TicketCount: number\n}\n\nconst MAX_TICKETS = 250\n\n/**\n * Verify the form and type of a TicketCreate at runtime.\n *\n * @param tx - A TicketCreate Transaction.\n * @throws When the TicketCreate is malformed.\n */\nexport function validateTicketCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n const { TicketCount } = tx\n\n if (TicketCount === undefined) {\n throw new ValidationError('TicketCreate: missing field TicketCount')\n }\n\n if (typeof TicketCount !== 'number') {\n throw new ValidationError('TicketCreate: TicketCount must be a number')\n }\n\n if (\n !Number.isInteger(TicketCount) ||\n TicketCount < 1 ||\n TicketCount > MAX_TICKETS\n ) {\n throw new ValidationError(\n 'TicketCreate: TicketCount must be an integer from 1 to 250',\n )\n }\n}\n","import {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateRequiredField,\n Account,\n validateOptionalField,\n isAccount,\n GlobalFlagsInterface,\n} from './common'\n\n/**\n * Transaction Flags for an MPTokenAuthorize Transaction.\n *\n * @category Transaction Flags\n */\nexport enum MPTokenAuthorizeFlags {\n /**\n * If set and transaction is submitted by a holder, it indicates that the holder no\n * longer wants to hold the MPToken, which will be deleted as a result. If the the holder's\n * MPToken has non-zero balance while trying to set this flag, the transaction will fail. On\n * the other hand, if set and transaction is submitted by an issuer, it would mean that the\n * issuer wants to unauthorize the holder (only applicable for allow-listing),\n * which would unset the lsfMPTAuthorized flag on the MPToken.\n */\n tfMPTUnauthorize = 0x00000001,\n}\n\n/**\n * Map of flags to boolean values representing {@link MPTokenAuthorize} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface MPTokenAuthorizeFlagsInterface extends GlobalFlagsInterface {\n tfMPTUnauthorize?: boolean\n}\n\n/**\n * The MPTokenAuthorize transaction is used to globally lock/unlock a MPTokenIssuance,\n * or lock/unlock an individual's MPToken.\n */\nexport interface MPTokenAuthorize extends BaseTransaction {\n TransactionType: 'MPTokenAuthorize'\n /**\n * Identifies the MPTokenIssuance\n */\n MPTokenIssuanceID: string\n /**\n * An optional XRPL Address of an individual token holder balance to lock/unlock.\n * If omitted, this transaction will apply to all any accounts holding MPTs.\n */\n Holder?: Account\n Flags?: number | MPTokenAuthorizeFlagsInterface\n}\n\n/**\n * Verify the form and type of an MPTokenAuthorize at runtime.\n *\n * @param tx - An MPTokenAuthorize Transaction.\n * @throws When the MPTokenAuthorize is Malformed.\n */\nexport function validateMPTokenAuthorize(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n validateRequiredField(tx, 'MPTokenIssuanceID', isString)\n validateOptionalField(tx, 'Holder', isAccount)\n}\n","import InnerNode from './InnerNode'\nimport LeafNode from './LeafNode'\nimport { NodeType } from './node'\n\n/**\n * SHAMap is the hash structure used to model ledgers.\n * If the root hash is equivalent, that means all nodes should be equivalent as well.\n */\nclass SHAMap {\n public root: InnerNode\n\n /**\n * SHAMap tree constructor.\n */\n public constructor() {\n this.root = new InnerNode(0)\n }\n\n /**\n * Get the hash of the SHAMap.\n *\n * @returns The hash of the root of the SHAMap.\n */\n public get hash(): string {\n return this.root.hash\n }\n\n /**\n * Add an item to the SHAMap.\n *\n * @param tag - Index of the Node to add.\n * @param data - Data to insert into the tree.\n * @param type - Type of the node to add.\n */\n public addItem(tag: string, data: string, type: NodeType): void {\n this.root.addItem(tag, new LeafNode(tag, data, type))\n }\n}\n\nexport * from './node'\nexport default SHAMap\n","const assertHelper: {\n ok: (cond: boolean, message?: string) => asserts cond is true\n} = {\n ok(cond, message): asserts cond is true {\n if (!cond) {\n throw new Error(message)\n }\n },\n}\n\nexport default assertHelper\n","import BigNumber from 'bignumber.js'\n\nimport type { Client } from '../client'\nimport { ValidationError } from '../errors'\nimport { LedgerIndex } from '../models/common'\nimport { OfferFlags } from '../models/ledger/Offer'\nimport {\n BookOffer,\n BookOfferCurrency,\n BookOffersRequest,\n} from '../models/methods/bookOffers'\n\nconst DEFAULT_LIMIT = 20\n\nfunction sortOffers(offers: BookOffer[]): BookOffer[] {\n return offers.sort((offerA, offerB) => {\n const qualityA = offerA.quality ?? 0\n const qualityB = offerB.quality ?? 0\n\n return new BigNumber(qualityA).comparedTo(qualityB)\n })\n}\n\nconst getOrderbookOptionsSet = new Set([\n 'limit',\n 'ledger_index',\n 'ledger_hash',\n 'taker',\n])\n\n/**\n * Represents the options for retrieving the order book.\n */\nexport interface GetOrderBookOptions {\n /**\n * The limit on the number of offers to return.\n */\n limit?: number\n /**\n * The ledger index of the ledger to use.\n */\n ledger_index?: LedgerIndex\n /**\n * The ledger hash of the ledger to use.\n */\n ledger_hash?: string | null\n /**\n * The account that takes the offers.\n */\n taker?: string | null\n}\n\n/**\n * Validates the options for retrieving the order book.\n *\n * @param options - The options to validate.\n * @throws {ValidationError} If any validation errors occur.\n */\n// eslint-disable-next-line complexity -- Necessary for validation.\nexport function validateOrderbookOptions(options: GetOrderBookOptions): void {\n for (const key of Object.keys(options)) {\n if (!getOrderbookOptionsSet.has(key)) {\n throw new ValidationError(`Unexpected option: ${key}`, options)\n }\n }\n\n if (options.limit && typeof options.limit !== 'number') {\n throw new ValidationError('limit must be a number', options.limit)\n }\n\n if (\n options.ledger_index &&\n !(\n typeof options.ledger_index === 'number' ||\n (typeof options.ledger_index === 'string' &&\n ['validated', 'closed', 'current'].includes(options.ledger_index))\n )\n ) {\n throw new ValidationError(\n 'ledger_index must be a number or a string of \"validated\", \"closed\", or \"current\"',\n options.ledger_index,\n )\n }\n\n if (\n options.ledger_hash !== undefined &&\n options.ledger_hash !== null &&\n typeof options.ledger_hash !== 'string'\n ) {\n throw new ValidationError(\n 'ledger_hash must be a string',\n options.ledger_hash,\n )\n }\n\n if (options.taker !== undefined && typeof options.taker !== 'string') {\n throw new ValidationError('taker must be a string', options.taker)\n }\n}\n\n/**\n * Creates a request object for retrieving book offers.\n *\n * @param currency1 - The first currency in the pair.\n * @param currency2 - The second currency in the pair.\n * @param options - Additional options for the request.\n * @param [options.limit] - The maximum number of offers to retrieve.\n * @param [options.ledger_index] - The ledger index to use for retrieval.\n * @param [options.ledger_hash] - The ledger hash to use for retrieval.\n * @param [options.taker] - The taker address for retrieval.\n * @returns The created request object.\n */\nexport function createBookOffersRequest(\n currency1: BookOfferCurrency,\n currency2: BookOfferCurrency,\n options: {\n limit?: number\n ledger_index?: LedgerIndex\n ledger_hash?: string | null\n taker?: string | null\n },\n): BookOffersRequest {\n const request: BookOffersRequest = {\n command: 'book_offers',\n taker_pays: currency1,\n taker_gets: currency2,\n ledger_index: options.ledger_index ?? 'validated',\n ledger_hash: options.ledger_hash === null ? undefined : options.ledger_hash,\n limit: options.limit ?? DEFAULT_LIMIT,\n taker: options.taker ? options.taker : undefined,\n }\n\n return request\n}\n\ntype BookOfferResult = BookOffer[]\n\n/**\n * Retrieves all book offer results using the given request.\n *\n * @param client - The Ripple client.\n * @param request - The request object.\n * @returns The array of book offer results.\n */\nexport async function requestAllOffers(\n client: Client,\n request: BookOffersRequest,\n): Promise<BookOfferResult[]> {\n const results = await client.requestAll(request)\n return results.map((result) => result.result.offers)\n}\n\n/**\n * Creates a reverse request object by swapping the taker pays and taker gets amounts.\n *\n * @param request - The original request object.\n * @returns The reverse request object.\n */\nexport function reverseRequest(request: BookOffersRequest): BookOffersRequest {\n return {\n ...request,\n taker_pays: request.taker_gets,\n taker_gets: request.taker_pays,\n }\n}\n\n/**\n * Extracts the offers from the book offer results.\n *\n * @param offerResults - The array of book offer results.\n * @returns The extracted offers.\n */\nexport function extractOffers(offerResults: BookOfferResult[]): BookOffer[] {\n return offerResults.flatMap((offerResult) => offerResult)\n}\n\n/**\n * Combines the direct and reverse offers into a single array.\n *\n * @param directOffers - The direct offers.\n * @param reverseOffers - The reverse offers.\n * @returns The combined array of offers.\n */\nexport function combineOrders(\n directOffers: BookOffer[],\n reverseOffers: BookOffer[],\n): BookOffer[] {\n return [...directOffers, ...reverseOffers]\n}\n\n/**\n * Separates the buy and sell orders from the given array of orders.\n *\n * @param orders - The array of orders.\n * @returns The separated buy and sell orders.\n */\nexport function separateBuySellOrders(orders: BookOffer[]): {\n buy: BookOffer[]\n sell: BookOffer[]\n} {\n const buy: BookOffer[] = []\n const sell: BookOffer[] = []\n\n orders.forEach((order) => {\n // eslint-disable-next-line no-bitwise -- necessary for flags check\n if ((order.Flags & OfferFlags.lsfSell) === 0) {\n buy.push(order)\n } else {\n sell.push(order)\n }\n })\n\n return { buy, sell }\n}\n\n/**\n * Sorts and limits the given array of offers.\n *\n * @param offers - The array of offers to sort and limit.\n * @param [limit] - The maximum number of offers to include.\n * @returns The sorted and limited array of offers.\n */\nexport function sortAndLimitOffers(\n offers: BookOffer[],\n limit?: number,\n): BookOffer[] {\n const sortedOffers = sortOffers(offers)\n return sortedOffers.slice(0, limit)\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isNumber,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * Sequester XRP until the escrow process either finishes or is canceled.\n *\n * @category Transaction Models\n */\nexport interface EscrowCreate extends BaseTransaction {\n TransactionType: 'EscrowCreate'\n /**\n * Amount of XRP, in drops, to deduct from the sender's balance and escrow.\n * Once escrowed, the XRP can either go to the Destination address (after the.\n * FinishAfter time) or returned to the sender (after the CancelAfter time).\n */\n Amount: string\n /** Address to receive escrowed XRP. */\n Destination: Account\n /**\n * The time, in seconds since the Ripple Epoch, when this escrow expires.\n * This value is immutable; the funds can only be returned the sender after.\n * this time.\n */\n CancelAfter?: number\n /**\n * The time, in seconds since the Ripple Epoch, when the escrowed XRP can be\n * released to the recipient. This value is immutable; the funds cannot move.\n * until this time is reached.\n */\n FinishAfter?: number\n /**\n * Hex value representing a PREIMAGE-SHA-256 crypto-condition . The funds can.\n * only be delivered to the recipient if this condition is fulfilled.\n */\n Condition?: string\n /**\n * Arbitrary tag to further specify the destination for this escrowed.\n * payment, such as a hosted recipient at the destination address.\n */\n DestinationTag?: number\n\n FinishFunction?: string\n\n Data?: string\n}\n\n/**\n * Verify the form and type of an EscrowCreate at runtime.\n *\n * @param tx - An EscrowCreate Transaction.\n * @throws When the EscrowCreate is Malformed.\n */\nexport function validateEscrowCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Amount === undefined) {\n throw new ValidationError('EscrowCreate: missing field Amount')\n }\n\n if (typeof tx.Amount !== 'string') {\n throw new ValidationError('EscrowCreate: Amount must be a string')\n }\n\n validateRequiredField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n if (tx.CancelAfter === undefined && tx.FinishAfter === undefined) {\n throw new ValidationError(\n 'EscrowCreate: Either CancelAfter or FinishAfter must be specified',\n )\n }\n\n if (\n tx.FinishAfter === undefined &&\n tx.Condition === undefined &&\n tx.FinishFunction === undefined\n ) {\n throw new ValidationError(\n 'EscrowCreate: Either FinishAfter, Condition, or FinishFunction must be specified',\n )\n }\n\n if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== 'number') {\n throw new ValidationError('EscrowCreate: CancelAfter must be a number')\n }\n\n if (tx.FinishAfter !== undefined && typeof tx.FinishAfter !== 'number') {\n throw new ValidationError('EscrowCreate: FinishAfter must be a number')\n }\n\n if (tx.Condition !== undefined && typeof tx.Condition !== 'string') {\n throw new ValidationError('EscrowCreate: Condition must be a string')\n }\n}\n","import { Comparable } from './serialized-type'\n\n/**\n * Compare numbers and bigInts n1 and n2\n *\n * @param n1 First object to compare\n * @param n2 Second object to compare\n * @returns -1, 0, or 1, depending on how the two objects compare\n */\nfunction compare(n1: number | bigint, n2: number | bigint): number {\n return n1 < n2 ? -1 : n1 == n2 ? 0 : 1\n}\n\n/**\n * Base class for serializing and deserializing unsigned integers.\n */\nabstract class UInt extends Comparable<UInt | number> {\n protected static width: number\n\n constructor(bytes: Uint8Array) {\n super(bytes)\n }\n\n /**\n * Overload of compareTo for Comparable\n *\n * @param other other UInt to compare this to\n * @returns -1, 0, or 1 depending on how the objects relate to each other\n */\n compareTo(other: UInt | number): number {\n return compare(this.valueOf(), other.valueOf())\n }\n\n /**\n * Convert a UInt object to JSON\n *\n * @returns number or string represented by this.bytes\n */\n toJSON(): number | string {\n const val = this.valueOf()\n return typeof val === 'number' ? val : val.toString()\n }\n\n /**\n * Get the value of the UInt represented by this.bytes\n *\n * @returns the value\n */\n abstract valueOf(): number | bigint\n\n static checkUintRange(val: number, min: number, max: number): void {\n if (val < min || val > max) {\n throw new Error(\n `Invalid ${this.constructor.name}: ${val} must be >= ${min} and <= ${max}`,\n )\n }\n }\n}\n\nexport { UInt }\n","import { Amount, MPTAmount } from '../common'\n\nimport { BaseTransaction } from './common'\nimport {\n MPTokenIssuanceCreate,\n MPTokenIssuanceCreateMetadata,\n} from './MPTokenIssuanceCreate'\nimport {\n NFTokenAcceptOffer,\n NFTokenAcceptOfferMetadata,\n} from './NFTokenAcceptOffer'\nimport {\n NFTokenCancelOffer,\n NFTokenCancelOfferMetadata,\n} from './NFTokenCancelOffer'\nimport {\n NFTokenCreateOffer,\n NFTokenCreateOfferMetadata,\n} from './NFTokenCreateOffer'\nimport { NFTokenMint, NFTokenMintMetadata } from './NFTokenMint'\nimport { Payment, PaymentMetadata } from './payment'\nimport type { Transaction } from './transaction'\n\nexport interface CreatedNode {\n CreatedNode: {\n LedgerEntryType: string\n LedgerIndex: string\n NewFields: { [field: string]: unknown }\n }\n}\n\nexport interface ModifiedNode {\n ModifiedNode: {\n LedgerEntryType: string\n LedgerIndex: string\n FinalFields?: { [field: string]: unknown }\n PreviousFields?: { [field: string]: unknown }\n PreviousTxnID?: string\n PreviousTxnLgrSeq?: number\n }\n}\n\nexport interface DeletedNode {\n DeletedNode: {\n LedgerEntryType: string\n LedgerIndex: string\n PreviousFields?: { [field: string]: unknown }\n FinalFields: { [field: string]: unknown }\n }\n}\n\nexport type Node = CreatedNode | ModifiedNode | DeletedNode\n\n/**\n * A typeguard to check if a node is a CreatedNode.\n *\n * @param node - A node from metadata.\n * @returns whether the given node is a CreatedNode.\n */\nexport function isCreatedNode(node: Node): node is CreatedNode {\n return Object.prototype.hasOwnProperty.call(node, `CreatedNode`)\n}\n\n/**\n * A typeguard to check if a node is a ModifiedNode.\n *\n * @param node - A node from metadata.\n * @returns whether the given node is a ModifiedNode.\n */\nexport function isModifiedNode(node: Node): node is ModifiedNode {\n return Object.prototype.hasOwnProperty.call(node, `ModifiedNode`)\n}\n\n/**\n * A typeguard to check if a node is a DeletedNode.\n *\n * @param node - A node from metadata.\n * @returns whether the given node is a DeletedNode.\n */\nexport function isDeletedNode(node: Node): node is DeletedNode {\n return Object.prototype.hasOwnProperty.call(node, `DeletedNode`)\n}\n\nexport interface TransactionMetadataBase {\n AffectedNodes: Node[]\n DeliveredAmount?: Amount | MPTAmount\n // \"unavailable\" possible for transactions before 2014-01-20\n delivered_amount?: Amount | MPTAmount | 'unavailable'\n TransactionIndex: number\n TransactionResult: string\n\n ParentBatchID?: string\n}\n\nexport type TransactionMetadata<T extends BaseTransaction = Transaction> =\n T extends Payment\n ? PaymentMetadata\n : T extends NFTokenMint\n ? NFTokenMintMetadata\n : T extends NFTokenCreateOffer\n ? NFTokenCreateOfferMetadata\n : T extends NFTokenAcceptOffer\n ? NFTokenAcceptOfferMetadata\n : T extends NFTokenCancelOffer\n ? NFTokenCancelOfferMetadata\n : T extends MPTokenIssuanceCreate\n ? MPTokenIssuanceCreateMetadata\n : TransactionMetadataBase\n","import BigNumber from 'bignumber.js'\n\nimport { ValidationError } from '../errors'\n\nconst BASE_TEN = 10\nconst ONE_BILLION = '1000000000'\nconst TWO_BILLION = '2000000000'\n\nfunction percentToDecimal(percent: string): string {\n if (!percent.endsWith('%')) {\n throw new ValidationError(`Value ${percent} must end with %`)\n }\n\n // Split the string on % and filter out any empty strings\n const split = percent.split('%').filter((str) => str !== '')\n if (split.length !== 1) {\n throw new ValidationError(`Value ${percent} contains too many % signs`)\n }\n\n return new BigNumber(split[0]).dividedBy('100').toString(BASE_TEN)\n}\n\n/**\n * Converts a string decimal to \"billionths\" format for use with TransferRate.\n *\n * @param decimal - A string decimal between 0 and 1.00\n * @returns A number in the \"billionths\" format.\n * @throws ValidationError when the parameter is not convertible to\n * \"billionths\" format.\n * @category Utilities\n */\nexport function decimalToTransferRate(decimal: string): number {\n const rate = new BigNumber(decimal).times(ONE_BILLION).plus(ONE_BILLION)\n\n if (rate.isLessThan(ONE_BILLION) || rate.isGreaterThan(TWO_BILLION)) {\n throw new ValidationError(`Decimal value must be between 0 and 1.00.`)\n }\n\n const billionths = rate.toString(BASE_TEN)\n\n if (billionths === ONE_BILLION) {\n return 0\n }\n\n if (billionths === 'NaN') {\n throw new ValidationError(`Value is not a number`)\n }\n\n if (billionths.includes('.')) {\n throw new ValidationError(`Decimal exceeds maximum precision.`)\n }\n\n return Number(billionths)\n}\n\n/**\n * Converts a string percent to \"billionths\" format for use with TransferRate.\n *\n * @param percent - A string percent between 0% and 100%.\n * @returns A number in the \"billionths\" format.\n * @throws ValidationError when the percent parameter is not convertible to\n * \"billionths\" format.\n * @category Utilities\n */\nexport function percentToTransferRate(percent: string): number {\n return decimalToTransferRate(percentToDecimal(percent))\n}\n\n/**\n * Converts a string decimal to the \"billionths\" format for use with QualityIn/\n * QualityOut\n *\n * @param decimal - A string decimal (i.e. \".00034\").\n * @returns A number in the \"billionths\" format.\n * @throws ValidationError when the parameter is not convertible to\n * \"billionths\" format.\n * @category Utilities\n */\nexport function decimalToQuality(decimal: string): number {\n const rate = new BigNumber(decimal).times(ONE_BILLION)\n\n const billionths = rate.toString(BASE_TEN)\n\n if (billionths === 'NaN') {\n throw new ValidationError(`Value is not a number`)\n }\n\n if (billionths.includes('-')) {\n throw new ValidationError('Cannot have negative Quality')\n }\n\n if (billionths === ONE_BILLION) {\n return 0\n }\n\n if (billionths.includes('.')) {\n throw new ValidationError(`Decimal exceeds maximum precision.`)\n }\n\n return Number(billionths)\n}\n\n/**\n * Converts a quality in \"billionths\" format to a decimal.\n *\n * @param quality - Quality to convert to decimal.\n * @returns decimal representation of quality.\n * @throws ValidationError when quality is not convertible to decimal format.\n * @category Utilities\n */\nexport function qualityToDecimal(quality: number): string {\n if (!Number.isInteger(quality)) {\n throw new ValidationError('Quality must be an integer')\n }\n\n if (quality < 0) {\n throw new ValidationError('Negative quality not allowed')\n }\n\n if (quality === 0) {\n return '1'\n }\n\n const decimal = new BigNumber(quality).dividedBy(ONE_BILLION)\n\n return decimal.toString(BASE_TEN)\n}\n\n/**\n * Converts a transfer rate in \"billionths\" format to a decimal.\n *\n * @param rate - TransferRate to convert to decimal.\n * @returns decimal representation of transfer Rate.\n * @throws ValidationError when it cannot convert from billionths format.\n * @category Utilities\n */\nexport function transferRateToDecimal(rate: number): string {\n if (!Number.isInteger(rate)) {\n throw new ValidationError(\n 'Error decoding, transfer Rate must be an integer',\n )\n }\n\n if (rate === 0) {\n return '0'\n }\n\n const decimal = new BigNumber(rate).minus(ONE_BILLION).dividedBy(ONE_BILLION)\n\n if (decimal.isLessThan(0)) {\n throw new ValidationError('Error decoding, negative transfer rate')\n }\n\n return decimal.toString(BASE_TEN)\n}\n\n/**\n * Converts a string percent to the \"billionths\" format for use with QualityIn/\n * QualityOut\n *\n * @param percent - A string percent (i.e. \".034%\").\n * @returns A number in the \"billionths\" format.\n * @throws ValidationError when the percent parameter is not convertible to\n * \"billionths\" format.\n * @category Utilities\n */\nexport function percentToQuality(percent: string): number {\n return decimalToQuality(percentToDecimal(percent))\n}\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","import { Amount } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateRequiredField,\n isString,\n isAmount,\n} from './common'\n\n/**\n * The VaultDeposit transaction adds liqudity in exchange for vault shares.\n *\n * @category Transaction Models\n */\nexport interface VaultDeposit extends BaseTransaction {\n TransactionType: 'VaultDeposit'\n\n /**\n * The ID of the vault to which the assets are deposited.\n */\n VaultID: string\n\n /**\n * Asset amount to deposit.\n */\n Amount: Amount\n}\n\n/**\n * Verify the form and type of a {@link VaultDeposit} at runtime.\n *\n * @param tx - A {@link VaultDeposit} Transaction.\n * @throws When the {@link VaultDeposit} is malformed.\n */\nexport function validateVaultDeposit(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'VaultID', isString)\n validateRequiredField(tx, 'Amount', isAmount)\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isAmount,\n isNumber,\n isString,\n isXChainBridge,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainCommit is the second step in a cross-chain transfer. It puts assets\n * into trust on the locking chain so that they can be wrapped on the issuing\n * chain, or burns wrapped assets on the issuing chain so that they can be returned\n * on the locking chain.\n *\n * @category Transaction Models\n */\nexport interface XChainCommit extends BaseTransaction {\n TransactionType: 'XChainCommit'\n\n /**\n * The bridge to use to transfer funds.\n */\n XChainBridge: XChainBridge\n\n /**\n * The unique integer ID for a cross-chain transfer. This must be acquired on\n * the destination chain (via a {@link XChainCreateClaimID} transaction) and\n * checked from a validated ledger before submitting this transaction. If an\n * incorrect sequence number is specified, the funds will be lost.\n */\n XChainClaimID: number | string\n\n /**\n * The destination account on the destination chain. If this is not specified,\n * the account that submitted the {@link XChainCreateClaimID} transaction on the\n * destination chain will need to submit a {@link XChainClaim} transaction to\n * claim the funds.\n */\n OtherChainDestination?: Account\n\n /**\n * The asset to commit, and the quantity. This must match the door account's\n * LockingChainIssue (if on the locking chain) or the door account's\n * IssuingChainIssue (if on the issuing chain).\n */\n Amount: Amount\n}\n\n/**\n * Verify the form and type of an XChainCommit at runtime.\n *\n * @param tx - An XChainCommit Transaction.\n * @throws When the XChainCommit is malformed.\n */\nexport function validateXChainCommit(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(\n tx,\n 'XChainClaimID',\n (inp: unknown): inp is number | string => isNumber(inp) || isString(inp),\n )\n\n validateOptionalField(tx, 'OtherChainDestination', isAccount)\n\n validateRequiredField(tx, 'Amount', isAmount)\n}\n","import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, validateBaseTransaction } from './common'\n\n/**\n * An OfferCancel transaction removes an Offer object from the XRP Ledger.\n *\n * @category Transaction Models\n */\nexport interface OfferCancel extends BaseTransaction {\n TransactionType: 'OfferCancel'\n /**\n * The sequence number (or Ticket number) of a previous OfferCreate\n * transaction. If specified, cancel any offer object in the ledger that was\n * created by that transaction. It is not considered an error if the offer.\n * specified does not exist.\n */\n OfferSequence: number\n}\n\n/**\n * Verify the form and type of an OfferCancel at runtime.\n *\n * @param tx - An OfferCancel Transaction.\n * @throws When the OfferCancel is Malformed.\n */\nexport function validateOfferCancel(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.OfferSequence === undefined) {\n throw new ValidationError('OfferCancel: missing field OfferSequence')\n }\n\n if (typeof tx.OfferSequence !== 'number') {\n throw new ValidationError('OfferCancel: OfferSequence must be a number')\n }\n}\n","/**\n * XRP Ledger namespace prefixes.\n *\n * The XRP Ledger is a key-value store. In order to avoid name collisions,\n * names are partitioned into namespaces.\n *\n * Each namespace is just a single character prefix.\n *\n * See [LedgerNameSpace enum](https://github.com/ripple/rippled/blob/master/src/ripple/protocol/LedgerFormats.h#L100).\n */\nconst ledgerSpaces = {\n account: 'a',\n dirNode: 'd',\n generatorMap: 'g',\n rippleState: 'r',\n // Entry for an offer.\n offer: 'o',\n // Directory of things owned by an account.\n ownerDir: 'O',\n // Directory of order books.\n bookDir: 'B',\n contract: 'c',\n skipList: 's',\n escrow: 'u',\n amendment: 'f',\n feeSettings: 'e',\n ticket: 'T',\n signerList: 'S',\n paychan: 'x',\n check: 'C',\n depositPreauth: 'p',\n}\n\nexport default ledgerSpaces\n","import { SerializedType } from './serialized-type'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { Hash256 } from './hash-256'\nimport { BytesList } from '../serdes/binary-serializer'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\n/**\n * TypeGuard for Array<string>\n */\nfunction isStrings(arg): arg is Array<string> {\n return Array.isArray(arg) && (arg.length === 0 || typeof arg[0] === 'string')\n}\n\n/**\n * Class for serializing and deserializing vectors of Hash256\n */\nclass Vector256 extends SerializedType {\n constructor(bytes: Uint8Array) {\n super(bytes)\n }\n\n /**\n * Construct a Vector256 from a BinaryParser\n *\n * @param parser BinaryParser to\n * @param hint length of the vector, in bytes, optional\n * @returns a Vector256 object\n */\n static fromParser(parser: BinaryParser, hint?: number): Vector256 {\n const bytesList = new BytesList()\n const bytes = hint ?? parser.size()\n const hashes = bytes / 32\n for (let i = 0; i < hashes; i++) {\n Hash256.fromParser(parser).toBytesSink(bytesList)\n }\n return new Vector256(bytesList.toBytes())\n }\n\n /**\n * Construct a Vector256 object from an array of hashes\n *\n * @param value A Vector256 object or array of hex-strings representing Hash256's\n * @returns a Vector256 object\n */\n static from<T extends Vector256 | Array<string>>(value: T): Vector256 {\n if (value instanceof Vector256) {\n return value\n }\n\n if (isStrings(value)) {\n const bytesList = new BytesList()\n value.forEach((hash) => {\n Hash256.from(hash).toBytesSink(bytesList)\n })\n return new Vector256(bytesList.toBytes())\n }\n\n throw new Error('Cannot construct Vector256 from given value')\n }\n\n /**\n * Return an Array of hex-strings represented by this.bytes\n *\n * @returns An Array of strings representing the Hash256 objects\n */\n toJSON(): Array<string> {\n if (this.bytes.byteLength % 32 !== 0) {\n throw new Error('Invalid bytes for Vector256')\n }\n\n const result: Array<string> = []\n for (let i = 0; i < this.bytes.byteLength; i += 32) {\n result.push(bytesToHex(this.bytes.slice(i, i + 32)))\n }\n return result\n }\n}\n\nexport { Vector256 }\n","import { Bytes } from './bytes'\nimport { SerializedType } from '../types/serialized-type'\nimport { TYPE_WIDTH } from './constants'\n\n/**\n * Encoding information for a rippled field, often used in transactions.\n * See the enums [README.md](https://github.com/XRPLF/xrpl.js/tree/main/packages/ripple-binary-codec/src/enums) for more details on what each means.\n */\nexport interface FieldInfo {\n nth: number\n isVLEncoded: boolean\n isSerialized: boolean\n isSigningField: boolean\n type: string\n}\n\nexport interface FieldInstance {\n readonly nth: number\n readonly isVariableLengthEncoded: boolean\n readonly isSerialized: boolean\n readonly isSigningField: boolean\n readonly type: Bytes\n readonly ordinal: number\n readonly name: string\n readonly header: Uint8Array\n readonly associatedType: typeof SerializedType\n}\n\n/*\n * @brief: Serialize a field based on type_code and Field.nth\n */\nfunction fieldHeader(type: number, nth: number): Uint8Array {\n const header: Array<number> = []\n if (type < 16) {\n if (nth < 16) {\n header.push((type << 4) | nth)\n } else {\n header.push(type << 4, nth)\n }\n } else if (nth < 16) {\n header.push(nth, type)\n } else {\n header.push(0, type, nth)\n }\n return Uint8Array.from(header)\n}\n\nfunction buildField(\n [name, info]: [string, FieldInfo],\n typeOrdinal: number,\n): FieldInstance {\n const field = fieldHeader(typeOrdinal, info.nth)\n return {\n name: name,\n nth: info.nth,\n isVariableLengthEncoded: info.isVLEncoded,\n isSerialized: info.isSerialized,\n isSigningField: info.isSigningField,\n ordinal: (typeOrdinal << 16) | info.nth,\n type: new Bytes(info.type, typeOrdinal, TYPE_WIDTH),\n header: field,\n associatedType: SerializedType, // For later assignment in ./types/index.js or Definitions.updateAll(...)\n }\n}\n\n/*\n * @brief: The collection of all fields as defined in definitions.json\n */\nexport class FieldLookup {\n constructor(\n fields: Array<[string, FieldInfo]>,\n types: Record<string, number>,\n ) {\n fields.forEach(([name, field_info]) => {\n const typeOrdinal = types[field_info.type]\n this[name] = buildField([name, field_info], typeOrdinal)\n this[this[name].ordinal.toString()] = this[name]\n })\n }\n\n fromString(value: string): FieldInstance {\n return this[value] as FieldInstance\n }\n}\n","import { ValidationError } from '../../errors'\nimport { Currency, IssuedCurrency, IssuedCurrencyAmount } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n GlobalFlagsInterface,\n isAccount,\n isIssuedCurrency,\n isIssuedCurrencyAmount,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * Enum representing values for AMMClawback Transaction Flags.\n *\n * @category Transaction Flags\n */\nexport enum AMMClawbackFlags {\n tfClawTwoAssets = 0x00000001,\n}\n\n/**\n * Map of flags to boolean values representing {@link AMMClawback} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface AMMClawbackFlagsInterface extends GlobalFlagsInterface {\n tfClawTwoAssets?: boolean\n}\n\n/**\n * Claw back tokens from a holder that has deposited your issued tokens into an AMM pool.\n *\n * Clawback is disabled by default. To use clawback, you must send an AccountSet transaction to enable the\n * Allow Trust Line Clawback setting. An issuer with any existing tokens cannot enable clawback. You can\n * only enable Allow Trust Line Clawback if you have a completely empty owner directory, meaning you must\n * do so before you set up any trust lines, offers, escrows, payment channels, checks, or signer lists.\n * After you enable clawback, it cannot reverted: the account permanently gains the ability to claw back\n * issued assets on trust lines.\n */\nexport interface AMMClawback extends BaseTransaction {\n TransactionType: 'AMMClawback'\n\n /**\n * The account holding the asset to be clawed back.\n */\n Holder: Account\n\n /**\n * Specifies the asset that the issuer wants to claw back from the AMM pool.\n * In JSON, this is an object with currency and issuer fields. The issuer field must match with Account.\n */\n Asset: IssuedCurrency\n\n /**\n * Specifies the other asset in the AMM's pool. In JSON, this is an object with currency and\n * issuer fields (omit issuer for XRP).\n */\n Asset2: Currency\n\n /**\n * The maximum amount to claw back from the AMM account. The currency and issuer subfields should match\n * the Asset subfields. If this field isn't specified, or the value subfield exceeds the holder's available\n * tokens in the AMM, all of the holder's tokens will be clawed back.\n */\n Amount?: IssuedCurrencyAmount\n}\n\n/**\n * Verify the form and type of an AMMClawback at runtime.\n *\n * @param tx - An AMMClawback Transaction.\n * @throws {ValidationError} When the transaction is malformed.\n */\nexport function validateAMMClawback(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Holder', isAccount)\n\n validateRequiredField(tx, 'Asset', isIssuedCurrency)\n\n const asset = tx.Asset\n\n if (tx.Holder === asset.issuer) {\n throw new ValidationError(\n 'AMMClawback: Holder and Asset.issuer must be distinct',\n )\n }\n\n if (tx.Account !== asset.issuer) {\n throw new ValidationError(\n 'AMMClawback: Account must be the same as Asset.issuer',\n )\n }\n\n validateRequiredField(tx, 'Asset2', isIssuedCurrency)\n\n validateOptionalField(tx, 'Amount', isIssuedCurrencyAmount)\n\n if (tx.Amount != null) {\n if (tx.Amount.currency !== asset.currency) {\n throw new ValidationError(\n 'AMMClawback: Amount.currency must match Asset.currency',\n )\n }\n\n if (tx.Amount.issuer !== asset.issuer) {\n throw new ValidationError(\n 'AMMClawback: Amount.issuer must match Amount.issuer',\n )\n }\n }\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n Account,\n BaseTransaction,\n GlobalFlagsInterface,\n isAccount,\n validateBaseTransaction,\n validateOptionalField,\n} from './common'\n\n/**\n * Enum for AccountSet Flags.\n *\n * @category Transaction Flags\n */\nexport enum AccountSetAsfFlags {\n /** Require a destination tag to send transactions to this account. */\n asfRequireDest = 1,\n /**\n * Require authorization for users to hold balances issued by this address\n * can only be enabled if the address has no trust lines connected to it.\n */\n asfRequireAuth = 2,\n /** XRP should not be sent to this account. */\n asfDisallowXRP = 3,\n /**\n * Disallow use of the master key pair. Can only be enabled if the account\n * has configured another way to sign transactions, such as a Regular Key or a\n * Signer List.\n */\n asfDisableMaster = 4,\n /**\n * Track the ID of this account's most recent transaction. Required for\n * AccountTxnID.\n */\n asfAccountTxnID = 5,\n /**\n * Permanently give up the ability to freeze individual trust lines or\n * disable Global Freeze. This flag can never be disabled after being enabled.\n */\n asfNoFreeze = 6,\n /** Freeze all assets issued by this account. */\n asfGlobalFreeze = 7,\n /** Enable rippling on this account's trust lines by default. */\n asfDefaultRipple = 8,\n /** Enable Deposit Authorization on this account. */\n asfDepositAuth = 9,\n /**\n * Allow another account to mint and burn tokens on behalf of this account.\n */\n asfAuthorizedNFTokenMinter = 10,\n /** asf 11 is reserved for Hooks amendment */\n /** Disallow other accounts from creating incoming NFTOffers */\n asfDisallowIncomingNFTokenOffer = 12,\n /** Disallow other accounts from creating incoming Checks */\n asfDisallowIncomingCheck = 13,\n /** Disallow other accounts from creating incoming PayChannels */\n asfDisallowIncomingPayChan = 14,\n /** Disallow other accounts from creating incoming Trustlines */\n asfDisallowIncomingTrustline = 15,\n /** Permanently gain the ability to claw back issued IOUs */\n asfAllowTrustLineClawback = 16,\n}\n\n/**\n * Enum for AccountSet Transaction Flags.\n *\n * @category Transaction Flags\n */\nexport enum AccountSetTfFlags {\n /** The same as SetFlag: asfRequireDest. */\n tfRequireDestTag = 0x00010000,\n /** The same as ClearFlag: asfRequireDest. */\n tfOptionalDestTag = 0x00020000,\n /** The same as SetFlag: asfRequireAuth. */\n tfRequireAuth = 0x00040000,\n /** The same as ClearFlag: asfRequireAuth. */\n tfOptionalAuth = 0x00080000,\n /** The same as SetFlag: asfDisallowXRP. */\n tfDisallowXRP = 0x00100000,\n /** The same as ClearFlag: asfDisallowXRP. */\n tfAllowXRP = 0x00200000,\n}\n\n/**\n * Map of flags to boolean values representing {@link AccountSet} transaction\n * flags.\n *\n * @category Transaction Flags\n *\n * @example\n * ```typescript\n * const accountSetTx: AccountSet = {\n * TransactionType: 'AccountSet',\n * Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn',\n * Flags: {\n * tfOptionalDestTag: true,\n * tfRequireAuth: true\n * },\n * }\n *\n * // Autofill the tx to see how flags actually look compared to the interface usage.\n * const autofilledTx = await client.autofill(accountSetTx)\n * console.log(autofilledTx)\n * // {\n * // TransactionType: 'AccountSet',\n * // Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn',\n * // Flags: 393216,\n * // Sequence: 1,\n * // Fee: '12',\n * // LastLedgerSequence: 21971793\n * // }\n * ```\n */\nexport interface AccountSetFlagsInterface extends GlobalFlagsInterface {\n tfRequireDestTag?: boolean\n tfOptionalDestTag?: boolean\n tfRequireAuth?: boolean\n tfOptionalAuth?: boolean\n tfDisallowXRP?: boolean\n tfAllowXRP?: boolean\n}\n\n/**\n * An AccountSet transaction modifies the properties of an account in the XRP\n * Ledger.\n *\n * @category Transaction Models\n */\nexport interface AccountSet extends BaseTransaction {\n TransactionType: 'AccountSet'\n Flags?: number | AccountSetFlagsInterface\n /** Unique identifier of a flag to disable for this account. */\n ClearFlag?: number\n /**\n * The domain that owns this account, as a string of hex representing the.\n * ASCII for the domain in lowercase.\n */\n Domain?: string\n /** Hash of an email address to be used for generating an avatar image. */\n EmailHash?: string\n /** Public key for sending encrypted messages to this account. */\n MessageKey?: string\n /** Integer flag to enable for this account. */\n SetFlag?: AccountSetAsfFlags\n /**\n * The fee to charge when users transfer this account's issued currencies,\n * represented as billionths of a unit. Cannot be more than 2000000000 or less\n * than 1000000000, except for the special case 0 meaning no fee.\n */\n TransferRate?: number\n /**\n * Tick size to use for offers involving a currency issued by this address.\n * The exchange rates of those offers is rounded to this many significant\n * digits. Valid values are 3 to 15 inclusive, or 0 to disable.\n */\n TickSize?: number\n /**\n * Sets an alternate account that is allowed to mint NFTokens on this\n * account's behalf using NFTokenMint's `Issuer` field.\n */\n NFTokenMinter?: Account\n}\n\nconst MIN_TICK_SIZE = 3\nconst MAX_TICK_SIZE = 15\n\n/**\n * Verify the form and type of an AccountSet at runtime.\n *\n * @param tx - An AccountSet Transaction.\n * @throws When the AccountSet is Malformed.\n */\n// eslint-disable-next-line max-lines-per-function -- okay for this method, only a little over\nexport function validateAccountSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateOptionalField(tx, 'NFTokenMinter', isAccount)\n\n if (tx.ClearFlag !== undefined) {\n if (typeof tx.ClearFlag !== 'number') {\n throw new ValidationError('AccountSet: invalid ClearFlag')\n }\n if (!Object.values(AccountSetAsfFlags).includes(tx.ClearFlag)) {\n throw new ValidationError('AccountSet: invalid ClearFlag')\n }\n }\n\n if (tx.Domain !== undefined && typeof tx.Domain !== 'string') {\n throw new ValidationError('AccountSet: invalid Domain')\n }\n\n if (tx.EmailHash !== undefined && typeof tx.EmailHash !== 'string') {\n throw new ValidationError('AccountSet: invalid EmailHash')\n }\n\n if (tx.MessageKey !== undefined && typeof tx.MessageKey !== 'string') {\n throw new ValidationError('AccountSet: invalid MessageKey')\n }\n\n if (tx.SetFlag !== undefined) {\n if (typeof tx.SetFlag !== 'number') {\n throw new ValidationError('AccountSet: invalid SetFlag')\n }\n if (!Object.values(AccountSetAsfFlags).includes(tx.SetFlag)) {\n throw new ValidationError('AccountSet: invalid SetFlag')\n }\n }\n\n if (tx.TransferRate !== undefined && typeof tx.TransferRate !== 'number') {\n throw new ValidationError('AccountSet: invalid TransferRate')\n }\n\n if (tx.TickSize !== undefined) {\n if (typeof tx.TickSize !== 'number') {\n throw new ValidationError('AccountSet: invalid TickSize')\n }\n if (\n tx.TickSize !== 0 &&\n (tx.TickSize < MIN_TICK_SIZE || tx.TickSize > MAX_TICK_SIZE)\n ) {\n throw new ValidationError('AccountSet: invalid TickSize')\n }\n }\n}\n","export * from './schema/Account'\nexport * from './utils'\n","import { Comparable } from './serialized-type'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { HEX_REGEX, hexToBytes } from '@xrplf/isomorphic/utils'\nimport { compare } from '../utils'\n\n/**\n * Base class defining how to encode and decode hashes\n */\nclass Hash extends Comparable<Hash | string> {\n static readonly width: number\n\n constructor(bytes: Uint8Array) {\n super(bytes)\n if (this.bytes.length !== (this.constructor as typeof Hash).width) {\n throw new Error(`Invalid Hash length ${this.bytes.byteLength}`)\n }\n }\n\n /**\n * Construct a Hash object from an existing Hash object or a hex-string\n *\n * @param value A hash object or hex-string of a hash\n */\n static from<T extends Hash | string>(value: T): Hash {\n if (value instanceof this) {\n return value\n }\n\n if (typeof value === 'string') {\n if (!HEX_REGEX.test(value)) {\n throw new Error(`Invalid hash string ${value}`)\n }\n return new this(hexToBytes(value))\n }\n\n throw new Error('Cannot construct Hash from given value')\n }\n\n /**\n * Read a Hash object from a BinaryParser\n *\n * @param parser BinaryParser to read the hash from\n * @param hint length of the bytes to read, optional\n */\n static fromParser(parser: BinaryParser, hint?: number): Hash {\n return new this(parser.read(hint ?? this.width))\n }\n\n /**\n * Overloaded operator for comparing two hash objects\n *\n * @param other The Hash to compare this to\n */\n compareTo(other: Hash): number {\n return compare(\n this.bytes,\n (this.constructor as typeof Hash).from(other).bytes,\n )\n }\n\n /**\n * @returns the hex-string representation of this Hash\n */\n toString(): string {\n return this.toHex()\n }\n\n /**\n * Returns four bits at the specified depth within a hash\n *\n * @param depth The depth of the four bits\n * @returns The number represented by the four bits\n */\n nibblet(depth: number): number {\n const byteIx = depth > 0 ? (depth / 2) | 0 : 0\n let b = this.bytes[byteIx]\n if (depth % 2 === 0) {\n b = (b & 0xf0) >>> 4\n } else {\n b = b & 0x0f\n }\n return b\n }\n}\n\nexport { Hash }\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash } from './_assert.js';\nimport { Hash, toBytes, type CHash, type Input } from './utils.js';\n\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n","import { encode, encodeForSigning } from 'ripple-binary-codec'\nimport { verify } from 'ripple-keypairs'\n\nimport { ValidationError } from '../errors'\nimport { Signer } from '../models/common'\nimport { Transaction, validate } from '../models/transactions'\n\nimport { compareSigners, getDecodedTransaction } from './utils'\n\n/**\n * Takes several transactions with Signer fields (in object or blob form) and creates a\n * single transaction with all Signers that then gets signed and returned.\n *\n * @param transactions - An array of signed Transactions (in object or blob form) to combine into a single signed Transaction.\n * @returns A single signed Transaction which has all Signers from transactions within it.\n * @throws ValidationError if:\n * - There were no transactions given to sign\n * - The SigningPubKey field is not the empty string in any given transaction\n * - Any transaction is missing a Signers field.\n * @category Signing\n */\nfunction multisign(transactions: Array<Transaction | string>): string {\n if (transactions.length === 0) {\n throw new ValidationError('There were 0 transactions to multisign')\n }\n\n const decodedTransactions: Transaction[] = transactions.map(\n (txOrBlob: string | Transaction) => {\n return getDecodedTransaction(txOrBlob)\n },\n )\n\n decodedTransactions.forEach((tx) => {\n /*\n * This will throw a more clear error for JS users if any of the supplied transactions has incorrect formatting\n */\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- validate does not accept Transaction type\n validate(tx as unknown as Record<string, unknown>)\n if (tx.Signers == null || tx.Signers.length === 0) {\n throw new ValidationError(\n \"For multisigning all transactions must include a Signers field containing an array of signatures. You may have forgotten to pass the 'forMultisign' parameter when signing.\",\n )\n }\n\n if (tx.SigningPubKey !== '') {\n throw new ValidationError(\n 'SigningPubKey must be an empty string for all transactions when multisigning.',\n )\n }\n })\n\n validateTransactionEquivalence(decodedTransactions)\n\n return encode(getTransactionWithAllSigners(decodedTransactions))\n}\n\n/**\n * Verifies that the given transaction has a valid signature based on public-key encryption.\n *\n * @param tx - A transaction to verify the signature of. (Can be in object or encoded string format).\n * @param [publicKey] Specific public key to use to verify. If not specified the `SigningPublicKey` of tx will be used.\n * @returns Returns true if tx has a valid signature, and returns false otherwise.\n * @throws Error when transaction is missing TxnSignature\n * @throws Error when publicKey is not provided and transaction is missing SigningPubKey\n * @category Utilities\n */\nfunction verifySignature(\n tx: Transaction | string,\n publicKey?: string,\n): boolean {\n const decodedTx: Transaction = getDecodedTransaction(tx)\n let key = publicKey\n\n // Need a SignedTransaction class where TxnSignature is not optional.\n if (typeof decodedTx.TxnSignature !== 'string' || !decodedTx.TxnSignature) {\n throw new Error('Transaction is missing a signature, TxnSignature')\n }\n\n if (!key) {\n // Need a SignedTransaction class where TxnSignature is not optional.\n if (\n typeof decodedTx.SigningPubKey !== 'string' ||\n !decodedTx.SigningPubKey\n ) {\n throw new Error('Transaction is missing a public key, SigningPubKey')\n }\n key = decodedTx.SigningPubKey\n }\n\n return verify(encodeForSigning(decodedTx), decodedTx.TxnSignature, key)\n}\n\n/**\n * The transactions should all be equal except for the 'Signers' field.\n *\n * @param transactions - An array of Transactions which are expected to be equal other than 'Signers'.\n * @throws ValidationError if the transactions are not equal in any field other than 'Signers'.\n */\nfunction validateTransactionEquivalence(transactions: Transaction[]): void {\n const exampleTransaction = JSON.stringify({\n ...transactions[0],\n Signers: null,\n })\n if (\n transactions\n .slice(1)\n .some(\n (tx) => JSON.stringify({ ...tx, Signers: null }) !== exampleTransaction,\n )\n ) {\n throw new ValidationError(\n 'txJSON is not the same for all signedTransactions',\n )\n }\n}\n\nfunction getTransactionWithAllSigners(\n transactions: Transaction[],\n): Transaction {\n // Signers must be sorted in the combined transaction - See compareSigners' documentation for more details\n const sortedSigners: Signer[] = transactions\n .flatMap((tx) => tx.Signers ?? [])\n .sort((signer1, signer2) => compareSigners(signer1.Signer, signer2.Signer))\n\n return { ...transactions[0], Signers: sortedSigners }\n}\n\nexport { verifySignature, multisign }\n","import { AccountID } from './account-id'\nimport { Currency } from './currency'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { SerializedType, JsonObject } from './serialized-type'\nimport { bytesToHex, concat } from '@xrplf/isomorphic/utils'\n\n/**\n * Constants for separating Paths in a PathSet\n */\nconst PATHSET_END_BYTE = 0x00\nconst PATH_SEPARATOR_BYTE = 0xff\n\n/**\n * Constant for masking types of a Hop\n */\nconst TYPE_ACCOUNT = 0x01\nconst TYPE_CURRENCY = 0x10\nconst TYPE_ISSUER = 0x20\n\n/**\n * The object representation of a Hop, an issuer AccountID, an account AccountID, and a Currency\n */\ninterface HopObject extends JsonObject {\n issuer?: string\n account?: string\n currency?: string\n}\n\n/**\n * TypeGuard for HopObject\n */\nfunction isHopObject(arg): arg is HopObject {\n return (\n arg.issuer !== undefined ||\n arg.account !== undefined ||\n arg.currency !== undefined\n )\n}\n\n/**\n * TypeGuard for PathSet\n */\nfunction isPathSet(arg): arg is Array<Array<HopObject>> {\n return (\n (Array.isArray(arg) && arg.length === 0) ||\n (Array.isArray(arg) && Array.isArray(arg[0]) && arg[0].length === 0) ||\n (Array.isArray(arg) && Array.isArray(arg[0]) && isHopObject(arg[0][0]))\n )\n}\n\n/**\n * Serialize and Deserialize a Hop\n */\nclass Hop extends SerializedType {\n /**\n * Create a Hop from a HopObject\n *\n * @param value Either a hop or HopObject to create a hop with\n * @returns a Hop\n */\n static from(value: Hop | HopObject): Hop {\n if (value instanceof Hop) {\n return value\n }\n\n const bytes: Array<Uint8Array> = [Uint8Array.from([0])]\n\n if (value.account) {\n bytes.push(AccountID.from(value.account).toBytes())\n bytes[0][0] |= TYPE_ACCOUNT\n }\n\n if (value.currency) {\n bytes.push(Currency.from(value.currency).toBytes())\n bytes[0][0] |= TYPE_CURRENCY\n }\n\n if (value.issuer) {\n bytes.push(AccountID.from(value.issuer).toBytes())\n bytes[0][0] |= TYPE_ISSUER\n }\n\n return new Hop(concat(bytes))\n }\n\n /**\n * Construct a Hop from a BinaryParser\n *\n * @param parser BinaryParser to read the Hop from\n * @returns a Hop\n */\n static fromParser(parser: BinaryParser): Hop {\n const type = parser.readUInt8()\n const bytes: Array<Uint8Array> = [Uint8Array.from([type])]\n\n if (type & TYPE_ACCOUNT) {\n bytes.push(parser.read(AccountID.width))\n }\n\n if (type & TYPE_CURRENCY) {\n bytes.push(parser.read(Currency.width))\n }\n\n if (type & TYPE_ISSUER) {\n bytes.push(parser.read(AccountID.width))\n }\n\n return new Hop(concat(bytes))\n }\n\n /**\n * Get the JSON interpretation of this hop\n *\n * @returns a HopObject, an JS object with optional account, issuer, and currency\n */\n toJSON(): HopObject {\n const hopParser = new BinaryParser(bytesToHex(this.bytes))\n const type = hopParser.readUInt8()\n\n let account, currency, issuer\n if (type & TYPE_ACCOUNT) {\n account = (AccountID.fromParser(hopParser) as AccountID).toJSON()\n }\n\n if (type & TYPE_CURRENCY) {\n currency = (Currency.fromParser(hopParser) as Currency).toJSON()\n }\n\n if (type & TYPE_ISSUER) {\n issuer = (AccountID.fromParser(hopParser) as AccountID).toJSON()\n }\n\n const result: HopObject = {}\n if (account) {\n result.account = account\n }\n\n if (issuer) {\n result.issuer = issuer\n }\n\n if (currency) {\n result.currency = currency\n }\n\n return result\n }\n\n /**\n * get a number representing the type of this hop\n *\n * @returns a number to be bitwise and-ed with TYPE_ constants to describe the types in the hop\n */\n type(): number {\n return this.bytes[0]\n }\n}\n\n/**\n * Class for serializing/deserializing Paths\n */\nclass Path extends SerializedType {\n /**\n * construct a Path from an array of Hops\n *\n * @param value Path or array of HopObjects to construct a Path\n * @returns the Path\n */\n static from(value: Path | Array<HopObject>): Path {\n if (value instanceof Path) {\n return value\n }\n\n const bytes: Array<Uint8Array> = []\n value.forEach((hop: HopObject) => {\n bytes.push(Hop.from(hop).toBytes())\n })\n\n return new Path(concat(bytes))\n }\n\n /**\n * Read a Path from a BinaryParser\n *\n * @param parser BinaryParser to read Path from\n * @returns the Path represented by the bytes read from the BinaryParser\n */\n static fromParser(parser: BinaryParser): Path {\n const bytes: Array<Uint8Array> = []\n while (!parser.end()) {\n bytes.push(Hop.fromParser(parser).toBytes())\n\n if (\n parser.peek() === PATHSET_END_BYTE ||\n parser.peek() === PATH_SEPARATOR_BYTE\n ) {\n break\n }\n }\n return new Path(concat(bytes))\n }\n\n /**\n * Get the JSON representation of this Path\n *\n * @returns an Array of HopObject constructed from this.bytes\n */\n toJSON(): Array<HopObject> {\n const json: Array<HopObject> = []\n const pathParser = new BinaryParser(this.toString())\n\n while (!pathParser.end()) {\n json.push(Hop.fromParser(pathParser).toJSON())\n }\n\n return json\n }\n}\n\n/**\n * Deserialize and Serialize the PathSet type\n */\nclass PathSet extends SerializedType {\n /**\n * Construct a PathSet from an Array of Arrays representing paths\n *\n * @param value A PathSet or Array of Array of HopObjects\n * @returns the PathSet constructed from value\n */\n static from<T extends PathSet | Array<Array<HopObject>>>(value: T): PathSet {\n if (value instanceof PathSet) {\n return value\n }\n\n if (isPathSet(value)) {\n const bytes: Array<Uint8Array> = []\n\n value.forEach((path: Array<HopObject>) => {\n bytes.push(Path.from(path).toBytes())\n bytes.push(Uint8Array.from([PATH_SEPARATOR_BYTE]))\n })\n\n bytes[bytes.length - 1] = Uint8Array.from([PATHSET_END_BYTE])\n\n return new PathSet(concat(bytes))\n }\n\n throw new Error('Cannot construct PathSet from given value')\n }\n\n /**\n * Construct a PathSet from a BinaryParser\n *\n * @param parser A BinaryParser to read PathSet from\n * @returns the PathSet read from parser\n */\n static fromParser(parser: BinaryParser): PathSet {\n const bytes: Array<Uint8Array> = []\n\n while (!parser.end()) {\n bytes.push(Path.fromParser(parser).toBytes())\n bytes.push(parser.read(1))\n\n if (bytes[bytes.length - 1][0] == PATHSET_END_BYTE) {\n break\n }\n }\n\n return new PathSet(concat(bytes))\n }\n\n /**\n * Get the JSON representation of this PathSet\n *\n * @returns an Array of Array of HopObjects, representing this PathSet\n */\n toJSON(): Array<Array<HopObject>> {\n const json: Array<Array<HopObject>> = []\n const pathParser = new BinaryParser(this.toString())\n\n while (!pathParser.end()) {\n json.push(Path.fromParser(pathParser).toJSON())\n pathParser.skip(1)\n }\n\n return json\n }\n}\n\nexport { PathSet }\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.js';\nimport { type CHash, rotr, wrapConstructor } from './utils.js';\n\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n SHA256_W.fill(0);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n protected A = 0xc1059ed8 | 0;\n protected B = 0x367cd507 | 0;\n protected C = 0x3070dd17 | 0;\n protected D = 0xf70e5939 | 0;\n protected E = 0xffc00b31 | 0;\n protected F = 0x68581511 | 0;\n protected G = 0x64f98fa7 | 0;\n protected H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/** SHA2-256 hash function */\nexport const sha256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.js';\nimport { bitLen, validateObject } from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\nfunction calcWOpts(W: number, bits: number) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>(); // This allows use make points immutable (nothing changes inside)\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n) break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0) continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0) curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = BigInt((1 << windowSize) - 1);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n","/* eslint-disable max-lines -- Connection is a large file w/ lots of imports/exports */\nimport type { Agent } from 'http'\n\nimport { bytesToHex, hexToString } from '@xrplf/isomorphic/utils'\nimport WebSocket, { ClientOptions } from '@xrplf/isomorphic/ws'\nimport { EventEmitter } from 'eventemitter3'\n\nimport {\n DisconnectedError,\n NotConnectedError,\n ConnectionError,\n XrplError,\n} from '../errors'\nimport type { APIVersion, RequestResponseMap } from '../models'\nimport { BaseRequest } from '../models/methods/baseMethod'\n\nimport ConnectionManager from './ConnectionManager'\nimport ExponentialBackoff from './ExponentialBackoff'\nimport RequestManager from './RequestManager'\n\nconst SECONDS_PER_MINUTE = 60\nconst TIMEOUT = 20\nconst CONNECTION_TIMEOUT = 5\n\n/**\n * ConnectionOptions is the configuration for the Connection class.\n */\ninterface ConnectionOptions {\n trace?: boolean | ((id: string, message: string) => void)\n headers?: { [key: string]: string }\n agent?: Agent\n authorization?: string\n connectionTimeout: number\n timeout: number\n}\n\n/**\n * ConnectionUserOptions is the user-provided configuration object. All configuration\n * is optional, so any ConnectionOptions configuration that has a default value is\n * still optional at the point that the user provides it.\n */\nexport type ConnectionUserOptions = Partial<ConnectionOptions>\n\n/**\n * Represents an intentionally triggered web-socket disconnect code.\n * WebSocket spec allows 4xxx codes for app/library specific codes.\n * See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n */\nexport const INTENTIONAL_DISCONNECT_CODE = 4000\n\ntype WebsocketState = 0 | 1 | 2 | 3\n\n/**\n * Create a new websocket given your URL and optional proxy/certificate\n * configuration.\n *\n * @param url - The URL to connect to.\n * @param config - THe configuration options for the WebSocket.\n * @returns A Websocket that fits the given configuration parameters.\n */\nfunction createWebSocket(\n url: string,\n config: ConnectionOptions,\n): WebSocket | null {\n const options: ClientOptions = {\n agent: config.agent,\n }\n if (config.headers) {\n options.headers = config.headers\n }\n if (config.authorization != null) {\n options.headers = {\n ...options.headers,\n Authorization: `Basic ${btoa(config.authorization)}`,\n }\n }\n const websocketOptions = { ...options }\n return new WebSocket(url, websocketOptions)\n}\n\n/**\n * Ws.send(), but promisified.\n *\n * @param ws - Websocket to send with.\n * @param message - Message to send.\n * @returns When the message has been sent.\n */\nasync function websocketSendAsync(\n ws: WebSocket,\n message: string,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n ws.send(message, (error) => {\n if (error) {\n reject(new DisconnectedError(error.message, error))\n } else {\n resolve()\n }\n })\n })\n}\n\n/**\n * The main Connection class. Responsible for connecting to & managing\n * an active WebSocket connection to a XRPL node.\n */\nexport class Connection extends EventEmitter {\n private readonly url: string | undefined\n private ws: WebSocket | null = null\n // Typing necessary for Jest tests running in browser\n private reconnectTimeoutID: null | ReturnType<typeof setTimeout> = null\n // Typing necessary for Jest tests running in browser\n private heartbeatIntervalID: null | ReturnType<typeof setTimeout> = null\n private readonly retryConnectionBackoff = new ExponentialBackoff({\n min: 100,\n max: SECONDS_PER_MINUTE * 1000,\n })\n\n private readonly config: ConnectionOptions\n private readonly requestManager = new RequestManager()\n private readonly connectionManager = new ConnectionManager()\n\n /**\n * Creates a new Connection object.\n *\n * @param url - URL to connect to.\n * @param options - Options for the Connection object.\n */\n public constructor(url?: string, options: ConnectionUserOptions = {}) {\n super()\n this.url = url\n this.config = {\n timeout: TIMEOUT * 1000,\n connectionTimeout: CONNECTION_TIMEOUT * 1000,\n ...options,\n }\n if (typeof options.trace === 'function') {\n this.trace = options.trace\n } else if (options.trace) {\n // eslint-disable-next-line no-console -- Used for tracing only\n this.trace = console.log\n }\n }\n\n /**\n * Gets the state of the websocket.\n *\n * @returns The Websocket's ready state.\n */\n private get state(): WebsocketState {\n return this.ws ? this.ws.readyState : WebSocket.CLOSED\n }\n\n /**\n * Returns whether the server should be connected.\n *\n * @returns Whether the server should be connected.\n */\n private get shouldBeConnected(): boolean {\n return this.ws !== null\n }\n\n /**\n * Returns whether the websocket is connected.\n *\n * @returns Whether the websocket connection is open.\n */\n public isConnected(): boolean {\n return this.state === WebSocket.OPEN\n }\n\n /**\n * Connects the websocket to the provided URL.\n *\n * @returns When the websocket is connected.\n * @throws ConnectionError if there is a connection error, RippleError if there is already a WebSocket in existence.\n */\n // eslint-disable-next-line max-lines-per-function -- Necessary\n public async connect(): Promise<void> {\n if (this.isConnected()) {\n return Promise.resolve()\n }\n if (this.state === WebSocket.CONNECTING) {\n return this.connectionManager.awaitConnection()\n }\n if (!this.url) {\n return Promise.reject(\n new ConnectionError('Cannot connect because no server was specified'),\n )\n }\n if (this.ws != null) {\n return Promise.reject(\n new XrplError('Websocket connection never cleaned up.', {\n state: this.state,\n }),\n )\n }\n\n // Create the connection timeout, in case the connection hangs longer than expected.\n const connectionTimeoutID: ReturnType<typeof setTimeout> = setTimeout(\n () => {\n this.onConnectionFailed(\n new ConnectionError(\n `Error: connect() timed out after ${this.config.connectionTimeout} ms. If your internet connection is working, the ` +\n `rippled server may be blocked or inaccessible. You can also try setting the 'connectionTimeout' option in the Client constructor.`,\n ),\n )\n },\n this.config.connectionTimeout,\n )\n // Connection listeners: these stay attached only until a connection is done/open.\n this.ws = createWebSocket(this.url, this.config)\n\n if (this.ws == null) {\n throw new XrplError('Connect: created null websocket')\n }\n\n this.ws.on('error', (error) => this.onConnectionFailed(error))\n this.ws.on('error', () => clearTimeout(connectionTimeoutID))\n this.ws.on('close', (reason) => this.onConnectionFailed(reason))\n this.ws.on('close', () => clearTimeout(connectionTimeoutID))\n this.ws.once('open', () => {\n void this.onceOpen(connectionTimeoutID)\n })\n return this.connectionManager.awaitConnection()\n }\n\n /**\n * Disconnect the websocket connection.\n * We never expect this method to reject. Even on \"bad\" disconnects, the websocket\n * should still successfully close with the relevant error code returned.\n * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent for the full list.\n * If no open websocket connection exists, resolve with no code (`undefined`).\n *\n * @returns A promise containing either `undefined` or a disconnected code, that resolves when the connection is destroyed.\n */\n public async disconnect(): Promise<number | undefined> {\n this.clearHeartbeatInterval()\n if (this.reconnectTimeoutID !== null) {\n clearTimeout(this.reconnectTimeoutID)\n this.reconnectTimeoutID = null\n }\n if (this.state === WebSocket.CLOSED) {\n return Promise.resolve(undefined)\n }\n if (this.ws == null) {\n return Promise.resolve(undefined)\n }\n\n return new Promise((resolve) => {\n if (this.ws == null) {\n resolve(undefined)\n }\n if (this.ws != null) {\n this.ws.once('close', (code) => resolve(code))\n }\n /*\n * Connection already has a disconnect handler for the disconnect logic.\n * Just close the websocket manually (with our \"intentional\" code) to\n * trigger that.\n */\n if (this.ws != null && this.state !== WebSocket.CLOSING) {\n this.ws.close(INTENTIONAL_DISCONNECT_CODE)\n }\n })\n }\n\n /**\n * Disconnect the websocket, then connect again.\n *\n */\n public async reconnect(): Promise<void> {\n /*\n * NOTE: We currently have a \"reconnecting\" event, but that only triggers\n * through an unexpected connection retry logic.\n * See: https://github.com/XRPLF/xrpl.js/pull/1101#issuecomment-565360423\n */\n this.emit('reconnect')\n await this.disconnect()\n await this.connect()\n }\n\n /**\n * Sends a request to the rippled server.\n *\n * @param request - The request to send to the server.\n * @param timeout - How long the Connection instance should wait before assuming that there will not be a response.\n * @returns The response from the rippled server.\n * @throws NotConnectedError if the Connection isn't connected to a server.\n */\n public async request<\n R extends BaseRequest,\n T = RequestResponseMap<R, APIVersion>,\n >(request: R, timeout?: number): Promise<T> {\n if (!this.shouldBeConnected || this.ws == null) {\n throw new NotConnectedError(JSON.stringify(request), request)\n }\n const [id, message, responsePromise] = this.requestManager.createRequest<\n R,\n T\n >(request, timeout ?? this.config.timeout)\n this.trace('send', message)\n websocketSendAsync(this.ws, message).catch((error) => {\n this.requestManager.reject(id, error)\n })\n\n return responsePromise\n }\n\n /**\n * Get the Websocket connection URL.\n *\n * @returns The Websocket connection URL.\n */\n public getUrl(): string {\n return this.url ?? ''\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function, class-methods-use-this -- Does nothing on default\n public readonly trace: (id: string, message: string) => void = () => {}\n\n /**\n * Handler for when messages are received from the server.\n *\n * @param message - The message received from the server.\n */\n private onMessage(message): void {\n this.trace('receive', message)\n let data: Record<string, unknown>\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Must be a JSON dictionary\n data = JSON.parse(message)\n } catch (error) {\n if (error instanceof Error) {\n this.emit('error', 'badMessage', error.message, message)\n }\n return\n }\n if (data.type == null && data.error) {\n // e.g. slowDown\n this.emit('error', data.error, data.error_message, data)\n return\n }\n if (data.type) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true\n this.emit(data.type as string, data)\n }\n if (data.type === 'response') {\n try {\n this.requestManager.handleResponse(data)\n } catch (error) {\n if (error instanceof Error) {\n this.emit('error', 'badMessage', error.message, message)\n } else {\n this.emit('error', 'badMessage', error, error)\n }\n }\n }\n }\n\n /**\n * Handler for what to do once the connection to the server is open.\n *\n * @param connectionTimeoutID - Timeout in case the connection hangs longer than expected.\n * @returns A promise that resolves to void when the connection is fully established.\n * @throws Error if the websocket initialized is somehow null.\n */\n // eslint-disable-next-line max-lines-per-function -- Many error code conditionals to check.\n private async onceOpen(\n connectionTimeoutID: ReturnType<typeof setTimeout>,\n ): Promise<void> {\n if (this.ws == null) {\n throw new XrplError('onceOpen: ws is null')\n }\n\n // Once the connection completes successfully, remove all old listeners\n this.ws.removeAllListeners()\n clearTimeout(connectionTimeoutID)\n // Add new, long-term connected listeners for messages and errors\n this.ws.on('message', (message: string) => this.onMessage(message))\n this.ws.on('error', (error) =>\n this.emit('error', 'websocket', error.message, error),\n )\n // Handle a closed connection: reconnect if it was unexpected\n this.ws.once('close', (code?: number, reason?: Uint8Array) => {\n if (this.ws == null) {\n throw new XrplError('onceClose: ws is null')\n }\n\n this.clearHeartbeatInterval()\n this.requestManager.rejectAll(\n new DisconnectedError(\n `websocket was closed, ${\n reason ? hexToString(bytesToHex(reason)) : ''\n }`,\n ),\n )\n this.ws.removeAllListeners()\n this.ws = null\n\n if (code === undefined) {\n // Useful to keep this code for debugging purposes.\n // const reasonText = reason ? reason.toString() : 'undefined'\n // // eslint-disable-next-line no-console -- The error is helpful for debugging.\n // console.error(\n // `Disconnected but the disconnect code was undefined (The given reason was ${reasonText}).` +\n // `This could be caused by an exception being thrown during a 'connect' callback. ` +\n // `Disconnecting with code 1011 to indicate an internal error has occurred.`,\n // )\n\n /*\n * Error code 1011 represents an Internal Error according to\n * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n */\n const internalErrorCode = 1011\n this.emit('disconnected', internalErrorCode)\n } else {\n this.emit('disconnected', code)\n }\n\n /*\n * If this wasn't a manual disconnect, then lets reconnect ASAP.\n * Code can be undefined if there's an exception while connecting.\n */\n if (code !== INTENTIONAL_DISCONNECT_CODE && code !== undefined) {\n this.intentionalDisconnect()\n }\n })\n // Finalize the connection and resolve all awaiting connect() requests\n try {\n this.retryConnectionBackoff.reset()\n this.startHeartbeatInterval()\n this.connectionManager.resolveAllAwaiting()\n this.emit('connected')\n } catch (error) {\n if (error instanceof Error) {\n this.connectionManager.rejectAllAwaiting(error)\n // Ignore this error, propagate the root cause.\n // eslint-disable-next-line @typescript-eslint/no-empty-function -- Need empty catch\n await this.disconnect().catch(() => {})\n }\n }\n }\n\n private intentionalDisconnect(): void {\n const retryTimeout = this.retryConnectionBackoff.duration()\n this.trace('reconnect', `Retrying connection in ${retryTimeout}ms.`)\n this.emit('reconnecting', this.retryConnectionBackoff.attempts)\n /*\n * Start the reconnect timeout, but set it to `this.reconnectTimeoutID`\n * so that we can cancel one in-progress on disconnect.\n */\n this.reconnectTimeoutID = setTimeout(() => {\n this.reconnect().catch((error: Error) => {\n this.emit('error', 'reconnect', error.message, error)\n })\n }, retryTimeout)\n }\n\n /**\n * Clears the heartbeat connection interval.\n */\n private clearHeartbeatInterval(): void {\n if (this.heartbeatIntervalID) {\n clearInterval(this.heartbeatIntervalID)\n }\n }\n\n /**\n * Starts a heartbeat to check the connection with the server.\n *\n */\n private startHeartbeatInterval(): void {\n this.clearHeartbeatInterval()\n this.heartbeatIntervalID = setInterval(() => {\n void this.heartbeat()\n }, this.config.timeout)\n }\n\n /**\n * A heartbeat is just a \"ping\" command, sent on an interval.\n * If this succeeds, we're good. If it fails, disconnect so that the consumer can reconnect, if desired.\n *\n * @returns A Promise that resolves to void when the heartbeat returns successfully.\n */\n private async heartbeat(): Promise<void> {\n this.request({ command: 'ping' }).catch(async () => {\n return this.reconnect().catch((error: Error) => {\n this.emit('error', 'reconnect', error.message, error)\n })\n })\n }\n\n /**\n * Process a failed connection.\n *\n * @param errorOrCode - (Optional) Error or code for connection failure.\n */\n private onConnectionFailed(errorOrCode: Error | number | null): void {\n if (this.ws) {\n this.ws.removeAllListeners()\n this.ws.on('error', () => {\n /*\n * Correctly listen for -- but ignore -- any future errors: If you\n * don't have a listener on \"error\" node would log a warning on error.\n */\n })\n this.ws.close()\n this.ws = null\n }\n if (typeof errorOrCode === 'number') {\n this.connectionManager.rejectAllAwaiting(\n new NotConnectedError(`Connection failed with code ${errorOrCode}.`, {\n code: errorOrCode,\n }),\n )\n } else if (errorOrCode?.message) {\n this.connectionManager.rejectAllAwaiting(\n new NotConnectedError(errorOrCode.message, errorOrCode),\n )\n } else {\n this.connectionManager.rejectAllAwaiting(\n new NotConnectedError('Connection failed.'),\n )\n }\n }\n}\n","import {\n DEFAULT_DEFINITIONS,\n Field,\n TransactionType,\n LedgerEntryType,\n Type,\n TransactionResult,\n} from './enums'\nimport * as types from './types'\nimport * as binary from './binary'\nimport { ShaMap } from './shamap'\nimport * as ledgerHashes from './ledger-hashes'\nimport * as hashes from './hashes'\nimport { quality } from './quality'\nimport { HashPrefix } from './hash-prefixes'\n\nexport {\n hashes,\n binary,\n ledgerHashes,\n DEFAULT_DEFINITIONS,\n Field,\n TransactionType,\n LedgerEntryType,\n Type,\n TransactionResult,\n quality,\n HashPrefix,\n ShaMap,\n types,\n}\n","import { decode } from 'ripple-binary-codec'\n\nimport {\n CreatedNode,\n isCreatedNode,\n TransactionMetadata,\n} from '../models/transactions/metadata'\n\n/**\n * Ensures that the metadata is in a deserialized format to parse.\n *\n * @param meta - the metadata from a `tx` method call. Can be in json format or binary format.\n * @returns the metadata in a deserialized format.\n */\nfunction ensureDecodedMeta(\n meta: TransactionMetadata | string,\n): TransactionMetadata {\n if (typeof meta === 'string') {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Meta is either metadata or serialized metadata.\n return decode(meta) as unknown as TransactionMetadata\n }\n return meta\n}\n\n/**\n * Gets the XChainClaimID value from the metadata of an `XChainCreateClaimID` transaction.\n *\n * @param meta - Metadata from the response to submitting and waiting for an XChainCreateClaimID transaction\n * or from a `tx` method call.\n * @returns The XChainClaimID for the minted NFT.\n * @throws if meta is not TransactionMetadata.\n */\nexport default function getXChainClaimID(\n meta: TransactionMetadata | string | undefined,\n): string | undefined {\n if (typeof meta !== 'string' && meta?.AffectedNodes === undefined) {\n throw new TypeError(`Unable to parse the parameter given to getXChainClaimID.\n 'meta' must be the metadata from an XChainCreateClaimID transaction. Received ${JSON.stringify(\n meta,\n )} instead.`)\n }\n\n const decodedMeta = ensureDecodedMeta(meta)\n\n if (!decodedMeta.TransactionResult) {\n throw new TypeError(\n 'Cannot get XChainClaimID from un-validated transaction',\n )\n }\n\n if (decodedMeta.TransactionResult !== 'tesSUCCESS') {\n return undefined\n }\n\n const createdNode = decodedMeta.AffectedNodes.find(\n (node) =>\n isCreatedNode(node) &&\n node.CreatedNode.LedgerEntryType === 'XChainOwnedClaimID',\n )\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- necessary here\n return (createdNode as CreatedNode).CreatedNode.NewFields\n .XChainClaimID as string\n}\n","import { UInt } from './uint'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { readUInt32BE, writeUInt32BE } from '../utils'\n\n/**\n * Derived UInt class for serializing/deserializing 32 bit UInt\n */\nclass UInt32 extends UInt {\n protected static readonly width: number = 32 / 8 // 4\n static readonly defaultUInt32: UInt32 = new UInt32(\n new Uint8Array(UInt32.width),\n )\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? UInt32.defaultUInt32.bytes)\n }\n\n static fromParser(parser: BinaryParser): UInt {\n return new UInt32(parser.read(UInt32.width))\n }\n\n /**\n * Construct a UInt32 object from a number\n *\n * @param val UInt32 object or number\n */\n static from<T extends UInt32 | number | string>(val: T): UInt32 {\n if (val instanceof UInt32) {\n return val\n }\n\n const buf = new Uint8Array(UInt32.width)\n\n if (typeof val === 'string') {\n const num = Number.parseInt(val)\n writeUInt32BE(buf, num, 0)\n return new UInt32(buf)\n }\n\n if (typeof val === 'number') {\n UInt32.checkUintRange(val, 0, 0xffffffff)\n writeUInt32BE(buf, val, 0)\n return new UInt32(buf)\n }\n\n throw new Error('Cannot construct UInt32 from given value')\n }\n\n /**\n * get the value of a UInt32 object\n *\n * @returns the number represented by this.bytes\n */\n valueOf(): number {\n return parseInt(readUInt32BE(this.bytes, 0), 10)\n }\n}\n\nexport { UInt32 }\n","import type { Client } from '../client'\nimport { XRPLFaucetError } from '../errors'\n\nexport interface FaucetWallet {\n account: {\n xAddress: string\n classicAddress?: string\n secret: string\n }\n amount: number\n balance: number\n}\n\nexport enum FaucetNetwork {\n Testnet = 'faucet.altnet.rippletest.net',\n Devnet = 'faucet.devnet.rippletest.net',\n WasmDevnet = 'wasmfaucet.devnet.rippletest.net',\n}\n\nexport const faucetNetworkPaths: Record<string, string> = {\n [FaucetNetwork.Testnet]: '/accounts',\n [FaucetNetwork.Devnet]: '/accounts',\n [FaucetNetwork.WasmDevnet]: '/accounts',\n}\n\n/* eslint-disable @typescript-eslint/no-magic-numbers -- this is where they're being defined */\nexport const faucetNetworkIDs: Map<number, FaucetNetwork> = new Map([\n [1, FaucetNetwork.Testnet],\n [2, FaucetNetwork.Devnet],\n [2002, FaucetNetwork.WasmDevnet],\n])\n/* eslint-enable @typescript-eslint/no-magic-numbers */\n\n/**\n * Get the faucet host based on the Client connection.\n *\n * @param client - Client.\n * @returns A {@link FaucetNetwork}.\n * @throws When there is no known faucet for the client's network ID.\n */\nexport function getFaucetHost(client: Client): FaucetNetwork | undefined {\n if (client.networkID == null) {\n throw new XRPLFaucetError(\n 'Cannot create faucet URL without networkID or the faucetHost information',\n )\n }\n\n if (faucetNetworkIDs.has(client.networkID)) {\n return faucetNetworkIDs.get(client.networkID)\n }\n\n if (client.networkID === 0) {\n // mainnet does not have a faucet\n throw new XRPLFaucetError('Faucet is not available for mainnet.')\n }\n\n throw new XRPLFaucetError('Faucet URL is not defined or inferrable.')\n}\n\n/**\n * Get the faucet pathname based on the faucet hostname.\n *\n * @param hostname - hostname.\n * @returns A String with the correct path for the input hostname.\n * If hostname undefined or cannot find (key, value) pair in {@link faucetNetworkPaths}, defaults to '/accounts'\n */\nexport function getFaucetPath(hostname: string | undefined): string {\n if (hostname === undefined) {\n return '/accounts'\n }\n return faucetNetworkPaths[hostname] || '/accounts'\n}\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output<T extends Hash<T>>(\n PRF: Hash<T>,\n PRFSalt: Hash<T>,\n DK: Uint8Array,\n prfW: Hash<T>,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise<Uint8Array> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.ts';\n// export { isBytes } from './_assert.ts';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n// Cast array to view\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const byteSwapIfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): void {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Convert JS string to byte array.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash function */\nexport type CHash = ReturnType<typeof wrapConstructor>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof wrapConstructorWithOpts>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof wrapXOFConstructorWithOpts>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function wrapConstructor<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/* eslint-disable @typescript-eslint/no-magic-numbers -- Doing many bitwise operations which need specific numbers */\n/* eslint-disable no-bitwise -- Bitwise operators are required for this encoding/decoding */\n/* eslint-disable id-length -- Bitwise math uses shorthand terms */\n/*\n *rfc1751.ts : Converts between 128-bit strings and a human-readable\n *sequence of words, as defined in RFC1751: \"A Convention for\n *Human-Readable 128-bit Keys\", by Daniel L. McDonald.\n *Ported from rfc1751.py / Python Cryptography Toolkit (public domain).\n *Copied from https://github.com/bip32/bip32.github.io/blob/master/js/rfc1751.js which\n *is part of the public domain.\n */\n\nimport { hexToBytes, concat } from '@xrplf/isomorphic/utils'\n\nimport rfc1751Words from './rfc1751Words.json'\n\nconst rfc1751WordList: string[] = rfc1751Words\n\n// Added prettier-ignore to allow _BINARY to be on two lines, instead of one entry per line.\n\n// prettier-ignore\nconst BINARY = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',\n '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'];\n\n/**\n * Convert a number array into a binary string.\n *\n * @param key - An array of numbers in base 10.\n * @returns A binary string.\n */\nfunction keyToBinary(key: number[]): string {\n let res = ''\n for (const num of key) {\n res += BINARY[num >> 4] + BINARY[num & 0x0f]\n }\n return res\n}\n\n/**\n * Converts a substring of an encoded secret to its numeric value.\n *\n * @param key - The encoded secret.\n * @param start - The start index to parse from.\n * @param length - The number of digits to parse after the start index.\n * @returns The binary value of the substring.\n */\nfunction extract(key: string, start: number, length: number): number {\n const subKey = key.substring(start, start + length)\n let acc = 0\n for (let index = 0; index < subKey.length; index++) {\n acc = acc * 2 + subKey.charCodeAt(index) - 48\n }\n return acc\n}\n\n/**\n * Generates a modified RFC1751 mnemonic in the same way rippled's wallet_propose does.\n *\n * @param hex_key - An encoded secret in hex format.\n * @returns A mnemonic following rippled's modified RFC1751 mnemonic standard.\n */\nfunction keyToRFC1751Mnemonic(hex_key: string): string {\n // Remove whitespace and interpret hex\n const buf = hexToBytes(hex_key.replace(/\\s+/gu, ''))\n // Swap byte order and use rfc1751\n let key: number[] = bufferToArray(swap128(buf))\n\n // pad to 8 bytes\n const padding: number[] = []\n for (let index = 0; index < (8 - (key.length % 8)) % 8; index++) {\n padding.push(0)\n }\n key = padding.concat(key)\n\n const english: string[] = []\n for (let index = 0; index < key.length; index += 8) {\n const subKey = key.slice(index, index + 8)\n\n // add parity\n let skbin = keyToBinary(subKey)\n let parity = 0\n for (let j = 0; j < 64; j += 2) {\n parity += extract(skbin, j, 2)\n }\n subKey.push((parity << 6) & 0xff)\n\n skbin = keyToBinary(subKey)\n for (let j = 0; j < 64; j += 11) {\n english.push(rfc1751WordList[extract(skbin, j, 11)])\n }\n }\n return english.join(' ')\n}\n\n/**\n * Converts an english mnemonic following rippled's modified RFC1751 standard to an encoded hex secret.\n *\n * @param english - A mnemonic generated using ripple's modified RFC1751 standard.\n * @throws Error if the parity after decoding does not match.\n * @returns A Buffer containing an encoded secret.\n */\nfunction rfc1751MnemonicToKey(english: string): Uint8Array {\n const words = english.split(' ')\n let key: number[] = []\n\n for (let index = 0; index < words.length; index += 6) {\n const { subKey, word }: { subKey: number[]; word: string } = getSubKey(\n words,\n index,\n )\n\n // check parity\n const skbin = keyToBinary(subKey)\n let parity = 0\n for (let j = 0; j < 64; j += 2) {\n parity += extract(skbin, j, 2)\n }\n const cs0 = extract(skbin, 64, 2)\n const cs1 = parity & 3\n if (cs0 !== cs1) {\n throw new Error(`Parity error at ${word}`)\n }\n\n key = key.concat(subKey.slice(0, 8))\n }\n\n // This is a step specific to the XRPL's implementation\n const bufferKey = swap128(Uint8Array.from(key))\n return bufferKey\n}\n\nfunction getSubKey(\n words: string[],\n index: number,\n): { subKey: number[]; word: string } {\n const sublist = words.slice(index, index + 6)\n let bits = 0\n const ch = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n let word = ''\n for (word of sublist) {\n const idx = rfc1751WordList.indexOf(word.toUpperCase())\n if (idx === -1) {\n throw new TypeError(\n `Expected an RFC1751 word, but received '${word}'. ` +\n `For the full list of words in the RFC1751 encoding see https://datatracker.ietf.org/doc/html/rfc1751`,\n )\n }\n const shift = (8 - ((bits + 11) % 8)) % 8\n const y = idx << shift\n const cl = y >> 16\n const cc = (y >> 8) & 0xff\n const cr = y & 0xff\n const t = Math.floor(bits / 8)\n if (shift > 5) {\n ch[t] |= cl\n ch[t + 1] |= cc\n ch[t + 2] |= cr\n } else if (shift > -3) {\n ch[t] |= cc\n ch[t + 1] |= cr\n } else {\n ch[t] |= cr\n }\n bits += 11\n }\n const subKey: number[] = ch.slice()\n return { subKey, word }\n}\n\nfunction bufferToArray(buf: Uint8Array): number[] {\n /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We know the end type */\n return Array.prototype.slice.call(buf) as number[]\n}\n\nfunction swap(arr: Uint8Array, n: number, m: number): void {\n const i = arr[n]\n // eslint-disable-next-line no-param-reassign -- we have to swap\n arr[n] = arr[m]\n // eslint-disable-next-line no-param-reassign -- see above\n arr[m] = i\n}\n\n/**\n * Interprets arr as an array of 64-bit numbers and swaps byte order in 64 bit chunks.\n * Example of two 64 bit numbers 0000000100000002 => 1000000020000000\n *\n * @param arr A Uint8Array representation of one or more 64 bit numbers\n * @returns Uint8Array An array containing the bytes of 64 bit numbers each with reversed endianness\n */\nfunction swap64(arr: Uint8Array): Uint8Array {\n const len = arr.length\n\n for (let i = 0; i < len; i += 8) {\n swap(arr, i, i + 7)\n swap(arr, i + 1, i + 6)\n swap(arr, i + 2, i + 5)\n swap(arr, i + 3, i + 4)\n }\n\n return arr\n}\n\n/**\n * Swap the byte order of a 128-bit array.\n * Ex. 0000000100000002 => 2000000010000000\n *\n * @param arr - A 128-bit (16 byte) array\n * @returns An array containing the same data with reversed endianness\n */\nfunction swap128(arr: Uint8Array): Uint8Array {\n // Interprets arr as an array of (two, in this case) 64-bit numbers and swaps byte order in 64 bit chunks.\n // Ex. 0000000100000002 => 1000000020000000\n const reversedBytes = swap64(arr)\n // Further swap the two 64-bit numbers since our buffer is 128 bits.\n // Ex. 1000000020000000 => 2000000010000000\n return concat([reversedBytes.slice(8, 16), reversedBytes.slice(0, 8)])\n}\n\nexport { rfc1751MnemonicToKey, keyToRFC1751Mnemonic }\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","import { ValidationError } from '../../errors'\nimport { AuthAccount, Currency, IssuedCurrencyAmount } from '../common'\n\nimport {\n BaseTransaction,\n isAmount,\n isArray,\n isIssuedCurrency,\n isRecord,\n validateBaseTransaction,\n} from './common'\n\nconst MAX_AUTH_ACCOUNTS = 4\n\n/**\n * Bid on an Automated Market Maker's (AMM's) auction slot.\n *\n * If you win, you can trade against the AMM at a discounted fee until you are outbid or 24 hours have passed.\n * If you are outbid before 24 hours have passed, you are refunded part of the cost of your bid based on how much time remains.\n * You bid using the AMM's LP Tokens; the amount of a winning bid is returned to the AMM,\n * decreasing the outstanding balance of LP Tokens.\n */\nexport interface AMMBid extends BaseTransaction {\n TransactionType: 'AMMBid'\n\n /**\n * The definition for one of the assets in the AMM's pool.\n */\n Asset: Currency\n\n /**\n * The definition for the other asset in the AMM's pool.\n */\n Asset2: Currency\n\n /**\n * Pay at least this LPToken amount for the slot.\n * Setting this value higher makes it harder for others to outbid you.\n * If omitted, pay the minimum necessary to win the bid.\n */\n BidMin?: IssuedCurrencyAmount\n\n /**\n * Pay at most this LPToken amount for the slot.\n * If the cost to win the bid is higher than this amount, the transaction fails.\n * If omitted, pay as much as necessary to win the bid.\n */\n BidMax?: IssuedCurrencyAmount\n\n /**\n * A list of up to 4 additional accounts that you allow to trade at the discounted fee.\n * This cannot include the address of the transaction sender.\n */\n AuthAccounts?: AuthAccount[]\n}\n\n/**\n * Verify the form and type of an AMMBid at runtime.\n *\n * @param tx - An AMMBid Transaction.\n * @throws When the AMMBid is Malformed.\n */\nexport function validateAMMBid(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Asset == null) {\n throw new ValidationError('AMMBid: missing field Asset')\n }\n\n if (!isIssuedCurrency(tx.Asset)) {\n throw new ValidationError('AMMBid: Asset must be a Currency')\n }\n\n if (tx.Asset2 == null) {\n throw new ValidationError('AMMBid: missing field Asset2')\n }\n\n if (!isIssuedCurrency(tx.Asset2)) {\n throw new ValidationError('AMMBid: Asset2 must be a Currency')\n }\n\n if (tx.BidMin != null && !isAmount(tx.BidMin)) {\n throw new ValidationError('AMMBid: BidMin must be an Amount')\n }\n\n if (tx.BidMax != null && !isAmount(tx.BidMax)) {\n throw new ValidationError('AMMBid: BidMax must be an Amount')\n }\n\n if (tx.AuthAccounts != null) {\n if (!isArray(tx.AuthAccounts)) {\n throw new ValidationError(\n `AMMBid: AuthAccounts must be an AuthAccount array`,\n )\n }\n if (tx.AuthAccounts.length > MAX_AUTH_ACCOUNTS) {\n throw new ValidationError(\n `AMMBid: AuthAccounts length must not be greater than ${MAX_AUTH_ACCOUNTS}`,\n )\n }\n validateAuthAccounts(tx.Account, tx.AuthAccounts)\n }\n}\n\nfunction validateAuthAccounts(\n senderAddress: string,\n authAccounts: unknown[],\n): boolean {\n for (const authAccount of authAccounts) {\n if (!isRecord(authAccount)) {\n throw new ValidationError(`AMMBid: invalid AuthAccounts`)\n }\n if (!isRecord(authAccount.AuthAccount)) {\n throw new ValidationError(`AMMBid: invalid AuthAccounts`)\n }\n if (authAccount.AuthAccount.Account == null) {\n throw new ValidationError(`AMMBid: invalid AuthAccounts`)\n }\n if (typeof authAccount.AuthAccount.Account !== 'string') {\n throw new ValidationError(`AMMBid: invalid AuthAccounts`)\n }\n if (authAccount.AuthAccount.Account === senderAddress) {\n throw new ValidationError(\n `AMMBid: AuthAccounts must not include sender's address`,\n )\n }\n }\n\n return true\n}\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n type AffinePoint,\n type BasicCurve,\n type Group,\n type GroupConstructor,\n pippenger,\n validateBasic,\n wNAF,\n} from './curve.js';\nimport {\n Field,\n type IField,\n getMinHashLength,\n invert,\n mapHashToField,\n mod,\n validateField,\n} from './modular.js';\nimport * as ut from './utils.js';\nimport { type CHash, type Hex, type PrivKey, abool, ensureBytes, memoized } from './utils.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\ntype Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType<T>;\n toAffine(iz?: T): AffinePoint<T>;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n msm(points: ProjPointType<T>[], scalars: bigint[]): ProjPointType<T>;\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = ut.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType<T> {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint<T> {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // Our custom check \"just in case\"\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n ut.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || ut.isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n","import type {\n Client,\n SubmitRequest,\n SubmitResponse,\n SubmittableTransaction,\n Transaction,\n Wallet,\n} from '..'\nimport { ValidationError, XrplError } from '../errors'\nimport { Signer } from '../models/common'\nimport { TxResponse } from '../models/methods'\nimport { BaseTransaction } from '../models/transactions/common'\nimport { decode, encode } from '../utils'\n\n/** Approximate time for a ledger to close, in milliseconds */\nconst LEDGER_CLOSE_TIME = 1000\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n// Helper functions\n\n/**\n * Submits a request to the client with a signed transaction.\n *\n * @param client - The client to submit the request to.\n * @param signedTransaction - The signed transaction to submit. It can be either a Transaction object or a\n * string (encode from ripple-binary-codec) representation of the transaction.\n * @param [failHard=false] - Optional. Determines whether the submission should fail hard (true) or not (false). Default is false.\n * @returns A promise that resolves with the response from the client.\n * @throws {ValidationError} If the signed transaction is not valid (not signed).\n *\n * @example\n * import { Client } from \"xrpl\"\n * const client = new Client(\"wss://s.altnet.rippletest.net:51233\");\n * await client.connect();\n * const signedTransaction = createSignedTransaction();\n * // Example 1: Submitting a Transaction object\n * const response1 = await submitRequest(client, signedTransaction);\n *\n * // Example 2: Submitting a string representation of the transaction\n * const signedTransactionString = encode(signedTransaction);\n * const response2 = await submitRequest(client, signedTransactionString, true);\n */\nexport async function submitRequest(\n client: Client,\n signedTransaction: SubmittableTransaction | string,\n failHard = false,\n): Promise<SubmitResponse> {\n if (!isSigned(signedTransaction)) {\n throw new ValidationError('Transaction must be signed.')\n }\n\n const signedTxEncoded =\n typeof signedTransaction === 'string'\n ? signedTransaction\n : encode(signedTransaction)\n const request: SubmitRequest = {\n command: 'submit',\n tx_blob: signedTxEncoded,\n fail_hard: isAccountDelete(signedTransaction) || failHard,\n }\n return client.request(request)\n}\n\n/**\n * Waits for the final outcome of a transaction by polling the ledger until the result can be considered final,\n * meaning it has either been included in a validated ledger, or the transaction's lastLedgerSequence has been\n * surpassed by the latest ledger sequence (meaning it will never be included in a validated ledger).\n *\n * @template T - The type of the transaction. Defaults to `Transaction`.\n * @param client - The client to use for requesting transaction information.\n * @param txHash - The hash of the transaction to wait for.\n * @param lastLedger - The last ledger sequence of the transaction.\n * @param submissionResult - The preliminary result of the transaction.\n * @returns A promise that resolves with the final transaction response.\n *\n * @throws {XrplError} If the latest ledger sequence surpasses the transaction's lastLedgerSequence.\n *\n * @example\n * import { hashes, Client } from \"xrpl\"\n * const client = new Client(\"wss://s.altnet.rippletest.net:51233\")\n * await client.connect()\n *\n * const transaction = createTransaction() // your transaction function\n *\n * const signedTx = await getSignedTx(this, transaction)\n *\n * const lastLedger = getLastLedgerSequence(signedTx)\n *\n * if (lastLedger == null) {\n * throw new ValidationError(\n * 'Transaction must contain a LastLedgerSequence value for reliable submission.',\n * )\n * }\n *\n * const response = await submitRequest(this, signedTx, opts?.failHard)\n *\n * const txHash = hashes.hashSignedTx(signedTx)\n * return waitForFinalTransactionOutcome(\n * this,\n * txHash,\n * lastLedger,\n * response.result.engine_result,\n * )\n */\n// eslint-disable-next-line max-params, max-lines-per-function -- this function needs to display and do with more information.\nexport async function waitForFinalTransactionOutcome<\n T extends BaseTransaction = SubmittableTransaction,\n>(\n client: Client,\n txHash: string,\n lastLedger: number,\n submissionResult: string,\n): Promise<TxResponse<T>> {\n await sleep(LEDGER_CLOSE_TIME)\n\n const latestLedger = await client.getLedgerIndex()\n\n if (lastLedger < latestLedger) {\n throw new XrplError(\n `The latest ledger sequence ${latestLedger} is greater than the transaction's LastLedgerSequence (${lastLedger}).\\n` +\n `Preliminary result: ${submissionResult}`,\n )\n }\n\n const txResponse = await client\n .request({\n command: 'tx',\n transaction: txHash,\n })\n .catch(async (error) => {\n // error is of an unknown type and hence we assert type to extract the value we need.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions,@typescript-eslint/no-unsafe-member-access -- ^\n const message = error?.data?.error as string\n if (message === 'txnNotFound') {\n return waitForFinalTransactionOutcome<T>(\n client,\n txHash,\n lastLedger,\n submissionResult,\n )\n }\n throw new Error(\n `${message} \\n Preliminary result: ${submissionResult}.\\nFull error details: ${String(\n error,\n )}`,\n )\n })\n\n if (txResponse.result.validated) {\n // TODO: resolve the type assertion below\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- we know that txResponse is of type TxResponse\n return txResponse as TxResponse<T>\n }\n\n return waitForFinalTransactionOutcome<T>(\n client,\n txHash,\n lastLedger,\n submissionResult,\n )\n}\n\n// checks if the transaction has been signed\nfunction isSigned(transaction: SubmittableTransaction | string): boolean {\n const tx = typeof transaction === 'string' ? decode(transaction) : transaction\n if (typeof tx === 'string') {\n return false\n }\n if (tx.Signers != null) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- we know that tx.Signers is an array of Signers\n const signers = tx.Signers as Signer[]\n for (const signer of signers) {\n if (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- necessary check\n signer.Signer.SigningPubKey == null ||\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- necessary check\n signer.Signer.TxnSignature == null\n ) {\n return false\n }\n }\n return true\n }\n return tx.SigningPubKey != null && tx.TxnSignature != null\n}\n\n/**\n * Updates a transaction with `autofill` then signs it if it is unsigned.\n *\n * @param client - The client from which to retrieve the signed transaction.\n * @param transaction - The transaction to retrieve. It can be either a Transaction object or\n * a string (encode from ripple-binary-codec) representation of the transaction.\n * @param [options={}] - Optional. Additional options for retrieving the signed transaction.\n * @param [options.autofill=true] - Optional. Determines whether the transaction should be autofilled (true)\n * or not (false). Default is true.\n * @param [options.wallet] - Optional. A wallet to sign the transaction. It must be provided when submitting\n * an unsigned transaction. Default is undefined.\n * @returns A promise that resolves with the signed transaction.\n *\n * @throws {ValidationError} If the transaction is not signed and no wallet is provided.\n *\n * @example\n * import { Client } from \"xrpl\"\n * import { encode } from \"ripple-binary-codec\"\n *\n * const client = new Client(\"wss://s.altnet.rippletest.net:51233\");\n * await client.connect():\n * const transaction = createTransaction(); // createTransaction is your function to create a transaction\n * const options = {\n * autofill: true,\n * wallet: myWallet,\n * };\n *\n * // Example 1: Retrieving a signed Transaction object\n * const signedTx1 = await getSignedTx(client, transaction, options);\n *\n * // Example 2: Retrieving a string representation of the signed transaction\n * const signedTxString = await getSignedTx(client, encode(transaction), options);\n */\nexport async function getSignedTx(\n client: Client,\n transaction: SubmittableTransaction | string,\n {\n autofill = true,\n wallet,\n }: {\n // If true, autofill a transaction.\n autofill?: boolean\n // A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.\n wallet?: Wallet\n } = {},\n): Promise<SubmittableTransaction | string> {\n if (isSigned(transaction)) {\n return transaction\n }\n\n if (!wallet) {\n throw new ValidationError(\n 'Wallet must be provided when submitting an unsigned transaction',\n )\n }\n\n let tx =\n typeof transaction === 'string'\n ? // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- converts JsonObject to correct Transaction type\n (decode(transaction) as unknown as SubmittableTransaction)\n : transaction\n\n if (autofill) {\n tx = await client.autofill(tx)\n }\n\n return wallet.sign(tx).tx_blob\n}\n\n// checks if there is a LastLedgerSequence as a part of the transaction\n/**\n * Retrieves the last ledger sequence from a transaction.\n *\n * @param transaction - The transaction to retrieve the last ledger sequence from. It can be either a Transaction object or\n * a string (encode from ripple-binary-codec) representation of the transaction.\n * @returns The last ledger sequence of the transaction, or null if not available.\n *\n * @example\n * const transaction = createTransaction(); // your function to create a transaction\n *\n * // Example 1: Retrieving the last ledger sequence from a Transaction object\n * const lastLedgerSequence1 = getLastLedgerSequence(transaction);\n * console.log(lastLedgerSequence1); // Output: 12345\n *\n * // Example 2: Retrieving the last ledger sequence from a string representation of the transaction\n * const transactionString = encode(transaction);\n * const lastLedgerSequence2 = getLastLedgerSequence(transactionString);\n * console.log(lastLedgerSequence2); // Output: 67890\n */\nexport function getLastLedgerSequence(\n transaction: Transaction | string,\n): number | null {\n const tx = typeof transaction === 'string' ? decode(transaction) : transaction\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- converts LastLedgerSeq to number if present.\n return tx.LastLedgerSequence as number | null\n}\n\n// checks if the transaction is an AccountDelete transaction\nfunction isAccountDelete(transaction: Transaction | string): boolean {\n const tx = typeof transaction === 'string' ? decode(transaction) : transaction\n return tx.TransactionType === 'AccountDelete'\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n isAmount,\n isXChainBridge,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * Enum representing values of {@link XChainModifyBridge} transaction flags.\n *\n * @category Transaction Flags\n */\nexport enum XChainModifyBridgeFlags {\n /** Clears the MinAccountCreateAmount of the bridge. */\n tfClearAccountCreateAmount = 0x00010000,\n}\n\n/**\n * Map of flags to boolean values representing {@link XChainModifyBridge} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface XChainModifyBridgeFlagsInterface extends GlobalFlagsInterface {\n /** Clears the MinAccountCreateAmount of the bridge. */\n tfClearAccountCreateAmount?: boolean\n}\n\n/**\n * The XChainModifyBridge transaction allows bridge managers to modify the parameters\n * of the bridge.\n *\n * @category Transaction Models\n */\nexport interface XChainModifyBridge extends BaseTransaction {\n TransactionType: 'XChainModifyBridge'\n\n /**\n * The bridge to modify.\n */\n XChainBridge: XChainBridge\n\n /**\n * The signature reward split between the witnesses for submitting attestations.\n */\n SignatureReward?: Amount\n\n /**\n * The minimum amount, in XRP, required for a {@link XChainAccountCreateCommit}\n * transaction. If this is not present, the {@link XChainAccountCreateCommit}\n * transaction will fail. This field can only be present on XRP-XRP bridges.\n */\n MinAccountCreateAmount?: Amount\n\n Flags?: number | XChainModifyBridgeFlagsInterface\n}\n\n/**\n * Verify the form and type of an XChainModifyBridge at runtime.\n *\n * @param tx - An XChainModifyBridge Transaction.\n * @throws When the XChainModifyBridge is malformed.\n */\nexport function validateXChainModifyBridge(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateOptionalField(tx, 'SignatureReward', isAmount)\n\n validateOptionalField(tx, 'MinAccountCreateAmount', isAmount)\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateRequiredField,\n isAccount,\n Account,\n} from './common'\n\nconst PERMISSIONS_MAX_LENGTH = 10\nconst NON_DELEGATABLE_TRANSACTIONS = new Set([\n 'AccountSet',\n 'SetRegularKey',\n 'SignerListSet',\n 'DelegateSet',\n 'AccountDelete',\n 'Batch',\n // Pseudo transactions below:\n 'EnableAmendment',\n 'SetFee',\n 'UNLModify',\n])\n\nexport interface Permission {\n Permission: {\n PermissionValue: string\n }\n}\n\n/**\n * DelegateSet allows an account to delegate a set of permissions to another account.\n *\n * @category Transaction Models\n */\nexport interface DelegateSet extends BaseTransaction {\n TransactionType: 'DelegateSet'\n\n /**\n * The authorized account.\n */\n Authorize: Account\n\n /**\n * The transaction permissions (represented by integers) that the account has been granted.\n */\n Permissions: Permission[]\n}\n\n/**\n * Verify the form and type of an DelegateSet at runtime.\n *\n * @param tx - An DelegateSet Transaction.\n * @throws When the DelegateSet is malformed.\n */\n// eslint-disable-next-line max-lines-per-function -- necessary for validation\nexport function validateDelegateSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Authorize', isAccount)\n\n if (tx.Authorize === tx.Account) {\n throw new ValidationError(\n 'DelegateSet: Authorize and Account must be different.',\n )\n }\n\n validateRequiredField(tx, 'Permissions', Array.isArray)\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- required for validation\n const permissions = tx.Permissions as DelegateSet['Permissions']\n if (permissions.length > PERMISSIONS_MAX_LENGTH) {\n throw new ValidationError(\n `DelegateSet: Permissions array length cannot be greater than ${PERMISSIONS_MAX_LENGTH}.`,\n )\n }\n\n const permissionValueSet = new Set()\n permissions.forEach((permission: Permission) => {\n if (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- required for validation\n permission == null ||\n Object.keys(permission).length !== 1 ||\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- required for validation\n permission.Permission == null ||\n Object.keys(permission.Permission).length !== 1\n ) {\n throw new ValidationError(\n 'DelegateSet: Permissions array element is malformed',\n )\n }\n const permissionValue = permission.Permission.PermissionValue\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- required for validation\n if (permissionValue == null) {\n throw new ValidationError('DelegateSet: PermissionValue must be defined')\n }\n if (typeof permissionValue !== 'string') {\n throw new ValidationError('DelegateSet: PermissionValue must be a string')\n }\n if (NON_DELEGATABLE_TRANSACTIONS.has(permissionValue)) {\n throw new ValidationError(\n `DelegateSet: PermissionValue contains a non-delegatable transaction ${permissionValue}`,\n )\n }\n permissionValueSet.add(permissionValue)\n })\n if (permissions.length !== permissionValueSet.size) {\n throw new ValidationError(\n 'DelegateSet: Permissions array cannot contain duplicate values',\n )\n }\n}\n","import {\n type DefinitionsData,\n XrplDefinitionsBase,\n} from './xrpl-definitions-base'\nimport { coreTypes } from '../types'\nimport { SerializedType } from '../types/serialized-type'\n\n/**\n * Stores the various types and fields for rippled to be used to encode/decode information later on.\n * Should be used instead of XrplDefinitionsBase since this defines default `types` for serializing/deserializing\n * ledger data.\n */\nexport class XrplDefinitions extends XrplDefinitionsBase {\n /**\n * Present rippled types in a typed and updatable format.\n * For an example of the input format see `definitions.json`\n * To generate a new definitions file from rippled source code, use the tool at\n * `packages/ripple-binary-codec/tools/generateDefinitions.js`.\n *\n * See the definitions.test.js file for examples of how to create your own updated definitions.json.\n *\n * @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.\n * @param additionalTypes - A list of SerializedType objects with the same name as the fields defined.\n * These types will be included in addition to the coreTypes used on mainnet.\n */\n constructor(\n enums: DefinitionsData,\n additionalTypes?: Record<string, typeof SerializedType>,\n ) {\n const types = Object.assign({}, coreTypes, additionalTypes)\n super(enums, types)\n }\n}\n","import {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\nexport interface PermissionedDomainDelete extends BaseTransaction {\n /* The transaction type (PermissionedDomainDelete). */\n TransactionType: 'PermissionedDomainDelete'\n\n /* The domain to delete. */\n DomainID: string\n}\n\n/**\n * Verify the form and type of a PermissionedDomainDelete transaction.\n *\n * @param tx - The transaction to verify.\n * @throws When the transaction is malformed.\n */\nexport function validatePermissionedDomainDelete(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'DomainID', isString)\n}\n","/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","import { sha512 } from '@xrplf/isomorphic/sha512'\nimport { bytesToNumberBE } from '@noble/curves/abstract/utils'\n\ntype Input = Uint8Array | number[] | string\n\nexport default class Sha512 {\n // instantiate empty sha512 hash\n hash = sha512.create()\n\n static half(input: Input): Uint8Array {\n return new Sha512().add(input).first256()\n }\n\n add(bytes: Input): this {\n this.hash.update(bytes)\n return this\n }\n\n addU32(i: number): this {\n const buffer = new Uint8Array(4)\n new DataView(buffer.buffer).setUint32(0, i)\n return this.add(buffer)\n }\n\n finish(): Uint8Array {\n return this.hash.digest()\n }\n\n first256(): Uint8Array {\n return this.finish().slice(0, 32)\n }\n\n first256BigInt(): bigint {\n return bytesToNumberBE(this.first256())\n }\n}\n","import { ValidationError } from '../../errors'\nimport { Currency } from '../common'\n\nimport {\n BaseTransaction,\n isIssuedCurrency,\n validateBaseTransaction,\n} from './common'\n\n/**\n * Delete an empty Automated Market Maker (AMM) instance that could not be fully deleted automatically.\n *\n * Tip: The AMMWithdraw transaction automatically tries to delete an AMM, along with associated ledger\n * entries such as empty trust lines, if it withdrew all the assets from the AMM's pool.\n * However, if there are too many trust lines to the AMM account to remove in one transaction,\n * it may stop before fully removing the AMM. Similarly, an AMMDelete transaction removes up to\n * a maximum number of trust lines; in extreme cases, it may take several AMMDelete transactions\n * to fully delete the trust lines and the associated AMM.\n * In all cases, the AMM ledger entry and AMM account are deleted by the last such transaction.\n */\nexport interface AMMDelete extends BaseTransaction {\n TransactionType: 'AMMDelete'\n\n /**\n * The definition for one of the assets in the AMM's pool.\n */\n Asset: Currency\n\n /**\n * The definition for the other asset in the AMM's pool.\n */\n Asset2: Currency\n}\n\n/**\n * Verify the form and type of an AMMDelete at runtime.\n *\n * @param tx - An AMMDelete Transaction.\n * @throws When the AMMDelete is Malformed.\n */\nexport function validateAMMDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Asset == null) {\n throw new ValidationError('AMMDelete: missing field Asset')\n }\n\n if (!isIssuedCurrency(tx.Asset)) {\n throw new ValidationError('AMMDelete: Asset must be a Currency')\n }\n\n if (tx.Asset2 == null) {\n throw new ValidationError('AMMDelete: missing field Asset2')\n }\n\n if (!isIssuedCurrency(tx.Asset2)) {\n throw new ValidationError('AMMDelete: Asset2 must be a Currency')\n }\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n BaseTransaction,\n isAmount,\n isXChainBridge,\n validateBaseTransaction,\n validateRequiredField,\n isAccount,\n Account,\n} from './common'\n\n/**\n * The XChainAccountCreateCommit transaction creates a new account on one of the\n * chains a bridge connects, which serves as the bridge entrance for that chain.\n *\n * WARNING: This transaction should only be executed if the witness attestations\n * will be reliably delivered to the destination chain. If the signatures aren't\n * delivered, then account creation will be blocked until attestations are received.\n * This can be used maliciously; to disable this transaction on XRP-XRP bridges,\n * the bridge's MinAccountCreateAmount shouldn't be present.\n *\n * @category Transaction Models\n */\nexport interface XChainAccountCreateCommit extends BaseTransaction {\n TransactionType: 'XChainAccountCreateCommit'\n\n /**\n * The bridge to create accounts for.\n */\n XChainBridge: XChainBridge\n\n /**\n * The amount, in XRP, to be used to reward the witness servers for providing\n * signatures. This must match the amount on the {@link Bridge} ledger object.\n */\n SignatureReward: Amount\n\n /**\n * The destination account on the destination chain.\n */\n Destination: Account\n\n /**\n * The amount, in XRP, to use for account creation. This must be greater than or\n * equal to the MinAccountCreateAmount specified in the {@link Bridge} ledger object.\n */\n Amount: Amount\n}\n\n/**\n * Verify the form and type of an XChainAccountCreateCommit at runtime.\n *\n * @param tx - An XChainAccountCreateCommit Transaction.\n * @throws When the XChainAccountCreateCommit is malformed.\n */\nexport function validateXChainAccountCreateCommit(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(tx, 'SignatureReward', isAmount)\n\n validateRequiredField(tx, 'Destination', isAccount)\n\n validateRequiredField(tx, 'Amount', isAmount)\n}\n","/* eslint-disable jsdoc/require-jsdoc -- Request has many aliases, but they don't need unique docs */\n\n/* eslint-disable max-lines -- Client is a large file w/ lots of imports/exports */\nimport { EventEmitter } from 'eventemitter3'\n\nimport {\n RippledError,\n NotFoundError,\n ValidationError,\n XrplError,\n} from '../errors'\nimport {\n APIVersion,\n LedgerIndex,\n Balance,\n DEFAULT_API_VERSION,\n} from '../models/common'\nimport {\n Request,\n // account methods\n AccountChannelsRequest,\n AccountChannelsResponse,\n AccountInfoRequest,\n AccountLinesRequest,\n AccountLinesResponse,\n AccountObjectsRequest,\n AccountObjectsResponse,\n AccountOffersRequest,\n AccountOffersResponse,\n AccountTxRequest,\n AccountTxResponse,\n // ledger methods\n LedgerDataRequest,\n LedgerDataResponse,\n TxResponse,\n} from '../models/methods'\nimport type {\n RequestResponseMap,\n RequestAllResponseMap,\n MarkerRequest,\n MarkerResponse,\n SubmitResponse,\n SimulateRequest,\n} from '../models/methods'\nimport type { BookOffer, BookOfferCurrency } from '../models/methods/bookOffers'\nimport {\n SimulateBinaryResponse,\n SimulateJsonResponse,\n} from '../models/methods/simulate'\nimport type {\n EventTypes,\n OnEventToListenerMap,\n} from '../models/methods/subscribe'\nimport type { SubmittableTransaction } from '../models/transactions'\nimport { convertTxFlagsToNumber } from '../models/utils/flags'\nimport {\n ensureClassicAddress,\n submitRequest,\n getSignedTx,\n getLastLedgerSequence,\n waitForFinalTransactionOutcome,\n} from '../sugar'\nimport {\n setValidAddresses,\n setNextValidSequenceNumber,\n setLatestValidatedLedgerSequence,\n checkAccountDeleteBlockers,\n txNeedsNetworkID,\n autofillBatchTxn,\n handleDeliverMax,\n getTransactionFee,\n} from '../sugar/autofill'\nimport { formatBalances } from '../sugar/balances'\nimport {\n validateOrderbookOptions,\n createBookOffersRequest,\n requestAllOffers,\n reverseRequest,\n extractOffers,\n combineOrders,\n separateBuySellOrders,\n sortAndLimitOffers,\n} from '../sugar/getOrderbook'\nimport { dropsToXrp, hashes, isValidClassicAddress } from '../utils'\nimport { Wallet } from '../Wallet'\nimport {\n type FaucetRequestBody,\n FundingOptions,\n requestFunding,\n} from '../Wallet/fundWallet'\n\nimport {\n Connection,\n ConnectionUserOptions,\n INTENTIONAL_DISCONNECT_CODE,\n} from './connection'\nimport {\n handlePartialPayment,\n handleStreamPartialPayment,\n} from './partialPayment'\n\nexport interface ClientOptions extends ConnectionUserOptions {\n /**\n * Multiplication factor to multiply estimated fee by to provide a cushion in case the\n * required fee rises during submission of a transaction. Defaults to 1.2.\n *\n * @category Fee\n */\n feeCushion?: number\n /**\n * Maximum transaction cost to allow, in decimal XRP. Must be a string-encoded\n * number. Defaults to '2'.\n *\n * @category Fee\n */\n maxFeeXRP?: string\n /**\n * Duration to wait for a request to timeout.\n */\n timeout?: number\n}\n\n// Make sure to update both this and `RequestNextPageReturnMap` at the same time\ntype RequestNextPageType =\n | AccountChannelsRequest\n | AccountLinesRequest\n | AccountObjectsRequest\n | AccountOffersRequest\n | AccountTxRequest\n | LedgerDataRequest\n\ntype RequestNextPageReturnMap<T> = T extends AccountChannelsRequest\n ? AccountChannelsResponse\n : T extends AccountLinesRequest\n ? AccountLinesResponse\n : T extends AccountObjectsRequest\n ? AccountObjectsResponse\n : T extends AccountOffersRequest\n ? AccountOffersResponse\n : T extends AccountTxRequest\n ? AccountTxResponse\n : T extends LedgerDataRequest\n ? LedgerDataResponse\n : never\n\n/**\n * Get the response key / property name that contains the listed data for a\n * command. This varies from command to command, but we need to know it to\n * properly count across many requests.\n *\n * @param command - The rippled request command.\n * @returns The property key corresponding to the command.\n */\nfunction getCollectKeyFromCommand(command: string): string | null {\n switch (command) {\n case 'account_channels':\n return 'channels'\n case 'account_lines':\n return 'lines'\n case 'account_objects':\n return 'account_objects'\n case 'account_tx':\n return 'transactions'\n case 'account_offers':\n case 'book_offers':\n return 'offers'\n case 'ledger_data':\n return 'state'\n default:\n return null\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n if (min > max) {\n throw new Error('Illegal clamp bounds')\n }\n return Math.min(Math.max(value, min), max)\n}\n\nconst DEFAULT_FEE_CUSHION = 1.2\nconst DEFAULT_MAX_FEE_XRP = '2'\n\nconst MIN_LIMIT = 10\nconst MAX_LIMIT = 400\n\nconst NORMAL_DISCONNECT_CODE = 1000\n\n/**\n * Client for interacting with rippled servers.\n *\n * @category Clients\n */\nclass Client extends EventEmitter<EventTypes> {\n /*\n * Underlying connection to rippled.\n */\n public readonly connection: Connection\n\n /**\n * Factor to multiply estimated fee by to provide a cushion in case the\n * required fee rises during submission of a transaction. Defaults to 1.2.\n *\n * @category Fee\n */\n public readonly feeCushion: number\n\n /**\n * Maximum transaction cost to allow, in decimal XRP. Must be a string-encoded\n * number. Defaults to '2'.\n *\n * @category Fee\n */\n public readonly maxFeeXRP: string\n\n /**\n * Network ID of the server this client is connected to\n *\n */\n public networkID: number | undefined\n\n /**\n * Rippled Version used by the server this client is connected to\n *\n */\n public buildVersion: string | undefined\n\n /**\n * API Version used by the server this client is connected to\n *\n */\n public apiVersion: APIVersion = DEFAULT_API_VERSION\n\n /**\n * Creates a new Client with a websocket connection to a rippled server.\n *\n * @param server - URL of the server to connect to.\n * @param options - Options for client settings.\n * @category Constructor\n *\n * @example\n * ```ts\n * import { Client } from \"xrpl\"\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * ```\n */\n /* eslint-disable max-lines-per-function -- the constructor requires more lines to implement the logic */\n public constructor(server: string, options: ClientOptions = {}) {\n super()\n if (typeof server !== 'string' || !/wss?(?:\\+unix)?:\\/\\//u.exec(server)) {\n throw new ValidationError(\n 'server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.',\n )\n }\n\n this.feeCushion = options.feeCushion ?? DEFAULT_FEE_CUSHION\n this.maxFeeXRP = options.maxFeeXRP ?? DEFAULT_MAX_FEE_XRP\n\n this.connection = new Connection(server, options)\n\n this.connection.on('error', (errorCode, errorMessage, data) => {\n this.emit('error', errorCode, errorMessage, data)\n })\n\n this.connection.on('reconnect', () => {\n this.connection.on('connected', () => this.emit('connected'))\n })\n\n this.connection.on('disconnected', (code: number) => {\n let finalCode = code\n /*\n * 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close\n * Since 4000 is a normal disconnect reason, we convert this to the standard exit code 1000\n */\n if (finalCode === INTENTIONAL_DISCONNECT_CODE) {\n finalCode = NORMAL_DISCONNECT_CODE\n }\n this.emit('disconnected', finalCode)\n })\n\n this.connection.on('ledgerClosed', (ledger) => {\n this.emit('ledgerClosed', ledger)\n })\n\n this.connection.on('transaction', (tx) => {\n // mutates `tx` to add warnings\n handleStreamPartialPayment(tx, this.connection.trace)\n this.emit('transaction', tx)\n })\n\n this.connection.on('validationReceived', (validation) => {\n this.emit('validationReceived', validation)\n })\n\n this.connection.on('manifestReceived', (manifest) => {\n this.emit('manifestReceived', manifest)\n })\n\n this.connection.on('peerStatusChange', (status) => {\n this.emit('peerStatusChange', status)\n })\n\n this.connection.on('consensusPhase', (consensus) => {\n this.emit('consensusPhase', consensus)\n })\n\n this.connection.on('path_find', (path) => {\n this.emit('path_find', path)\n })\n }\n /* eslint-enable max-lines-per-function */\n\n /**\n * Get the url that the client is connected to.\n *\n * @returns The URL of the server this client is connected to.\n * @category Network\n */\n public get url(): string {\n return this.connection.getUrl()\n }\n\n /**\n * Makes a request to the client with the given command and\n * additional request body parameters.\n *\n * @category Network\n * @param req - Request to send to the server.\n * @returns The response from the server.\n *\n * @example\n * ```ts\n * const response = await client.request({\n * command: 'account_info',\n * account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',\n * })\n * console.log(response)\n * ```\n */\n public async request<\n R extends Request,\n V extends APIVersion = typeof DEFAULT_API_VERSION,\n T = RequestResponseMap<R, V>,\n >(req: R): Promise<T> {\n const request = {\n ...req,\n account:\n typeof req.account === 'string'\n ? ensureClassicAddress(req.account)\n : undefined,\n api_version: req.api_version ?? this.apiVersion,\n }\n const response = await this.connection.request<R, T>(request)\n\n // mutates `response` to add warnings\n handlePartialPayment(req.command, response)\n\n return response\n }\n\n /**\n * Requests the next page of data.\n *\n * @category Network\n *\n * @param req - Request to send.\n * @param resp - Response with the marker to use in the request.\n * @returns The response with the next page of data.\n *\n * @example\n * ```ts\n * const response = await client.request({\n * command: 'account_tx',\n * account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',\n * })\n * console.log(response)\n * const nextResponse = await client.requestNextPage({\n * command: 'account_tx',\n * account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',\n * },\n * response)\n * console.log(nextResponse)\n * ```\n */\n public async requestNextPage<\n T extends RequestNextPageType,\n U extends RequestNextPageReturnMap<T>,\n >(req: T, resp: U): Promise<RequestNextPageReturnMap<T>> {\n if (!resp.result.marker) {\n return Promise.reject(\n new NotFoundError('response does not have a next page'),\n )\n }\n const nextPageRequest = { ...req, marker: resp.result.marker }\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Necessary for overloading\n return this.request(nextPageRequest) as unknown as U\n }\n\n /**\n * Event handler for subscription streams.\n *\n * @category Network\n *\n * @param eventName - Name of the event. Only forwards streams.\n * @param listener - Function to run on event.\n * @returns This, because it inherits from EventEmitter.\n *\n * * @example\n * ```ts\n * const api = new Client('wss://s.altnet.rippletest.net:51233')\n *\n * api.on('transaction', (tx: TransactionStream) => {\n * console.log(\"Received Transaction\")\n * console.log(tx)\n * })\n *\n * await api.connect()\n * const response = await api.request({\n * command: 'subscribe',\n * streams: ['transactions_proposed']\n * })\n * ```\n */\n public on<\n T extends EventTypes,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- needs to be any for overload\n U extends (...args: any[]) => void = OnEventToListenerMap<T>,\n >(eventName: T, listener: U): this {\n return super.on(eventName, listener)\n }\n\n /**\n * Makes multiple paged requests to the client to return a given number of\n * resources. Multiple paged requests will be made until the `limit`\n * number of resources is reached (if no `limit` is provided, a single request\n * will be made).\n *\n * If the command is unknown, an additional `collect` property is required to\n * know which response key contains the array of resources.\n *\n * NOTE: This command is used by existing methods and is not recommended for\n * general use. Instead, use rippled's built-in pagination and make multiple\n * requests as needed.\n *\n * @category Network\n *\n * @param request - The initial request to send to the server.\n * @param collect - (Optional) the param to use to collect the array of resources (only needed if command is unknown).\n * @returns The array of all responses.\n * @throws ValidationError if there is no collection key (either from a known command or for the unknown command).\n *\n * @example\n * // Request all ledger data pages\n * const allResponses = await client.requestAll({ command: 'ledger_data' });\n * console.log(allResponses);\n *\n * @example\n * // Request all transaction data pages\n * const allResponses = await client.requestAll({ command: 'transaction_data' });\n * console.log(allResponses);\n */\n\n public async requestAll<\n T extends MarkerRequest,\n U = RequestAllResponseMap<T, APIVersion>,\n >(request: T, collect?: string): Promise<U[]> {\n /*\n * The data under collection is keyed based on the command. Fail if command\n * not recognized and collection key not provided.\n */\n const collectKey = collect ?? getCollectKeyFromCommand(request.command)\n if (!collectKey) {\n throw new ValidationError(`no collect key for command ${request.command}`)\n }\n /*\n * If limit is not provided, fetches all data over multiple requests.\n * NOTE: This may return much more than needed. Set limit when possible.\n */\n const countTo: number = request.limit == null ? Infinity : request.limit\n let count = 0\n let marker: unknown = request.marker\n const results: U[] = []\n do {\n const countRemaining = clamp(countTo - count, MIN_LIMIT, MAX_LIMIT)\n const repeatProps = {\n ...request,\n limit: countRemaining,\n marker,\n }\n // eslint-disable-next-line no-await-in-loop -- Necessary for this, it really has to wait\n const singleResponse = await this.connection.request(repeatProps)\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true\n const singleResult = (singleResponse as MarkerResponse<APIVersion>).result\n if (!(collectKey in singleResult)) {\n throw new XrplError(`${collectKey} not in result`)\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Should be true\n const collectedData = singleResult[collectKey]\n marker = singleResult.marker\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true\n results.push(singleResponse as U)\n // Make sure we handle when no data (not even an empty array) is returned.\n if (Array.isArray(collectedData)) {\n count += collectedData.length\n }\n } while (Boolean(marker) && count < countTo)\n return results\n }\n\n /**\n * Get networkID and buildVersion from server_info\n *\n * @returns void\n * @example\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.getServerInfo()\n * console.log(client.networkID)\n * console.log(client.buildVersion)\n * ```\n */\n public async getServerInfo(): Promise<void> {\n try {\n const response = await this.request({\n command: 'server_info',\n })\n this.networkID = response.result.info.network_id ?? undefined\n this.buildVersion = response.result.info.build_version\n } catch (error) {\n // eslint-disable-next-line no-console -- Print the error to console but allows client to be connected.\n console.error(error)\n }\n }\n\n /**\n * Tells the Client instance to connect to its rippled server.\n *\n * @example\n *\n * Client.connect() establishes a connection between a Client object and the server.\n *\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * // do something with the client\n * await client.disconnect()\n * ```\n * If you open a client connection, be sure to close it with `await client.disconnect()`\n * before exiting your application.\n * @returns A promise that resolves with a void value when a connection is established.\n * @category Network\n *\n * @example\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * // do something with the client\n * await client.disconnect()\n * ```\n */\n public async connect(): Promise<void> {\n return this.connection.connect().then(async () => {\n await this.getServerInfo()\n this.emit('connected')\n })\n }\n\n /**\n * Disconnects the XRPL client from the server and cancels all pending requests and subscriptions. Call when\n * you want to disconnect the client from the server, such as when you're finished using the client or when you\n * need to switch to a different server.\n *\n * @example\n *\n * To use the disconnect() method, you first need to create a new Client object and connect it to a server:\n *\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * // do something with the client\n * await client.disconnect()\n * ```\n *\n * @returns A promise that resolves with a void value when a connection is destroyed.\n * @category Network\n */\n public async disconnect(): Promise<void> {\n /*\n * backwards compatibility: connection.disconnect() can return a number, but\n * this method returns nothing. SO we await but don't return any result.\n */\n await this.connection.disconnect()\n }\n\n /**\n * Checks if the Client instance is connected to its rippled server.\n *\n * @returns Whether the client instance is connected.\n * @category Network\n * @example\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * console.log(client.isConnected())\n * // true\n * await client.disconnect()\n * console.log(client.isConnected())\n * // false\n * ```\n */\n public isConnected(): boolean {\n return this.connection.isConnected()\n }\n\n /**\n * Autofills fields in a transaction. This will set `Sequence`, `Fee`,\n * `lastLedgerSequence` according to the current state of the server this Client\n * is connected to. It also converts all X-Addresses to classic addresses and\n * flags interfaces into numbers.\n *\n * @category Core\n *\n * @example\n *\n * ```ts\n * const { Client } = require('xrpl')\n *\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n *\n * async function createAndAutofillTransaction() {\n * const transaction = {\n * TransactionType: 'Payment',\n * Account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',\n * Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',\n * Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)\n * }\n *\n * try {\n * const autofilledTransaction = await client.autofill(transaction)\n * console.log(autofilledTransaction)\n * } catch (error) {\n * console.error(`Failed to autofill transaction: ${error}`)\n * }\n * }\n *\n * createAndAutofillTransaction()\n * ```\n *\n * Autofill helps fill in fields which should be included in a transaction, but can be determined automatically\n * such as `LastLedgerSequence` and `Fee`. If you override one of the fields `autofill` changes, your explicit\n * values will be used instead. By default, this is done as part of `submit` and `submitAndWait` when you pass\n * in an unsigned transaction along with your wallet to be submitted.\n *\n * @template T\n * @param transaction - A {@link SubmittableTransaction} in JSON format\n * @param signersCount - The expected number of signers for this transaction.\n * Only used for multisigned transactions.\n * @returns The autofilled transaction.\n * @throws ValidationError If Amount and DeliverMax fields are not identical in a Payment Transaction\n */\n public async autofill<T extends SubmittableTransaction>(\n transaction: T,\n signersCount?: number,\n ): Promise<T> {\n const tx = { ...transaction }\n\n setValidAddresses(tx)\n tx.Flags = convertTxFlagsToNumber(tx)\n\n const promises: Array<Promise<void>> = []\n if (tx.NetworkID == null) {\n tx.NetworkID = txNeedsNetworkID(this) ? this.networkID : undefined\n }\n if (tx.Sequence == null) {\n promises.push(setNextValidSequenceNumber(this, tx))\n }\n if (tx.Fee == null) {\n promises.push(getTransactionFee(this, tx, signersCount))\n }\n if (tx.LastLedgerSequence == null) {\n promises.push(setLatestValidatedLedgerSequence(this, tx))\n }\n if (tx.TransactionType === 'AccountDelete') {\n promises.push(checkAccountDeleteBlockers(this, tx))\n }\n if (tx.TransactionType === 'Batch') {\n promises.push(autofillBatchTxn(this, tx))\n }\n if (tx.TransactionType === 'Payment' && tx.DeliverMax != null) {\n handleDeliverMax(tx)\n }\n\n return Promise.all(promises).then(() => tx)\n }\n\n /**\n * Simulates an unsigned transaction.\n * Steps performed on a transaction:\n * 1. Autofill.\n * 2. Sign & Encode.\n * 3. Submit.\n *\n * @category Core\n *\n * @param transaction - A transaction to autofill, sign & encode, and submit.\n * @param opts - (Optional) Options used to sign and submit a transaction.\n * @param opts.binary - If true, return the metadata in a binary encoding.\n *\n * @returns A promise that contains SimulateResponse.\n * @throws RippledError if the simulate request fails.\n */\n\n public async simulate<Binary extends boolean = false>(\n transaction: SubmittableTransaction | string,\n opts?: {\n // If true, return the binary-encoded representation of the results.\n binary?: Binary\n },\n ): Promise<\n Binary extends true ? SimulateBinaryResponse : SimulateJsonResponse\n > {\n // send request\n const binary = opts?.binary ?? false\n const request: SimulateRequest =\n typeof transaction === 'string'\n ? { command: 'simulate', tx_blob: transaction, binary }\n : { command: 'simulate', tx_json: transaction, binary }\n return this.request(request)\n }\n\n /**\n * Submits a signed/unsigned transaction.\n * Steps performed on a transaction:\n * 1. Autofill.\n * 2. Sign & Encode.\n * 3. Submit.\n *\n * @category Core\n *\n * @param transaction - A transaction to autofill, sign & encode, and submit.\n * @param opts - (Optional) Options used to sign and submit a transaction.\n * @param opts.autofill - If true, autofill a transaction.\n * @param opts.failHard - If true, and the transaction fails locally, do not retry or relay the transaction to other servers.\n * @param opts.wallet - A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.\n *\n * @returns A promise that contains SubmitResponse.\n * @throws RippledError if submit request fails.\n *\n * @example\n * ```ts\n * const { Client, Wallet } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * const wallet = Wallet.generate()\n * const transaction = {\n * TransactionType: 'Payment',\n * Account: wallet.classicAddress,\n * Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',\n * Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)\n * }\n * const submitResponse = await client.submit(transaction, { wallet })\n * console.log(submitResponse)\n * ```\n */\n public async submit(\n transaction: SubmittableTransaction | string,\n opts?: {\n // If true, autofill a transaction.\n autofill?: boolean\n // If true, and the transaction fails locally, do not retry or relay the transaction to other servers.\n failHard?: boolean\n // A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.\n wallet?: Wallet\n },\n ): Promise<SubmitResponse> {\n const signedTx = await getSignedTx(this, transaction, opts)\n return submitRequest(this, signedTx, opts?.failHard)\n }\n\n /**\n * Asynchronously submits a transaction and verifies that it has been included in a\n * validated ledger (or has errored/will not be included for some reason).\n * See [Reliable Transaction Submission](https://xrpl.org/reliable-transaction-submission.html).\n *\n * @category Core\n *\n * @example\n *\n * ```ts\n * const { Client, Wallet } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n *\n * async function submitTransaction() {\n * const senderWallet = client.fundWallet()\n * const recipientWallet = client.fundWallet()\n *\n * const transaction = {\n * TransactionType: 'Payment',\n * Account: senderWallet.address,\n * Destination: recipientWallet.address,\n * Amount: '10'\n * }\n *\n * try {\n * await client.submit(signedTransaction, { wallet: senderWallet })\n * console.log(result)\n * } catch (error) {\n * console.error(`Failed to submit transaction: ${error}`)\n * }\n * }\n *\n * submitTransaction()\n * ```\n *\n * In this example we submit a payment transaction between two newly created testnet accounts.\n *\n * Under the hood, `submit` will call `client.autofill` by default, and because we've passed in a `Wallet` it\n * Will also sign the transaction for us before submitting the signed transaction binary blob to the ledger.\n *\n * This is similar to `submit`, which does all of the above, but also waits to see if the transaction has been validated.\n * @param transaction - A transaction to autofill, sign & encode, and submit.\n * @param opts - (Optional) Options used to sign and submit a transaction.\n * @param opts.autofill - If true, autofill a transaction.\n * @param opts.failHard - If true, and the transaction fails locally, do not retry or relay the transaction to other servers.\n * @param opts.wallet - A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.\n * @throws Connection errors: If the `Client` object is unable to establish a connection to the specified WebSocket endpoint,\n * an error will be thrown.\n * @throws Transaction errors: If the submitted transaction is invalid or cannot be included in a validated ledger for any\n * reason, the promise returned by `submitAndWait()` will be rejected with an error. This could include issues with insufficient\n * balance, invalid transaction fields, or other issues specific to the transaction being submitted.\n * @throws Ledger errors: If the ledger being used to submit the transaction is undergoing maintenance or otherwise unavailable,\n * an error will be thrown.\n * @throws Timeout errors: If the transaction takes longer than the specified timeout period to be included in a validated\n * ledger, the promise returned by `submitAndWait()` will be rejected with an error.\n * @returns A promise that contains TxResponse, that will return when the transaction has been validated.\n */\n public async submitAndWait<\n T extends SubmittableTransaction = SubmittableTransaction,\n >(\n transaction: T | string,\n opts?: {\n // If true, autofill a transaction.\n autofill?: boolean\n // If true, and the transaction fails locally, do not retry or relay the transaction to other servers.\n failHard?: boolean\n // A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.\n wallet?: Wallet\n },\n ): Promise<TxResponse<T>> {\n const signedTx = await getSignedTx(this, transaction, opts)\n\n const lastLedger = getLastLedgerSequence(signedTx)\n if (lastLedger == null) {\n throw new ValidationError(\n 'Transaction must contain a LastLedgerSequence value for reliable submission.',\n )\n }\n\n const response = await submitRequest(this, signedTx, opts?.failHard)\n\n if (response.result.engine_result.startsWith('tem')) {\n throw new XrplError(\n `Transaction failed, ${response.result.engine_result}: ${response.result.engine_result_message}`,\n )\n }\n\n const txHash = hashes.hashSignedTx(signedTx)\n return waitForFinalTransactionOutcome(\n this,\n txHash,\n lastLedger,\n response.result.engine_result,\n )\n }\n\n /**\n * Deprecated: Use autofill instead, provided for users familiar with v1\n *\n * @param transaction - A {@link Transaction} in JSON format\n * @param signersCount - The expected number of signers for this transaction.\n * Only used for multisigned transactions.\n * @deprecated Use autofill instead, provided for users familiar with v1\n */\n public async prepareTransaction(\n transaction: SubmittableTransaction,\n signersCount?: number,\n ): ReturnType<Client['autofill']> {\n return this.autofill(transaction, signersCount)\n }\n\n /**\n * Retrieves the XRP balance of a given account address.\n *\n * @category Abstraction\n *\n * @example\n * ```ts\n * const client = new Client(wss://s.altnet.rippletest.net:51233)\n * await client.connect()\n * const balance = await client.getXrpBalance('rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn')\n * console.log(balance)\n * await client.disconnect()\n * /// '200'\n * ```\n *\n * @param address - The XRP address to retrieve the balance for.\n * @param [options] - Additional options for fetching the balance (optional).\n * @param [options.ledger_hash] - The hash of the ledger to retrieve the balance from (optional).\n * @param [options.ledger_index] - The index of the ledger to retrieve the balance from (optional).\n * @returns A promise that resolves with the XRP balance as a number.\n */\n public async getXrpBalance(\n address: string,\n options: {\n ledger_hash?: string\n ledger_index?: LedgerIndex\n } = {},\n ): Promise<number> {\n const xrpRequest: AccountInfoRequest = {\n command: 'account_info',\n account: address,\n ledger_index: options.ledger_index ?? 'validated',\n ledger_hash: options.ledger_hash,\n }\n const response = await this.request(xrpRequest)\n return dropsToXrp(response.result.account_data.Balance)\n }\n\n /**\n * Get XRP/non-XRP balances for an account.\n *\n * @category Abstraction\n *\n * @example\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n *\n * async function getAccountBalances(address) {\n * try {\n * const options = {\n * ledger_index: 'validated',\n * limit: 10\n * };\n *\n * const balances = await xrplClient.getBalances(address, options);\n *\n * console.log('Account Balances:');\n * balances.forEach((balance) => {\n * console.log(`Currency: ${balance.currency}`);\n * console.log(`Value: ${balance.value}`);\n * console.log(`Issuer: ${balance.issuer}`);\n * console.log('---');\n * });\n * } catch (error) {\n * console.error('Error retrieving account balances:', error);\n * }\n * }\n *\n * const address = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh';\n * await getAccountBalances(address);\n * await client.disconnect();\n * ```\n *\n * @param address - Address of the account to retrieve balances for.\n * @param options - Allows the client to specify a ledger_hash, ledger_index,\n * filter by peer, and/or limit number of balances.\n * @param options.ledger_index - Retrieve the account balances at a given\n * ledger_index.\n * @param options.ledger_hash - Retrieve the account balances at the ledger with\n * a given ledger_hash.\n * @param options.peer - Filter balances by peer.\n * @param options.limit - Limit number of balances to return.\n * @returns An array of XRP/non-XRP balances for the given account.\n */\n /* eslint-disable max-lines-per-function -- getBalances requires more lines to implement logic */\n public async getBalances(\n address: string,\n options: {\n ledger_hash?: string\n ledger_index?: LedgerIndex\n peer?: string\n limit?: number\n } = {},\n ): Promise<\n Array<{ value: string; currency: string; issuer?: string | undefined }>\n > {\n const balances: Balance[] = []\n\n // get XRP balance\n let xrpPromise: Promise<number> = Promise.resolve(0)\n if (!options.peer) {\n xrpPromise = this.getXrpBalance(address, {\n ledger_hash: options.ledger_hash,\n ledger_index: options.ledger_index,\n })\n }\n\n // get non-XRP balances\n const linesRequest: AccountLinesRequest = {\n command: 'account_lines',\n account: address,\n ledger_index: options.ledger_index ?? 'validated',\n ledger_hash: options.ledger_hash,\n peer: options.peer,\n limit: options.limit,\n }\n const linesPromise = this.requestAll(linesRequest)\n\n // combine results\n await Promise.all([xrpPromise, linesPromise]).then(\n ([xrpBalance, linesResponses]) => {\n const accountLinesBalance = linesResponses.flatMap((response) =>\n formatBalances(response.result.lines),\n )\n if (xrpBalance !== 0) {\n balances.push({ currency: 'XRP', value: xrpBalance.toString() })\n }\n balances.push(...accountLinesBalance)\n },\n )\n return balances.slice(0, options.limit)\n }\n /* eslint-enable max-lines-per-function */\n\n /**\n * Fetch orderbook (buy/sell orders) between two currency pairs. This checks both sides of the orderbook\n * by making two `order_book` requests (with the second reversing takerPays and takerGets). Returned offers are\n * not normalized in this function, so either currency could be takerGets or takerPays.\n *\n * @category Abstraction\n *\n * @param currency1 - Specification of one currency involved. (With a currency code and optionally an issuer)\n * @param currency2 - Specification of a second currency involved. (With a currency code and optionally an issuer)\n * @param options - Options allowing the client to specify ledger_index,\n * ledger_hash, filter by taker, and/or limit number of orders.\n * @param options.ledger_index - Retrieve the orderbook at a given ledger_index.\n * @param options.ledger_hash - Retrieve the orderbook at the ledger with a\n * given ledger_hash.\n * @param options.taker - Filter orders by taker.\n * @param options.limit - The limit passed into each book_offers request.\n * Can return more than this due to two calls being made. Defaults to 20.\n * @returns An object containing buy and sell objects.\n */\n\n public async getOrderbook(\n currency1: BookOfferCurrency,\n currency2: BookOfferCurrency,\n options: {\n limit?: number\n ledger_index?: LedgerIndex\n ledger_hash?: string | null\n taker?: string | null\n } = {},\n ): Promise<{\n buy: BookOffer[]\n sell: BookOffer[]\n }> {\n validateOrderbookOptions(options)\n\n const request = createBookOffersRequest(currency1, currency2, options)\n\n const directOfferResults = await requestAllOffers(this, request)\n const reverseOfferResults = await requestAllOffers(\n this,\n reverseRequest(request),\n )\n\n const directOffers = extractOffers(directOfferResults)\n const reverseOffers = extractOffers(reverseOfferResults)\n\n const orders = combineOrders(directOffers, reverseOffers)\n\n const { buy, sell } = separateBuySellOrders(orders)\n\n /*\n * Sort the orders\n * for both buys and sells, lowest quality is closest to mid-market\n * we sort the orders so that earlier orders are closer to mid-market\n */\n return {\n buy: sortAndLimitOffers(buy, options.limit),\n sell: sortAndLimitOffers(sell, options.limit),\n }\n }\n\n /**\n * Returns the index of the most recently validated ledger.\n *\n * @category Abstraction\n *\n * @returns The most recently validated ledger index.\n *\n * @example\n * ```ts\n * const { Client } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * const ledgerIndex = await client.getLedgerIndex()\n * console.log(ledgerIndex)\n * // 884039\n * ```\n */\n public async getLedgerIndex(): Promise<number> {\n const ledgerResponse = await this.request({\n command: 'ledger',\n ledger_index: 'validated',\n })\n return ledgerResponse.result.ledger_index\n }\n\n /**\n * The fundWallet() method is used to send an amount of XRP (usually 1000) to a new (randomly generated)\n * or existing XRP Ledger wallet.\n *\n * @category Faucet\n *\n * @example\n *\n * Example 1: Fund a randomly generated wallet\n * const { Client, Wallet } = require('xrpl')\n *\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n * await client.connect()\n * const { balance, wallet } = await client.fundWallet()\n *\n * Under the hood, this will use `Wallet.generate()` to create a new random wallet, then ask a testnet faucet\n * To send it XRP on ledger to make it a real account. If successful, this will return the new account balance in XRP\n * Along with the Wallet object to track the keys for that account. If you'd like, you can also re-fill an existing\n * Account by passing in a Wallet you already have.\n * ```ts\n * const api = new xrpl.Client(\"wss://s.altnet.rippletest.net:51233\")\n * await api.connect()\n * const { wallet, balance } = await api.fundWallet()\n * ```\n *\n * Example 2: Fund wallet using a custom faucet host and known wallet address\n *\n * `fundWallet` will try to infer the url of a faucet API from the network your client is connected to.\n * There are hardcoded default faucets for popular test networks like testnet and devnet.\n * However, if you're working with a newer or more obscure network, you may have to specify the faucetHost\n * And faucetPath so `fundWallet` can ask that faucet to fund your wallet.\n *\n * ```ts\n * const newWallet = Wallet.generate()\n * const { balance, wallet } = await client.fundWallet(newWallet, {\n * amount: '10',\n * faucetHost: 'https://custom-faucet.example.com',\n * faucetPath: '/accounts'\n * })\n * console.log(`Sent 10 XRP to wallet: ${address} from the given faucet. Resulting balance: ${balance} XRP`)\n * } catch (error) {\n * console.error(`Failed to fund wallet: ${error}`)\n * }\n * }\n * ```\n *\n * @param wallet - An existing XRPL Wallet to fund. If undefined or null, a new Wallet will be created.\n * @param options - See below.\n * @param options.faucetHost - A custom host for a faucet server. On devnet,\n * testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct server automatically. In other environments,\n * or if you would like to customize the faucet host in devnet or testnet,\n * you should provide the host using this option.\n * @param options.faucetPath - A custom path for a faucet server. On devnet,\n * testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct path automatically. In other environments,\n * or if you would like to customize the faucet path in devnet or testnet,\n * you should provide the path using this option.\n * Ex: client.fundWallet(null,{'faucet.altnet.rippletest.net', '/accounts'})\n * specifies a request to 'faucet.altnet.rippletest.net/accounts' to fund a new wallet.\n * @param options.amount - A custom amount to fund, if undefined or null, the default amount will be 1000.\n * @returns A Wallet on the Testnet or Devnet that contains some amount of XRP,\n * and that wallet's balance in XRP.\n * @throws When either Client isn't connected or unable to fund wallet address.\n */\n public async fundWallet(\n this: Client,\n wallet?: Wallet | null,\n options: FundingOptions = {},\n ): Promise<{\n wallet: Wallet\n balance: number\n }> {\n if (!this.isConnected()) {\n throw new RippledError('Client not connected, cannot call faucet')\n }\n const existingWallet = Boolean(wallet)\n\n // Generate a new Wallet if no existing Wallet is provided or its address is invalid to fund\n const walletToFund =\n wallet && isValidClassicAddress(wallet.classicAddress)\n ? wallet\n : Wallet.generate()\n\n // Create the POST request body\n const postBody: FaucetRequestBody = {\n destination: walletToFund.classicAddress,\n xrpAmount: options.amount,\n usageContext: options.usageContext,\n userAgent: 'xrpl.js',\n }\n\n let startingBalance = 0\n if (existingWallet) {\n try {\n startingBalance = Number(\n await this.getXrpBalance(walletToFund.classicAddress),\n )\n } catch {\n /* startingBalance remains what it was previously */\n }\n }\n\n return requestFunding(\n options,\n this,\n startingBalance,\n walletToFund,\n postBody,\n )\n }\n}\n\nexport { Client }\n","import {\n Account,\n BaseTransaction,\n isAccount,\n isString,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * The NFTokenBurn transaction is used to remove an NFToken object from the\n * NFTokenPage in which it is being held, effectively removing the token from\n * the ledger (\"burning\" it).\n *\n * If this operation succeeds, the corresponding NFToken is removed. If this\n * operation empties the NFTokenPage holding the NFToken or results in the\n * consolidation, thus removing an NFTokenPage, the owner’s reserve requirement\n * is reduced by one.\n */\nexport interface NFTokenBurn extends BaseTransaction {\n TransactionType: 'NFTokenBurn'\n /**\n * Indicates the AccountID that submitted this transaction. The account MUST\n * be either the present owner of the token or, if the lsfBurnable flag is set\n * in the NFToken, either the issuer account or an account authorized by the\n * issuer, i.e. MintAccount.\n */\n Account: Account\n /**\n * Identifies the NFToken object to be removed by the transaction.\n */\n NFTokenID: string\n /**\n * Indicates which account currently owns the token if it is different than\n * Account. Only used to burn tokens which have the lsfBurnable flag enabled\n * and are not owned by the signing account.\n */\n Owner?: Account\n}\n\n/**\n * Verify the form and type of an NFTokenBurn at runtime.\n *\n * @param tx - An NFTokenBurn Transaction.\n * @throws When the NFTokenBurn is Malformed.\n */\nexport function validateNFTokenBurn(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n validateRequiredField(tx, 'NFTokenID', isString)\n validateOptionalField(tx, 'Owner', isAccount)\n}\n","import { Amount } from '../common'\n\nimport { BaseLedgerEntry, HasPreviousTxnID } from './BaseLedgerEntry'\n\nexport default interface Offer extends BaseLedgerEntry, HasPreviousTxnID {\n LedgerEntryType: 'Offer'\n /** A bit-map of boolean flags enabled for this Offer. */\n Flags: number\n /** The address of the account that placed this Offer. */\n Account: string\n /**\n * The Sequence value of the OfferCreate transaction that created this Offer\n * object. Used in combination with the Account to identify this Offer.\n */\n Sequence: number\n /** The remaining amount and type of currency requested by the Offer creator. */\n TakerPays: Amount\n /**\n * The remaining amount and type of currency being provided by the Offer\n * creator.\n */\n TakerGets: Amount\n /** The ID of the Offer Directory that links to this Offer. */\n BookDirectory: string\n /**\n * A hint indicating which page of the Offer Directory links to this object,\n * in case the directory consists of multiple pages.\n */\n BookNode: string\n /**\n * A hint indicating which page of the Owner Directory links to this object,\n * in case the directory consists of multiple pages.\n */\n OwnerNode: string\n /** The time this Offer expires, in seconds since the Ripple Epoch. */\n Expiration?: number\n}\n\nexport enum OfferFlags {\n lsfPassive = 0x00010000,\n lsfSell = 0x00020000,\n}\n","import { HDKey } from '@scure/bip32'\nimport { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\nimport BigNumber from 'bignumber.js'\nimport {\n classicAddressToXAddress,\n isValidXAddress,\n xAddressToClassicAddress,\n encodeSeed,\n} from 'ripple-address-codec'\nimport {\n encodeForSigning,\n encodeForMultisigning,\n encode,\n} from 'ripple-binary-codec'\nimport {\n deriveAddress,\n deriveKeypair,\n generateSeed,\n sign,\n} from 'ripple-keypairs'\n\nimport ECDSA from '../ECDSA'\nimport { ValidationError } from '../errors'\nimport { Transaction, validate } from '../models/transactions'\nimport { GlobalFlags } from '../models/transactions/common'\nimport { hasFlag } from '../models/utils'\nimport { ensureClassicAddress } from '../sugar/utils'\nimport { omitBy } from '../utils/collections'\nimport { hashSignedTx } from '../utils/hashes/hashLedger'\n\nimport { rfc1751MnemonicToKey } from './rfc1751'\nimport { verifySignature } from './signer'\n\nconst DEFAULT_ALGORITHM: ECDSA = ECDSA.ed25519\nconst DEFAULT_DERIVATION_PATH = \"m/44'/144'/0'/0/0\"\n\ntype ValidHDKey = HDKey & {\n privateKey: Uint8Array\n publicKey: Uint8Array\n}\n\nfunction validateKey(node: HDKey): asserts node is ValidHDKey {\n if (!(node.privateKey instanceof Uint8Array)) {\n throw new ValidationError('Unable to derive privateKey from mnemonic input')\n }\n\n if (!(node.publicKey instanceof Uint8Array)) {\n throw new ValidationError('Unable to derive publicKey from mnemonic input')\n }\n}\n\n/**\n * A utility for deriving a wallet composed of a keypair (publicKey/privateKey).\n * A wallet can be derived from either a seed, mnemonic, or entropy (array of random numbers).\n * It provides functionality to sign/verify transactions offline.\n *\n * @example\n * ```typescript\n *\n * // Derive a wallet from a base58 encoded seed.\n * const seedWallet = Wallet.fromSeed('ssZkdwURFMBXenJPbrpE14b6noJSu')\n * console.log(seedWallet)\n * // Wallet {\n * // publicKey: '02FE9932A9C4AA2AC9F0ED0F2B89302DE7C2C95F91D782DA3CF06E64E1C1216449',\n * // privateKey: '00445D0A16DD05EFAF6D5AF45E6B8A6DE4170D93C0627021A0B8E705786CBCCFF7',\n * // classicAddress: 'rG88FVLjvYiQaGftSa1cKuE2qNx7aK5ivo',\n * // seed: 'ssZkdwURFMBXenJPbrpE14b6noJSu'\n * // }.\n *\n * // Sign a JSON Transaction\n * const signed = seedWallet.signTransaction({\n * TransactionType: 'Payment',\n * Account: 'rG88FVLjvYiQaGftSa1cKuE2qNx7aK5ivo'\n * ...........\n * }).\n *\n * console.log(signed)\n * // '1200007321......B01BE1DFF3'.\n * console.log(decode(signed))\n * // {\n * // TransactionType: 'Payment',\n * // SigningPubKey: '02FE9932A9C4AA2AC9F0ED0F2B89302DE7C2C95F91D782DA3CF06E64E1C1216449',\n * // TxnSignature: '3045022100AAD......5B631ABD21171B61B07D304',\n * // Account: 'rG88FVLjvYiQaGftSa1cKuE2qNx7aK5ivo'\n * // ...........\n * // }\n * ```\n *\n * @category Signing\n */\nexport class Wallet {\n public readonly publicKey: string\n public readonly privateKey: string\n public readonly classicAddress: string\n public readonly seed?: string\n\n /**\n * Creates a new Wallet.\n *\n * @param publicKey - The public key for the account.\n * @param privateKey - The private key used for signing transactions for the account.\n * @param opts - (Optional) Options to initialize a Wallet.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @param opts.seed - The seed used to derive the account keys.\n */\n public constructor(\n publicKey: string,\n privateKey: string,\n opts: {\n masterAddress?: string\n seed?: string\n } = {},\n ) {\n this.publicKey = publicKey\n this.privateKey = privateKey\n this.classicAddress = opts.masterAddress\n ? ensureClassicAddress(opts.masterAddress)\n : deriveAddress(publicKey)\n this.seed = opts.seed\n }\n\n /**\n * Alias for wallet.classicAddress.\n *\n * @returns The wallet's classic address.\n */\n public get address(): string {\n return this.classicAddress\n }\n\n /**\n * `generate()` creates a new random Wallet. In order to make this a valid account on ledger, you must\n * Send XRP to it. On test networks that can be done with \"faucets\" which send XRP to any account which asks\n * For it. You can call `client.fundWallet()` in order to generate credentials and fund the account on test networks.\n *\n * @example\n * ```ts\n * const { Wallet } = require('xrpl')\n * const wallet = Wallet.generate()\n * ```\n *\n * @param algorithm - The digital signature algorithm to generate an address for.\n * @returns A new Wallet derived from a generated seed.\n *\n * @throws ValidationError when signing algorithm isn't valid\n */\n public static generate(algorithm: ECDSA = DEFAULT_ALGORITHM): Wallet {\n if (!Object.values(ECDSA).includes(algorithm)) {\n throw new ValidationError('Invalid cryptographic signing algorithm')\n }\n const seed = generateSeed({ algorithm })\n return Wallet.fromSeed(seed, { algorithm })\n }\n\n /**\n * Derives a wallet from a seed.\n *\n * @param seed - A string used to generate a keypair (publicKey/privateKey) to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @returns A Wallet derived from a seed.\n */\n public static fromSeed(\n seed: string,\n opts: { masterAddress?: string; algorithm?: ECDSA } = {},\n ): Wallet {\n return Wallet.deriveWallet(seed, {\n algorithm: opts.algorithm,\n masterAddress: opts.masterAddress,\n })\n }\n\n /**\n * Derives a wallet from a secret (AKA a seed).\n *\n * @param secret - A string used to generate a keypair (publicKey/privateKey) to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @returns A Wallet derived from a secret (AKA a seed).\n */\n // eslint-disable-next-line @typescript-eslint/member-ordering -- Member is used as a function here\n public static fromSecret = Wallet.fromSeed\n\n /**\n * Derives a wallet from an entropy (array of random numbers).\n *\n * @param entropy - An array of random numbers to generate a seed used to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @returns A Wallet derived from an entropy.\n */\n public static fromEntropy(\n entropy: Uint8Array | number[],\n opts: { masterAddress?: string; algorithm?: ECDSA } = {},\n ): Wallet {\n const algorithm = opts.algorithm ?? DEFAULT_ALGORITHM\n const options = {\n entropy: Uint8Array.from(entropy),\n algorithm,\n }\n const seed = generateSeed(options)\n return Wallet.deriveWallet(seed, {\n algorithm,\n masterAddress: opts.masterAddress,\n })\n }\n\n /**\n * Derives a wallet from a bip39 or RFC1751 mnemonic (Defaults to bip39).\n *\n * @deprecated since version 2.6.1.\n * Will be deleted in version 3.0.0.\n * This representation is currently deprecated in rippled.\n * You should use another method to represent your keys such as a seed or public/private keypair.\n *\n * @param mnemonic - A string consisting of words (whitespace delimited) used to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @param opts.derivationPath - The path to derive a keypair (publicKey/privateKey). Only used for bip39 conversions.\n * @param opts.mnemonicEncoding - If set to 'rfc1751', this interprets the mnemonic as a rippled RFC1751 mnemonic like\n * `wallet_propose` generates in rippled. Otherwise the function defaults to bip39 decoding.\n * @param opts.algorithm - Only used if opts.mnemonicEncoding is 'rfc1751'. Allows the mnemonic to generate its\n * secp256k1 seed, or its ed25519 seed. By default, it will generate the secp256k1 seed\n * to match the rippled `wallet_propose` default algorithm.\n * @returns A Wallet derived from a mnemonic.\n * @throws ValidationError if unable to derive private key from mnemonic input.\n */\n public static fromMnemonic(\n mnemonic: string,\n opts: {\n masterAddress?: string\n derivationPath?: string\n mnemonicEncoding?: 'bip39' | 'rfc1751'\n algorithm?: ECDSA\n } = {},\n ): Wallet {\n if (opts.mnemonicEncoding === 'rfc1751') {\n return Wallet.fromRFC1751Mnemonic(mnemonic, {\n masterAddress: opts.masterAddress,\n algorithm: opts.algorithm,\n })\n }\n // Otherwise decode using bip39's mnemonic standard\n if (!validateMnemonic(mnemonic, wordlist)) {\n throw new ValidationError(\n 'Unable to parse the given mnemonic using bip39 encoding',\n )\n }\n\n const seed = mnemonicToSeedSync(mnemonic)\n const masterNode = HDKey.fromMasterSeed(seed)\n const node = masterNode.derive(\n opts.derivationPath ?? DEFAULT_DERIVATION_PATH,\n )\n validateKey(node)\n\n const publicKey = bytesToHex(node.publicKey)\n const privateKey = bytesToHex(node.privateKey)\n return new Wallet(publicKey, `00${privateKey}`, {\n masterAddress: opts.masterAddress,\n })\n }\n\n /**\n * Derives a wallet from a RFC1751 mnemonic, which is how `wallet_propose` encodes mnemonics.\n *\n * @param mnemonic - A string consisting of words (whitespace delimited) used to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @returns A Wallet derived from a mnemonic.\n */\n private static fromRFC1751Mnemonic(\n mnemonic: string,\n opts: { masterAddress?: string; algorithm?: ECDSA },\n ): Wallet {\n const seed = rfc1751MnemonicToKey(mnemonic)\n let encodeAlgorithm: 'ed25519' | 'secp256k1'\n if (opts.algorithm === ECDSA.ed25519) {\n encodeAlgorithm = 'ed25519'\n } else {\n // Defaults to secp256k1 since that's the default for `wallet_propose`\n encodeAlgorithm = 'secp256k1'\n }\n const encodedSeed = encodeSeed(seed, encodeAlgorithm)\n return Wallet.fromSeed(encodedSeed, {\n masterAddress: opts.masterAddress,\n algorithm: opts.algorithm,\n })\n }\n\n /**\n * Derive a Wallet from a seed.\n *\n * @param seed - The seed used to derive the wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @returns A Wallet derived from the seed.\n */\n private static deriveWallet(\n seed: string,\n opts: { masterAddress?: string; algorithm?: ECDSA } = {},\n ): Wallet {\n const { publicKey, privateKey } = deriveKeypair(seed, {\n algorithm: opts.algorithm ?? DEFAULT_ALGORITHM,\n })\n return new Wallet(publicKey, privateKey, {\n seed,\n masterAddress: opts.masterAddress,\n })\n }\n\n /**\n * Signs a transaction offline.\n *\n * @example\n *\n * ```ts\n * const { Client, Wallet } = require('xrpl')\n * const client = new Client('wss://s.altnet.rippletest.net:51233')\n *\n * async function signTransaction() {\n * await client.connect()\n * const { balance: balance1, wallet: wallet1 } = client.fundWallet()\n * const { balance: balance2, wallet: wallet2 } = client.fundWallet()\n *\n * const transaction = {\n * TransactionType: 'Payment',\n * Account: wallet1.address,\n * Destination: wallet2.address,\n * Amount: '10'\n * }\n *\n * try {\n * await client.autofill(transaction)\n * const { tx_blob: signed_tx_blob, hash} = await wallet1.sign(transaction)\n * console.log(signed_tx_blob)\n * } catch (error) {\n * console.error(`Failed to sign transaction: ${error}`)\n * }\n * const result = await client.submit(signed_tx_blob)\n * await client.disconnect()\n * }\n *\n * signTransaction()\n * ```\n * In order for a transaction to be validated, it must be signed by the account sending the transaction to prove\n * That the owner is actually the one deciding to take that action.\n *\n * In this example, we created, signed, and then submitted a transaction to testnet. You may notice that the\n * Output of `sign` includes a `tx_blob` and a `hash`, both of which are needed to submit & verify the results.\n * Note: If you pass a `Wallet` to `client.submit` or `client.submitAndWait` it will do signing like this under the hood.\n *\n * `tx_blob` is a binary representation of a transaction on the XRP Ledger. It's essentially a byte array\n * that encodes all of the data necessary to execute the transaction, including the source address, the destination\n * address, the amount, and any additional fields required for the specific transaction type.\n *\n * `hash` is a unique identifier that's generated from the signed transaction data on the XRP Ledger. It's essentially\n * A cryptographic digest of the signed transaction blob, created using a hash function. The signed transaction hash is\n * Useful for identifying and tracking specific transactions on the XRP Ledger. It can be used to query transaction\n * Information, verify the authenticity of a transaction, and detect any tampering with the transaction data.\n *\n * @param this - Wallet instance.\n * @param transaction - A transaction to be signed offline.\n * @param multisign - Specify true/false to use multisign or actual address (classic/x-address) to make multisign tx request.\n * The actual address is only needed in the case of regular key usage.\n * @returns A signed transaction.\n * @throws ValidationError if the transaction is already signed or does not encode/decode to same result.\n * @throws XrplError if the issued currency being signed is XRP ignoring case.\n */\n // eslint-disable-next-line max-lines-per-function -- introduced more checks to support both string and boolean inputs.\n public sign(\n this: Wallet,\n transaction: Transaction,\n multisign?: boolean | string,\n ): {\n tx_blob: string\n hash: string\n } {\n let multisignAddress: boolean | string = false\n if (typeof multisign === 'string') {\n multisignAddress = multisign\n } else if (multisign) {\n multisignAddress = this.classicAddress\n }\n\n // clean null & undefined valued tx properties\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- ensure Transaction flows through\n const tx = omitBy(\n { ...transaction },\n (value) => value == null,\n ) as unknown as Transaction\n\n if (tx.TxnSignature || tx.Signers) {\n throw new ValidationError(\n 'txJSON must not contain \"TxnSignature\" or \"Signers\" properties',\n )\n }\n\n removeTrailingZeros(tx)\n\n /*\n * This will throw a more clear error for JS users if the supplied transaction has incorrect formatting\n */\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- validate does not accept Transaction type\n validate(tx as unknown as Record<string, unknown>)\n if (hasFlag(tx, GlobalFlags.tfInnerBatchTxn, 'tfInnerBatchTxn')) {\n throw new ValidationError('Cannot sign a Batch inner transaction.')\n }\n\n const txToSignAndEncode = { ...tx }\n\n if (multisignAddress) {\n txToSignAndEncode.SigningPubKey = ''\n const signer = {\n Account: multisignAddress,\n SigningPubKey: this.publicKey,\n TxnSignature: computeSignature(\n txToSignAndEncode,\n this.privateKey,\n multisignAddress,\n ),\n }\n txToSignAndEncode.Signers = [{ Signer: signer }]\n } else {\n txToSignAndEncode.SigningPubKey = this.publicKey\n txToSignAndEncode.TxnSignature = computeSignature(\n txToSignAndEncode,\n this.privateKey,\n )\n }\n\n const serialized = encode(txToSignAndEncode)\n return {\n tx_blob: serialized,\n hash: hashSignedTx(serialized),\n }\n }\n\n /**\n * Verifies a signed transaction offline.\n *\n * @param signedTransaction - A signed transaction (hex string of signTransaction result) to be verified offline.\n * @returns Returns true if a signedTransaction is valid.\n * @throws {Error} Transaction is missing a signature, TxnSignature\n */\n public verifyTransaction(signedTransaction: Transaction | string): boolean {\n return verifySignature(signedTransaction, this.publicKey)\n }\n\n /**\n * Gets an X-address in Testnet/Mainnet format.\n *\n * @param tag - A tag to be included within the X-address.\n * @param isTestnet - A boolean to indicate if X-address should be in Testnet (true) or Mainnet (false) format.\n * @returns An X-address.\n */\n public getXAddress(tag: number | false = false, isTestnet = false): string {\n return classicAddressToXAddress(this.classicAddress, tag, isTestnet)\n }\n}\n\n/**\n * Signs a transaction with the proper signing encoding.\n *\n * @param tx - A transaction to sign.\n * @param privateKey - A key to sign the transaction with.\n * @param signAs - Multisign only. An account address to include in the Signer field.\n * Can be either a classic address or an XAddress.\n * @returns A signed transaction in the proper format.\n */\nfunction computeSignature(\n tx: Transaction,\n privateKey: string,\n signAs?: string,\n): string {\n if (signAs) {\n const classicAddress = isValidXAddress(signAs)\n ? xAddressToClassicAddress(signAs).classicAddress\n : signAs\n\n return sign(encodeForMultisigning(tx, classicAddress), privateKey)\n }\n return sign(encodeForSigning(tx), privateKey)\n}\n\n/**\n * Remove trailing insignificant zeros for non-XRP Payment amount.\n * This resolves the serialization mismatch bug when encoding/decoding a non-XRP Payment transaction\n * with an amount that contains trailing insignificant zeros; for example, '123.4000' would serialize\n * to '123.4' and cause a mismatch.\n *\n * @param tx - The transaction prior to signing.\n */\nfunction removeTrailingZeros(tx: Transaction): void {\n if (\n tx.TransactionType === 'Payment' &&\n typeof tx.Amount !== 'string' &&\n tx.Amount.value.includes('.') &&\n tx.Amount.value.endsWith('0')\n ) {\n // eslint-disable-next-line no-param-reassign -- Required to update Transaction.Amount.value\n tx.Amount = { ...tx.Amount }\n // eslint-disable-next-line no-param-reassign -- Required to update Transaction.Amount.value\n tx.Amount.value = new BigNumber(tx.Amount.value).toString()\n }\n}\n","/* eslint-disable @typescript-eslint/no-magic-numbers -- Doing hex string parsing. */\nimport { hexToBytes } from '@xrplf/isomorphic/utils'\nimport BigNumber from 'bignumber.js'\nimport { encodeAccountID } from 'ripple-address-codec'\n\nimport { XrplError } from '../errors'\n\n/**\n * An issuer may issue several NFTs with the same taxon; to ensure that NFTs are\n * spread across multiple pages we lightly mix the taxon up by using the sequence\n * (which is not under the issuer's direct control) as the seed for a simple linear\n * congruential generator.\n *\n * From the Hull-Dobell theorem we know that f(x)=(m*x+c) mod n will yield a\n * permutation of [0, n) when n is a power of 2 if m is congruent to 1 mod 4 and\n * c is odd. By doing a bitwise XOR with this permutation we can scramble/unscramble\n * the taxon.\n *\n * The XLS-20d proposal fixes m = 384160001 and c = 2459.\n * We then take the modulus of 2^32 which is 4294967296.\n *\n * @param taxon - The scrambled or unscrambled taxon (The XOR is both the encoding and decoding)\n * @param tokenSeq - The account sequence when the token was minted. Used as a psuedorandom seed.\n * @returns the opposite taxon. If the taxon was scrambled it becomes unscrambled, and vice versa.\n */\nfunction unscrambleTaxon(taxon: number, tokenSeq: number): number {\n /* eslint-disable no-bitwise -- XOR is part of the encode/decode scheme. */\n const seed = 384160001\n const increment = 2459\n const max = 4294967296\n\n const scramble = new BigNumber(seed)\n .multipliedBy(tokenSeq)\n .modulo(max)\n .plus(increment)\n .modulo(max)\n .toNumber()\n return (taxon ^ scramble) >>> 0\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Parses an NFTokenID into the information it is encoding.\n *\n * Example decoding:\n *\n * 000B 0539 C35B55AA096BA6D87A6E6C965A6534150DC56E5E 12C5D09E 0000000C\n * +--- +--- +--------------------------------------- +------- +-------\n * | | | | |\n * | | | | `---> Sequence: 12\n * | | | |\n * | | | `---> Scrambled Taxon: 314,953,886\n * | | | Unscrambled Taxon: 1337\n * | | |\n * | | `---> Issuer: rJoxBSzpXhPtAuqFmqxQtGKjA13jUJWthE\n * | |\n * | `---> TransferFee: 1337.0 bps or 13.37%\n * |\n * `---> Flags: 11 -> lsfBurnable, lsfOnlyXRP and lsfTransferable\n *\n * @param nftokenID - A hex string which identifies an NFToken on the ledger.\n * @throws XrplError when given an invalid nftokenID.\n * @returns a decoded nftokenID with all fields encoded within.\n */\nexport default function parseNFTokenID(nftokenID: string): {\n NFTokenID: string\n Flags: number\n TransferFee: number\n Issuer: string\n Taxon: number\n Sequence: number\n} {\n const expectedLength = 64\n if (nftokenID.length !== expectedLength) {\n throw new XrplError(`Attempting to parse a nftokenID with length ${nftokenID.length}\n , but expected a token with length ${expectedLength}`)\n }\n\n const scrambledTaxon = new BigNumber(\n nftokenID.substring(48, 56),\n 16,\n ).toNumber()\n const sequence = new BigNumber(nftokenID.substring(56, 64), 16).toNumber()\n\n const NFTokenIDData = {\n NFTokenID: nftokenID,\n Flags: new BigNumber(nftokenID.substring(0, 4), 16).toNumber(),\n TransferFee: new BigNumber(nftokenID.substring(4, 8), 16).toNumber(),\n Issuer: encodeAccountID(hexToBytes(nftokenID.substring(8, 48))),\n Taxon: unscrambleTaxon(scrambledTaxon, sequence),\n Sequence: sequence,\n }\n\n return NFTokenIDData\n}\n","import { BaseLedgerEntry, HasOptionalPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The unique id for the nUNL object https://xrpl.org/negativeunl.html#negativeunl-id-format\n */\nexport const NEGATIVE_UNL_ID =\n '2E8A59AA9D3B5B186B0B9E0F62E6C02587CA74A4D778938E957B6357D364B244'\n\n/**\n * The NegativeUNL object type contains the current status of the Negative UNL,\n * a list of trusted validators currently believed to be offline.\n *\n * @category Ledger Entries\n */\nexport default interface NegativeUNL\n extends BaseLedgerEntry,\n HasOptionalPreviousTxnID {\n LedgerEntryType: 'NegativeUNL'\n /**\n * A list of trusted validators that are currently disabled.\n */\n DisabledValidators?: Array<{\n FirstLedgerSequence: number\n PublicKey: string\n }>\n /**\n * The public key of a trusted validator that is scheduled to be disabled in\n * the next flag ledger.\n */\n ValidatorToDisable?: string\n /**\n * The public key of a trusted validator in the Negative UNL that is\n * scheduled to be re-enabled in the next flag ledger.\n */\n ValidatorToReEnable?: string\n}\n","/*\n * Original code based on \"backo\" - https://github.com/segmentio/backo\n * MIT License - Copyright 2014 Segment.io\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\ninterface ExponentialBackoffOptions {\n // The min backoff duration.\n min?: number\n // The max backoff duration.\n max?: number\n}\n\nconst DEFAULT_MIN = 100\nconst DEFAULT_MAX = 1000\n\n/**\n * A Back off strategy that increases exponentially. Useful with repeated\n * setTimeout calls over a network (where the destination may be down).\n */\nexport default class ExponentialBackoff {\n private readonly ms: number\n private readonly max: number\n private readonly factor: number = 2\n private numAttempts = 0\n\n /**\n * Constructs an ExponentialBackoff object.\n *\n * @param opts - The options for the object.\n */\n public constructor(opts: ExponentialBackoffOptions = {}) {\n this.ms = opts.min ?? DEFAULT_MIN\n this.max = opts.max ?? DEFAULT_MAX\n }\n\n /**\n * Number of attempts for backoff so far.\n *\n * @returns Number of attempts.\n */\n public get attempts(): number {\n return this.numAttempts\n }\n\n /**\n * Return the backoff duration.\n *\n * @returns The backoff duration in milliseconds.\n */\n public duration(): number {\n const ms = this.ms * this.factor ** this.numAttempts\n this.numAttempts += 1\n return Math.floor(Math.min(ms, this.max))\n }\n\n /**\n * Reset the number of attempts.\n */\n public reset(): void {\n this.numAttempts = 0\n }\n}\n","import {\n decodeNodePublic,\n decodeSeed,\n encodeAccountID,\n encodeSeed,\n} from 'ripple-address-codec'\nimport { ripemd160 } from '@xrplf/isomorphic/ripemd160'\nimport { sha256 } from '@xrplf/isomorphic/sha256'\nimport { hexToBytes, randomBytes } from '@xrplf/isomorphic/utils'\n\nimport { accountPublicFromPublicGenerator } from './signing-schemes/secp256k1/utils'\nimport Sha512 from './utils/Sha512'\nimport assert from './utils/assert'\nimport type { Algorithm, HexString, KeyPair, SigningScheme } from './types'\nimport {\n getAlgorithmFromPrivateKey,\n getAlgorithmFromPublicKey,\n} from './utils/getAlgorithmFromKey'\n\nimport secp256k1 from './signing-schemes/secp256k1'\nimport ed25519 from './signing-schemes/ed25519'\n\nfunction getSigningScheme(algorithm: Algorithm): SigningScheme {\n const schemes = { 'ecdsa-secp256k1': secp256k1, ed25519 }\n return schemes[algorithm]\n}\n\nfunction generateSeed(\n options: {\n entropy?: Uint8Array\n algorithm?: Algorithm\n } = {},\n): string {\n assert.ok(\n !options.entropy || options.entropy.length >= 16,\n 'entropy too short',\n )\n const entropy = options.entropy\n ? options.entropy.slice(0, 16)\n : randomBytes(16)\n const type = options.algorithm === 'ed25519' ? 'ed25519' : 'secp256k1'\n return encodeSeed(entropy, type)\n}\n\nfunction deriveKeypair(\n seed: string,\n options?: {\n algorithm?: Algorithm\n validator?: boolean\n accountIndex?: number\n },\n): KeyPair {\n const decoded = decodeSeed(seed)\n const proposedAlgorithm = options?.algorithm ?? decoded.type\n const algorithm =\n proposedAlgorithm === 'ed25519' ? 'ed25519' : 'ecdsa-secp256k1'\n const scheme = getSigningScheme(algorithm)\n const keypair = scheme.deriveKeypair(decoded.bytes, options)\n const messageToVerify = Sha512.half('This test message should verify.')\n const signature = scheme.sign(messageToVerify, keypair.privateKey)\n /* istanbul ignore if */\n if (!scheme.verify(messageToVerify, signature, keypair.publicKey)) {\n throw new Error('derived keypair did not generate verifiable signature')\n }\n return keypair\n}\n\nfunction sign(messageHex: HexString, privateKey: HexString): HexString {\n const algorithm = getAlgorithmFromPrivateKey(privateKey)\n return getSigningScheme(algorithm).sign(hexToBytes(messageHex), privateKey)\n}\n\nfunction verify(\n messageHex: HexString,\n signature: HexString,\n publicKey: HexString,\n): boolean {\n const algorithm = getAlgorithmFromPublicKey(publicKey)\n return getSigningScheme(algorithm).verify(\n hexToBytes(messageHex),\n signature,\n publicKey,\n )\n}\n\nfunction computePublicKeyHash(publicKeyBytes: Uint8Array): Uint8Array {\n return ripemd160(sha256(publicKeyBytes))\n}\n\nfunction deriveAddressFromBytes(publicKeyBytes: Uint8Array): string {\n return encodeAccountID(computePublicKeyHash(publicKeyBytes))\n}\n\nfunction deriveAddress(publicKey: string): string {\n return deriveAddressFromBytes(hexToBytes(publicKey))\n}\n\nfunction deriveNodeAddress(publicKey: string): string {\n const generatorBytes = decodeNodePublic(publicKey)\n const accountPublicBytes = accountPublicFromPublicGenerator(generatorBytes)\n return deriveAddressFromBytes(accountPublicBytes)\n}\n\nexport {\n generateSeed,\n deriveKeypair,\n sign,\n verify,\n deriveAddress,\n deriveNodeAddress,\n decodeSeed,\n}\n","import { UInt } from './uint'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { bytesToHex, concat, hexToBytes } from '@xrplf/isomorphic/utils'\nimport { readUInt32BE, writeUInt32BE } from '../utils'\nimport { DEFAULT_DEFINITIONS, XrplDefinitionsBase } from '../enums'\n\nconst HEX_REGEX = /^[a-fA-F0-9]{1,16}$/\nconst BASE10_REGEX = /^[0-9]{1,20}$/\nconst mask = BigInt(0x00000000ffffffff)\n\nfunction useBase10(fieldName: string): boolean {\n return (\n fieldName === 'MaximumAmount' ||\n fieldName === 'OutstandingAmount' ||\n fieldName === 'MPTAmount'\n )\n}\n\n/**\n * Derived UInt class for serializing/deserializing 64 bit UInt\n */\nclass UInt64 extends UInt {\n protected static readonly width: number = 64 / 8 // 8\n static readonly defaultUInt64: UInt64 = new UInt64(\n new Uint8Array(UInt64.width),\n )\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? UInt64.defaultUInt64.bytes)\n }\n\n static fromParser(parser: BinaryParser): UInt {\n return new UInt64(parser.read(UInt64.width))\n }\n\n /**\n * Construct a UInt64 object\n *\n * @param val A UInt64, hex-string, bigInt, or number\n * @returns A UInt64 object\n */\n static from<T extends UInt64 | string | bigint | number>(\n val: T,\n fieldName = '',\n ): UInt64 {\n if (val instanceof UInt64) {\n return val\n }\n\n let buf = new Uint8Array(UInt64.width)\n\n if (typeof val === 'number') {\n if (val < 0) {\n throw new Error('value must be an unsigned integer')\n }\n\n const number = BigInt(val)\n\n const intBuf = [new Uint8Array(4), new Uint8Array(4)]\n writeUInt32BE(intBuf[0], Number(number >> BigInt(32)), 0)\n writeUInt32BE(intBuf[1], Number(number & BigInt(mask)), 0)\n\n return new UInt64(concat(intBuf))\n }\n\n if (typeof val === 'string') {\n if (useBase10(fieldName)) {\n if (!BASE10_REGEX.test(val)) {\n throw new Error(`${fieldName} ${val} is not a valid base 10 string`)\n }\n val = BigInt(val).toString(16) as T\n }\n\n if (typeof val === 'string' && !HEX_REGEX.test(val)) {\n throw new Error(`${val} is not a valid hex-string`)\n }\n\n const strBuf = (val as string).padStart(16, '0')\n buf = hexToBytes(strBuf)\n return new UInt64(buf)\n }\n\n if (typeof val === 'bigint') {\n const intBuf = [new Uint8Array(4), new Uint8Array(4)]\n writeUInt32BE(intBuf[0], Number(Number(val >> BigInt(32))), 0)\n writeUInt32BE(intBuf[1], Number(val & BigInt(mask)), 0)\n\n return new UInt64(concat(intBuf))\n }\n\n throw new Error('Cannot construct UInt64 from given value')\n }\n\n /**\n * The JSON representation of a UInt64 object\n *\n * @returns a hex-string\n */\n toJSON(\n _definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n fieldName = '',\n ): string {\n const hexString = bytesToHex(this.bytes)\n if (useBase10(fieldName)) {\n return BigInt('0x' + hexString).toString(10)\n }\n\n return hexString\n }\n\n /**\n * Get the value of the UInt64\n *\n * @returns the number represented buy this.bytes\n */\n valueOf(): bigint {\n const msb = BigInt(readUInt32BE(this.bytes.slice(0, 4), 0))\n const lsb = BigInt(readUInt32BE(this.bytes.slice(4), 0))\n return (msb << BigInt(32)) | lsb\n }\n\n /**\n * Get the bytes representation of the UInt64 object\n *\n * @returns 8 bytes representing the UInt64\n */\n toBytes(): Uint8Array {\n return this.bytes\n }\n}\n\nexport { UInt64 }\n","/**\n * Internal assertion helpers.\n * @module\n */\n\n/** Asserts something is positive integer. */\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Is number an Uint8Array? Copied from utils for perf. */\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Hash interface. */\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** Asserts something is hash */\nfunction ahash(h: Hash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nfunction aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nfunction aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\nexport { anumber, abytes, ahash, aexists, aoutput };\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Codec class\n */\n\nimport { base58xrp, BytesCoder } from '@scure/base'\nimport { sha256 } from '@xrplf/isomorphic/sha256'\n\nimport { arrayEqual, concatArgs, ByteArray } from './utils'\n\nclass Codec {\n private readonly _sha256: (bytes: ByteArray) => Uint8Array\n private readonly _codec: BytesCoder\n\n public constructor(options: { sha256: (bytes: ByteArray) => Uint8Array }) {\n this._sha256 = options.sha256\n this._codec = base58xrp\n }\n\n /**\n * Encoder.\n *\n * @param bytes - Uint8Array of data to encode.\n * @param opts - Options object including the version bytes and the expected length of the data to encode.\n */\n public encode(\n bytes: ByteArray,\n opts: {\n versions: number[]\n expectedLength: number\n },\n ): string {\n const versions = opts.versions\n return this._encodeVersioned(bytes, versions, opts.expectedLength)\n }\n\n /**\n * Decoder.\n *\n * @param base58string - Base58Check-encoded string to decode.\n * @param opts - Options object including the version byte(s) and the expected length of the data after decoding.\n */\n /* eslint-disable max-lines-per-function --\n * TODO refactor */\n public decode(\n base58string: string,\n opts: {\n versions: Array<number | number[]>\n expectedLength?: number\n versionTypes?: ['ed25519', 'secp256k1']\n },\n ): {\n version: number[]\n bytes: Uint8Array\n type: 'ed25519' | 'secp256k1' | null\n } {\n const versions = opts.versions\n const types = opts.versionTypes\n\n const withoutSum = this.decodeChecked(base58string)\n\n if (versions.length > 1 && !opts.expectedLength) {\n throw new Error(\n 'expectedLength is required because there are >= 2 possible versions',\n )\n }\n const versionLengthGuess =\n typeof versions[0] === 'number' ? 1 : versions[0].length\n const payloadLength =\n opts.expectedLength ?? withoutSum.length - versionLengthGuess\n const versionBytes = withoutSum.slice(0, -payloadLength)\n const payload = withoutSum.slice(-payloadLength)\n\n for (let i = 0; i < versions.length; i++) {\n /* eslint-disable @typescript-eslint/consistent-type-assertions --\n * TODO refactor */\n const version: number[] = Array.isArray(versions[i])\n ? (versions[i] as number[])\n : [versions[i] as number]\n if (arrayEqual(versionBytes, version)) {\n return {\n version,\n bytes: payload,\n type: types ? types[i] : null,\n }\n }\n /* eslint-enable @typescript-eslint/consistent-type-assertions */\n }\n\n throw new Error(\n 'version_invalid: version bytes do not match any of the provided version(s)',\n )\n }\n\n public encodeChecked(bytes: ByteArray): string {\n const check = this._sha256(this._sha256(bytes)).slice(0, 4)\n return this._encodeRaw(Uint8Array.from(concatArgs(bytes, check)))\n }\n\n public decodeChecked(base58string: string): Uint8Array {\n const intArray = this._decodeRaw(base58string)\n if (intArray.byteLength < 5) {\n throw new Error('invalid_input_size: decoded data must have length >= 5')\n }\n if (!this._verifyCheckSum(intArray)) {\n throw new Error('checksum_invalid')\n }\n return intArray.slice(0, -4)\n }\n\n private _encodeVersioned(\n bytes: ByteArray,\n versions: number[],\n expectedLength: number,\n ): string {\n if (!checkByteLength(bytes, expectedLength)) {\n throw new Error(\n 'unexpected_payload_length: bytes.length does not match expectedLength.' +\n ' Ensure that the bytes are a Uint8Array.',\n )\n }\n return this.encodeChecked(concatArgs(versions, bytes))\n }\n\n private _encodeRaw(bytes: ByteArray): string {\n return this._codec.encode(Uint8Array.from(bytes))\n }\n /* eslint-enable max-lines-per-function */\n\n private _decodeRaw(base58string: string): Uint8Array {\n return this._codec.decode(base58string)\n }\n\n private _verifyCheckSum(bytes: ByteArray): boolean {\n const computed = this._sha256(this._sha256(bytes.slice(0, -4))).slice(0, 4)\n const checksum = bytes.slice(-4)\n return arrayEqual(computed, checksum)\n }\n}\n\n/**\n * XRP codec\n */\n\n// base58 encodings: https://xrpl.org/base58-encodings.html\n// Account address (20 bytes)\nconst ACCOUNT_ID = 0\n// Account public key (33 bytes)\nconst ACCOUNT_PUBLIC_KEY = 0x23\n// 33; Seed value (for secret keys) (16 bytes)\nconst FAMILY_SEED = 0x21\n// 28; Validation public key (33 bytes)\nconst NODE_PUBLIC = 0x1c\n\n// [1, 225, 75]\nconst ED25519_SEED = [0x01, 0xe1, 0x4b]\n\nconst codecOptions = {\n sha256,\n}\n\nconst codecWithXrpAlphabet = new Codec(codecOptions)\n\nexport const codec = codecWithXrpAlphabet\n\n// entropy is a Uint8Array of size 16\n// type is 'ed25519' or 'secp256k1'\nexport function encodeSeed(\n entropy: ByteArray,\n type: 'ed25519' | 'secp256k1',\n): string {\n if (!checkByteLength(entropy, 16)) {\n throw new Error('entropy must have length 16')\n }\n const opts = {\n expectedLength: 16,\n\n // for secp256k1, use `FAMILY_SEED`\n versions: type === 'ed25519' ? ED25519_SEED : [FAMILY_SEED],\n }\n\n // prefixes entropy with version bytes\n return codecWithXrpAlphabet.encode(entropy, opts)\n}\n\nexport function decodeSeed(\n seed: string,\n opts: {\n versionTypes: ['ed25519', 'secp256k1']\n versions: Array<number | number[]>\n expectedLength: number\n } = {\n versionTypes: ['ed25519', 'secp256k1'],\n versions: [ED25519_SEED, FAMILY_SEED],\n expectedLength: 16,\n },\n): {\n version: number[]\n bytes: Uint8Array\n type: 'ed25519' | 'secp256k1' | null\n} {\n return codecWithXrpAlphabet.decode(seed, opts)\n}\n\nexport function encodeAccountID(bytes: ByteArray): string {\n const opts = { versions: [ACCOUNT_ID], expectedLength: 20 }\n return codecWithXrpAlphabet.encode(bytes, opts)\n}\n\n/* eslint-disable import/no-unused-modules ---\n * unclear why this is aliased but we should keep it in case someone else is\n * importing it with the aliased name */\nexport const encodeAddress = encodeAccountID\n/* eslint-enable import/no-unused-modules */\n\nexport function decodeAccountID(accountId: string): Uint8Array {\n const opts = { versions: [ACCOUNT_ID], expectedLength: 20 }\n return codecWithXrpAlphabet.decode(accountId, opts).bytes\n}\n\n/* eslint-disable import/no-unused-modules ---\n * unclear why this is aliased but we should keep it in case someone else is\n * importing it with the aliased name */\nexport const decodeAddress = decodeAccountID\n/* eslint-enable import/no-unused-modules */\n\nexport function decodeNodePublic(base58string: string): Uint8Array {\n const opts = { versions: [NODE_PUBLIC], expectedLength: 33 }\n return codecWithXrpAlphabet.decode(base58string, opts).bytes\n}\n\nexport function encodeNodePublic(bytes: ByteArray): string {\n const opts = { versions: [NODE_PUBLIC], expectedLength: 33 }\n return codecWithXrpAlphabet.encode(bytes, opts)\n}\n\nexport function encodeAccountPublic(bytes: ByteArray): string {\n const opts = { versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33 }\n return codecWithXrpAlphabet.encode(bytes, opts)\n}\n\nexport function decodeAccountPublic(base58string: string): Uint8Array {\n const opts = { versions: [ACCOUNT_PUBLIC_KEY], expectedLength: 33 }\n return codecWithXrpAlphabet.decode(base58string, opts).bytes\n}\n\nexport function isValidClassicAddress(address: string): boolean {\n try {\n decodeAccountID(address)\n } catch (_error) {\n return false\n }\n return true\n}\n\nfunction checkByteLength(bytes: ByteArray, expectedLength: number): boolean {\n return 'byteLength' in bytes\n ? bytes.byteLength === expectedLength\n : bytes.length === expectedLength\n}\n","// Even though this comes from NodeJS it is valid in the browser\nimport TypedArray = NodeJS.TypedArray\n\n/**\n * Writes value to array at the specified offset. The value must be a valid unsigned 8-bit integer.\n * @param array Uint8Array to be written to\n * @param value Number to be written to array.\n * @param offset plus the number of bytes written.\n */\nexport function writeUInt8(\n array: Uint8Array,\n value: number,\n offset: number,\n): void {\n value = Number(value)\n array[offset] = value\n}\n\n/**\n * Writes value to array at the specified offset as big-endian. The value must be a valid unsigned 16-bit integer.\n * @param array Uint8Array to be written to\n * @param value Number to be written to array.\n * @param offset plus the number of bytes written.\n */\nexport function writeUInt16BE(\n array: Uint8Array,\n value: number,\n offset: number,\n): void {\n value = Number(value)\n\n array[offset] = value >>> 8\n array[offset + 1] = value\n}\n\n/**\n * Writes value to array at the specified offset as big-endian. The value must be a valid unsigned 32-bit integer.\n * @param array Uint8Array to be written to\n * @param value Number to be written to array.\n * @param offset plus the number of bytes written.\n */\nexport function writeUInt32BE(\n array: Uint8Array,\n value: number,\n offset: number,\n): void {\n array[offset] = (value >>> 24) & 0xff\n array[offset + 1] = (value >>> 16) & 0xff\n array[offset + 2] = (value >>> 8) & 0xff\n array[offset + 3] = value & 0xff\n}\n\n/**\n * Writes a signed 32-bit integer to a Uint8Array at the specified offset (big-endian).\n *\n * @param array - The Uint8Array to write to.\n * @param value - The signed 32-bit integer to write.\n * @param offset - The offset at which to write.\n */\nexport function writeInt32BE(\n array: Uint8Array,\n value: number,\n offset: number,\n): void {\n new DataView(array.buffer, array.byteOffset, array.byteLength).setInt32(\n offset,\n value,\n false,\n )\n}\n\n/**\n * Writes a signed 64-bit integer (BigInt) to a Uint8Array at the specified offset (big-endian).\n *\n * @param array - The Uint8Array to write to.\n * @param value - The signed 64-bit integer (BigInt) to write.\n * @param offset - The offset at which to write.\n */\nexport function writeInt64BE(\n array: Uint8Array,\n value: bigint,\n offset: number,\n): void {\n new DataView(array.buffer, array.byteOffset, array.byteLength).setBigInt64(\n offset,\n value,\n false,\n )\n}\n\n/**\n * Reads an unsigned, big-endian 16-bit integer from the array at the specified offset.\n * @param array Uint8Array to read\n * @param offset Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2\n */\nexport function readUInt16BE(array: Uint8Array, offset: number): string {\n return new DataView(array.buffer).getUint16(offset, false).toString(10)\n}\n\n/**\n * Reads an unsigned, big-endian 16-bit integer from the array at the specified offset.\n * @param array Uint8Array to read\n * @param offset Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4\n */\nexport function readUInt32BE(array: Uint8Array, offset: number): string {\n return new DataView(array.buffer).getUint32(offset, false).toString(10)\n}\n\n/**\n * Reads a signed 32-bit integer from a Uint8Array at the specified offset (big-endian).\n *\n * @param array - The Uint8Array to read from.\n * @param offset - The offset at which to start reading.\n * @returns The signed 32-bit integer.\n */\nexport function readInt32BE(array: Uint8Array, offset: number): number {\n return new DataView(\n array.buffer,\n array.byteOffset,\n array.byteLength,\n ).getInt32(offset, false)\n}\n\n/**\n * Reads a signed 64-bit integer (BigInt) from a Uint8Array at the specified offset (big-endian).\n *\n * @param array - The Uint8Array to read from.\n * @param offset - The offset at which to start reading.\n * @returns The signed 64-bit integer (BigInt).\n */\nexport function readInt64BE(array: Uint8Array, offset: number): bigint {\n return new DataView(\n array.buffer,\n array.byteOffset,\n array.byteLength,\n ).getBigInt64(offset, false)\n}\n\n/**\n * Compares two Uint8Array or ArrayBuffers\n * @param a first array to compare\n * @param b second array to compare\n */\nexport function equal(\n a: Uint8Array | ArrayBuffer,\n b: Uint8Array | ArrayBuffer,\n): boolean {\n const aUInt = a instanceof ArrayBuffer ? new Uint8Array(a, 0) : a\n const bUInt = b instanceof ArrayBuffer ? new Uint8Array(b, 0) : b\n if (aUInt.byteLength != bUInt.byteLength) return false\n if (aligned32(aUInt) && aligned32(bUInt)) return compare32(aUInt, bUInt) === 0\n if (aligned16(aUInt) && aligned16(bUInt)) return compare16(aUInt, bUInt) === 0\n return compare8(aUInt, bUInt) === 0\n}\n\n/**\n * Compares two 8 bit aligned arrays\n * @param a first array to compare\n * @param b second array to compare\n */\nfunction compare8(a, b) {\n const ua = new Uint8Array(a.buffer, a.byteOffset, a.byteLength)\n const ub = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n return compare(ua, ub)\n}\n\n/**\n * Compares two 16 bit aligned arrays\n * @param a first array to compare\n * @param b second array to compare\n */\nfunction compare16(a: Uint8Array, b: Uint8Array) {\n const ua = new Uint16Array(a.buffer, a.byteOffset, a.byteLength / 2)\n const ub = new Uint16Array(b.buffer, b.byteOffset, b.byteLength / 2)\n return compare(ua, ub)\n}\n\n/**\n * Compares two 32 bit aligned arrays\n * @param a first array to compare\n * @param b second array to compare\n */\nfunction compare32(a: Uint8Array, b: Uint8Array) {\n const ua = new Uint32Array(a.buffer, a.byteOffset, a.byteLength / 4)\n const ub = new Uint32Array(b.buffer, b.byteOffset, b.byteLength / 4)\n return compare(ua, ub)\n}\n\n/**\n * Compare two TypedArrays\n * @param a first array to compare\n * @param b second array to compare\n */\nexport function compare(a: TypedArray, b: TypedArray): 1 | -1 | 0 {\n if (a.byteLength !== b.byteLength) {\n throw new Error('Cannot compare arrays of different length')\n }\n\n for (let i = 0; i < a.length - 1; i += 1) {\n if (a[i] > b[i]) return 1\n if (a[i] < b[i]) return -1\n }\n return 0\n}\n\n/**\n * Determine if TypedArray is 16 bit aligned\n * @param array The array to check\n */\nfunction aligned16(array: TypedArray) {\n return array.byteOffset % 2 === 0 && array.byteLength % 2 === 0\n}\n\n/**\n * Determine if TypedArray is 32 bit aligned\n * @param array The array to check\n */\nfunction aligned32(array: TypedArray) {\n return array.byteOffset % 4 === 0 && array.byteLength % 4 === 0\n}\n","import { ValidationError } from '../../errors'\nimport { Currency } from '../common'\nimport { hasFlag, isHex } from '../utils'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n GlobalFlagsInterface,\n validateOptionalField,\n isNumber,\n isCurrency,\n validateRequiredField,\n isString,\n VAULT_DATA_MAX_BYTE_LENGTH,\n XRPLNumber,\n isXRPLNumber,\n} from './common'\n\nconst META_MAX_BYTE_LENGTH = 1024\n\n/**\n * Enum representing withdrawal strategies for a Vault.\n */\nexport enum VaultWithdrawalPolicy {\n vaultStrategyFirstComeFirstServe = 0x0001,\n}\n\n/**\n * Enum representing values of {@link VaultCreate} transaction flags.\n *\n * @category Transaction Flags\n */\nexport enum VaultCreateFlags {\n tfVaultPrivate = 0x00010000,\n tfVaultShareNonTransferable = 0x00020000,\n}\n\n/**\n * Map of flags to boolean values representing {@link VaultCreate} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface VaultCreateFlagsInterface extends GlobalFlagsInterface {\n tfVaultPrivate?: boolean\n tfVaultShareNonTransferable?: boolean\n}\n\n/**\n * The VaultCreate transaction creates a new Vault object.\n *\n * @category Transaction Models\n */\nexport interface VaultCreate extends BaseTransaction {\n TransactionType: 'VaultCreate'\n\n /**\n * The asset (XRP, IOU or MPT) of the Vault.\n */\n Asset: Currency\n\n /**\n * Arbitrary Vault metadata, limited to 256 bytes.\n */\n Data?: string\n\n /**\n * The maximum asset amount that can be held in a vault.\n */\n AssetsMaximum?: XRPLNumber\n\n /**\n * Arbitrary metadata about the share MPT, in hex format, limited to 1024 bytes.\n */\n MPTokenMetadata?: string\n\n /**\n * Indicates the withdrawal strategy used by the Vault.\n */\n WithdrawalPolicy?: number\n\n /**\n * The PermissionedDomain object ID associated with the shares of this Vault.\n */\n DomainID?: string\n}\n\n/**\n * Verify the form and type of an {@link VaultCreate} at runtime.\n *\n * @param tx - A {@link VaultCreate} Transaction.\n * @throws When the {@link VaultCreate} is malformed.\n */\n// eslint-disable-next-line max-lines-per-function -- required to do all field validations\nexport function validateVaultCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Asset', isCurrency)\n validateOptionalField(tx, 'Data', isString)\n validateOptionalField(tx, 'AssetsMaximum', isXRPLNumber)\n validateOptionalField(tx, 'MPTokenMetadata', isString)\n validateOptionalField(tx, 'WithdrawalPolicy', isNumber)\n validateOptionalField(tx, 'DomainID', isString)\n\n if (tx.Data !== undefined) {\n const dataHex = tx.Data\n if (!isHex(dataHex)) {\n throw new ValidationError('VaultCreate: Data must be a valid hex string')\n }\n const dataByteLength = dataHex.length / 2\n if (dataByteLength > VAULT_DATA_MAX_BYTE_LENGTH) {\n throw new ValidationError(\n `VaultCreate: Data exceeds ${VAULT_DATA_MAX_BYTE_LENGTH} bytes (actual: ${dataByteLength})`,\n )\n }\n }\n\n if (tx.MPTokenMetadata !== undefined) {\n const metaHex = tx.MPTokenMetadata\n if (!isHex(metaHex)) {\n throw new ValidationError(\n 'VaultCreate: MPTokenMetadata must be a valid hex string',\n )\n }\n const metaByteLength = metaHex.length / 2\n if (metaByteLength > META_MAX_BYTE_LENGTH) {\n throw new ValidationError(\n `VaultCreate: MPTokenMetadata exceeds ${META_MAX_BYTE_LENGTH} bytes (actual: ${metaByteLength})`,\n )\n }\n }\n\n // If DomainID present, tfVaultPrivate must be set\n if (\n tx.DomainID !== undefined &&\n !hasFlag(tx, VaultCreateFlags.tfVaultPrivate, 'tfVaultPrivate')\n ) {\n throw new ValidationError(\n 'VaultCreate: Cannot set DomainID unless tfVaultPrivate flag is set.',\n )\n }\n}\n","import { quality, binary, HashPrefix } from './coretypes'\nimport { decodeLedgerData } from './ledger-hashes'\nimport { ClaimObject, BatchObject } from './binary'\nimport { JsonObject } from './types/serialized-type'\nimport {\n XrplDefinitionsBase,\n TRANSACTION_TYPES,\n DEFAULT_DEFINITIONS,\n} from './enums'\nimport { XrplDefinitions } from './enums/xrpl-definitions'\nimport { coreTypes } from './types'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\nconst {\n signingData,\n signingClaimData,\n multiSigningData,\n signingBatchData,\n binaryToJSON,\n serializeObject,\n} = binary\n\n/**\n * Decode a transaction\n *\n * @param binary hex-string of the encoded transaction\n * @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns the JSON representation of the transaction\n */\nfunction decode(binary: string, definitions?: XrplDefinitionsBase): JsonObject {\n if (typeof binary !== 'string') {\n throw new Error('binary must be a hex string')\n }\n return binaryToJSON(binary, definitions)\n}\n\n/**\n * Encode a transaction\n *\n * @param json The JSON representation of a transaction\n * @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n *\n * @returns A hex-string of the encoded transaction\n */\nfunction encode(json: object, definitions?: XrplDefinitionsBase): string {\n if (typeof json !== 'object') {\n throw new Error()\n }\n return bytesToHex(serializeObject(json as JsonObject, { definitions }))\n}\n\n/**\n * Encode a transaction and prepare for signing\n *\n * @param json JSON object representing the transaction\n * @param signer string representing the account to sign the transaction with\n * @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns a hex string of the encoded transaction\n */\nfunction encodeForSigning(\n json: object,\n definitions?: XrplDefinitionsBase,\n): string {\n if (typeof json !== 'object') {\n throw new Error()\n }\n return bytesToHex(\n signingData(json as JsonObject, HashPrefix.transactionSig, {\n definitions,\n }),\n )\n}\n\n/**\n * Encode a payment channel claim for signing.\n *\n * @param json JSON object representing the claim.\n * @returns a hex string of the encoded claim.\n */\nfunction encodeForSigningClaim(json: object): string {\n if (typeof json !== 'object') {\n throw new Error()\n }\n return bytesToHex(signingClaimData(json as ClaimObject))\n}\n\n/**\n * Encode a transaction and prepare for multi-signing.\n *\n * @param json JSON object representing the transaction.\n * @param signer string representing the account to sign the transaction with.\n * @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns a hex string of the encoded transaction.\n */\nfunction encodeForMultisigning(\n json: object,\n signer: string,\n definitions?: XrplDefinitionsBase,\n): string {\n if (typeof json !== 'object') {\n throw new Error()\n }\n if (json['SigningPubKey'] !== '') {\n throw new Error()\n }\n const definitionsOpt = definitions ? { definitions } : undefined\n return bytesToHex(\n multiSigningData(json as JsonObject, signer, definitionsOpt),\n )\n}\n\n/**\n * Encode a Batch transaction for signing.\n *\n * @param json JSON object representing the transaction.\n * @returns a hex string of the encoded transaction.\n */\nfunction encodeForSigningBatch(json: object): string {\n if (typeof json !== 'object') {\n throw new Error('Need an object to encode a Batch transaction')\n }\n return bytesToHex(signingBatchData(json as BatchObject))\n}\n\n/**\n * Encode a quality value\n *\n * @param value string representation of a number\n * @returns a hex-string representing the quality\n */\nfunction encodeQuality(value: string): string {\n if (typeof value !== 'string') {\n throw new Error()\n }\n return bytesToHex(quality.encode(value))\n}\n\n/**\n * Decode a quality value\n *\n * @param value hex-string of a quality\n * @returns a string representing the quality\n */\nfunction decodeQuality(value: string): string {\n if (typeof value !== 'string') {\n throw new Error()\n }\n return quality.decode(value).toString()\n}\n\nexport {\n decode,\n encode,\n encodeForSigning,\n encodeForSigningClaim,\n encodeForMultisigning,\n encodeForSigningBatch,\n encodeQuality,\n decodeQuality,\n decodeLedgerData,\n TRANSACTION_TYPES,\n XrplDefinitions,\n XrplDefinitionsBase,\n DEFAULT_DEFINITIONS,\n coreTypes,\n}\n","export { Client, ClientOptions } from './client'\n\nexport * from './models'\n\nexport * from './utils'\n\nexport { default as ECDSA } from './ECDSA'\n\nexport * from './errors'\n\nexport { FundingOptions } from './Wallet/fundWallet'\nexport { Wallet } from './Wallet'\n\nexport { walletFromSecretNumbers } from './Wallet/walletFromSecretNumbers'\n\nexport { keyToRFC1751Mnemonic, rfc1751MnemonicToKey } from './Wallet/rfc1751'\n\nexport * from './Wallet/signer'\n","import { XrplError } from '../../../errors'\nimport HashPrefix from '../HashPrefix'\nimport sha512Half from '../sha512Half'\n\nimport { NodeType, Node } from './node'\n\nconst HEX = 16\n\n/**\n * Class for SHAMap Leaf Node.\n */\nclass LeafNode extends Node {\n public tag: string\n public type: NodeType\n public data: string\n\n /**\n * Leaf node in a SHAMap tree.\n *\n * @param tag - Equates to a ledger entry `index`.\n * @param data - Hex of account state, transaction etc.\n * @param type - One of TYPE_ACCOUNT_STATE, TYPE_TRANSACTION_MD etc.\n */\n public constructor(tag: string, data: string, type: NodeType) {\n super()\n this.tag = tag\n this.type = type\n this.data = data\n }\n\n /**\n * Get the hash of a LeafNode.\n *\n * @returns Hash or undefined.\n * @throws If node is of unknown type.\n */\n public get hash(): string {\n switch (this.type) {\n case NodeType.ACCOUNT_STATE: {\n const leafPrefix = HashPrefix.LEAF_NODE.toString(HEX)\n return sha512Half(leafPrefix + this.data + this.tag)\n }\n case NodeType.TRANSACTION_NO_METADATA: {\n const txIDPrefix = HashPrefix.TRANSACTION_ID.toString(HEX)\n return sha512Half(txIDPrefix + this.data)\n }\n case NodeType.TRANSACTION_METADATA: {\n const txNodePrefix = HashPrefix.TRANSACTION_NODE.toString(HEX)\n return sha512Half(txNodePrefix + this.data + this.tag)\n }\n default:\n throw new XrplError('Tried to hash a SHAMap node of unknown type.')\n }\n }\n\n /**\n * Add item to Leaf.\n *\n * @param tag - Index of the Node.\n * @param node - Node to insert.\n * @throws When called, because LeafNodes cannot addItem.\n */\n public addItem(tag: string, node: Node): void {\n throw new XrplError('Cannot call addItem on a LeafNode')\n this.addItem(tag, node)\n }\n}\n\nexport default LeafNode\n","import {\n classicAddressToXAddress,\n decodeAccountID,\n decodeAccountPublic,\n decodeNodePublic,\n decodeSeed,\n decodeXAddress,\n encodeAccountID,\n encodeAccountPublic,\n encodeNodePublic,\n encodeSeed,\n encodeXAddress,\n isValidClassicAddress,\n isValidXAddress,\n xAddressToClassicAddress,\n} from 'ripple-address-codec'\nimport {\n encode as rbcEncode,\n decode as rbcDecode,\n encodeForMultisigning as rbcEncodeForMultisigning,\n encodeForSigning as rbcEncodeForSigning,\n encodeForSigningClaim as rbcEncodeForSigningClaim,\n} from 'ripple-binary-codec'\nimport { verify as verifyKeypairSignature } from 'ripple-keypairs'\n\nimport type { APIVersion } from '../models'\nimport { LedgerEntry } from '../models/ledger'\nimport { Response } from '../models/methods'\nimport { PaymentChannelClaim } from '../models/transactions/paymentChannelClaim'\nimport { Transaction } from '../models/transactions/transaction'\n\nimport { deriveKeypair, deriveAddress, deriveXAddress } from './derive'\nimport getBalanceChanges from './getBalanceChanges'\nimport getNFTokenID from './getNFTokenID'\nimport getXChainClaimID from './getXChainClaimID'\nimport {\n hashSignedTx,\n hashTx,\n hashAccountRoot,\n hashSignerListId,\n hashOfferId,\n hashTrustline,\n hashTxTree,\n hashStateTree,\n hashLedger,\n hashLedgerHeader,\n hashEscrow,\n hashPaymentChannel,\n} from './hashes'\nimport parseNFTokenID from './parseNFTokenID'\nimport {\n percentToTransferRate,\n decimalToTransferRate,\n transferRateToDecimal,\n percentToQuality,\n decimalToQuality,\n qualityToDecimal,\n} from './quality'\nimport signPaymentChannelClaim from './signPaymentChannelClaim'\nimport { convertHexToString, convertStringToHex } from './stringConversion'\nimport {\n rippleTimeToISOTime,\n isoTimeToRippleTime,\n rippleTimeToUnixTime,\n unixTimeToRippleTime,\n} from './timeConversion'\nimport verifyPaymentChannelClaim from './verifyPaymentChannelClaim'\nimport { xrpToDrops, dropsToXrp } from './xrpConversion'\n\n/**\n * Check if a secret is valid.\n *\n * @param secret - Secret to test for validity.\n * @returns True if secret can be derived into a keypair.\n * @category Utilities\n */\nfunction isValidSecret(secret: string): boolean {\n try {\n deriveKeypair(secret)\n return true\n } catch (_err) {\n return false\n }\n}\n\n/**\n * Encodes a LedgerEntry or Transaction into a hex string\n *\n * @param object - LedgerEntry or Transaction in JSON format.\n * @returns A hex string representing the encoded object.\n */\nfunction encode(object: Transaction | LedgerEntry): string {\n return rbcEncode(object)\n}\n\n/**\n * Encodes a Transaction for signing\n *\n * @param object - LedgerEntry in JSON or Transaction format.\n * @returns A hex string representing the encoded object.\n */\nfunction encodeForSigning(object: Transaction): string {\n return rbcEncodeForSigning(object)\n}\n\n/**\n * Encodes a PaymentChannelClaim for signing\n *\n * @param object - PaymentChannelClaim in JSON format.\n * @returns A hex string representing the encoded object.\n */\nfunction encodeForSigningClaim(object: PaymentChannelClaim): string {\n return rbcEncodeForSigningClaim(object)\n}\n\n/**\n * Encodes a Transaction for multi-signing\n *\n * @param object - Transaction in JSON format.\n * @param signer - The address of the account signing this transaction\n * @returns A hex string representing the encoded object.\n */\nfunction encodeForMultiSigning(object: Transaction, signer: string): string {\n return rbcEncodeForMultisigning(object, signer)\n}\n\n/**\n * Decodes a hex string into a transaction | ledger entry\n *\n * @param hex - hex string in the XRPL serialization format.\n * @returns The hex string decoded according to XRPL serialization format.\n */\nfunction decode(hex: string): Record<string, unknown> {\n return rbcDecode(hex)\n}\n\n/**\n * Validates that a given address is a valid X-Address or a valid classic\n * address.\n *\n * @param address - Address to validate.\n * @returns True if address is a valid X-Address or classic address.\n * @category Utilities\n */\nfunction isValidAddress(address: string): boolean {\n return isValidXAddress(address) || isValidClassicAddress(address)\n}\n\n/**\n * Returns true if there are more pages of data.\n *\n * When there are more results than contained in the response, the response\n * includes a `marker` field.\n *\n * See https://ripple.com/build/rippled-apis/#markers-and-pagination.\n *\n * @param response - Response to check for more pages on.\n * @returns Whether the response has more pages of data.\n * @category Utilities\n */\nfunction hasNextPage(response: Response<APIVersion>): boolean {\n // eslint-disable-next-line @typescript-eslint/dot-notation -- only checking if it exists\n return Boolean(response.result['marker'])\n}\n\n/**\n * @category Utilities\n */\nconst hashes = {\n hashSignedTx,\n hashTx,\n hashAccountRoot,\n hashSignerListId,\n hashOfferId,\n hashTrustline,\n hashTxTree,\n hashStateTree,\n hashLedger,\n hashLedgerHeader,\n hashEscrow,\n hashPaymentChannel,\n}\n\nexport {\n getBalanceChanges,\n dropsToXrp,\n xrpToDrops,\n hasNextPage,\n rippleTimeToISOTime,\n isoTimeToRippleTime,\n rippleTimeToUnixTime,\n unixTimeToRippleTime,\n percentToQuality,\n decimalToQuality,\n percentToTransferRate,\n decimalToTransferRate,\n transferRateToDecimal,\n qualityToDecimal,\n isValidSecret,\n isValidAddress,\n hashes,\n deriveKeypair,\n deriveAddress,\n deriveXAddress,\n signPaymentChannelClaim,\n verifyKeypairSignature,\n verifyPaymentChannelClaim,\n convertStringToHex,\n convertHexToString,\n classicAddressToXAddress,\n xAddressToClassicAddress,\n isValidXAddress,\n isValidClassicAddress,\n encodeSeed,\n decodeSeed,\n encodeAccountID,\n decodeAccountID,\n encodeNodePublic,\n decodeNodePublic,\n encodeAccountPublic,\n decodeAccountPublic,\n encodeXAddress,\n decodeXAddress,\n encode,\n decode,\n encodeForMultiSigning,\n encodeForSigning,\n encodeForSigningClaim,\n getNFTokenID,\n parseNFTokenID,\n getXChainClaimID,\n}\n","/**\n * Internal assertion helpers.\n * @module\n */\n\n/** Asserts something is positive integer. */\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Is number an Uint8Array? Copied from utils for perf. */\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Hash interface. */\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** Asserts something is hash */\nfunction ahash(h: Hash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nfunction aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nfunction aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\nexport { anumber, abytes, ahash, aexists, aoutput };\n","import { Amount } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateRequiredField,\n isString,\n isAmount,\n Account,\n validateOptionalField,\n isAccount,\n} from './common'\n\n/**\n * The VaultWithdraw transaction withdraws assets in exchange for the vault's shares.\n *\n * @category Transaction Models\n */\nexport interface VaultWithdraw extends BaseTransaction {\n TransactionType: 'VaultWithdraw'\n\n /**\n * The ID of the vault from which assets are withdrawn.\n */\n VaultID: string\n\n /**\n * The exact amount of Vault asset to withdraw.\n */\n Amount: Amount\n\n /**\n * An account to receive the assets. It must be able to receive the asset.\n */\n Destination?: Account\n}\n\n/**\n * Verify the form and type of a {@link VaultWithdraw} at runtime.\n *\n * @param tx - A {@link VaultWithdraw} Transaction.\n * @throws When the {@link VaultWithdraw} is malformed.\n */\nexport function validateVaultWithdraw(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'VaultID', isString)\n validateRequiredField(tx, 'Amount', isAmount)\n validateOptionalField(tx, 'Destination', isAccount)\n}\n","import { SerializedType } from './serialized-type'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { hexToBytes } from '@xrplf/isomorphic/utils'\n\n/**\n * Variable length encoded type\n */\nclass Blob extends SerializedType {\n constructor(bytes: Uint8Array) {\n super(bytes)\n }\n\n /**\n * Defines how to read a Blob from a BinaryParser\n *\n * @param parser The binary parser to read the Blob from\n * @param hint The length of the blob, computed by readVariableLengthLength() and passed in\n * @returns A Blob object\n */\n static fromParser(parser: BinaryParser, hint: number): Blob {\n return new Blob(parser.read(hint))\n }\n\n /**\n * Create a Blob object from a hex-string\n *\n * @param value existing Blob object or a hex-string\n * @returns A Blob object\n */\n static from<T extends Blob | string>(value: T): Blob {\n if (value instanceof Blob) {\n return value\n }\n\n if (typeof value === 'string') {\n if (!/^[A-F0-9]*$/iu.test(value)) {\n throw new Error('Cannot construct Blob from a non-hex string')\n }\n return new Blob(hexToBytes(value))\n }\n\n throw new Error('Cannot construct Blob from value given')\n }\n}\n\nexport { Blob }\n","import {\n decodeAccountID,\n encodeAccountID,\n isValidXAddress,\n xAddressToClassicAddress,\n} from 'ripple-address-codec'\nimport { Hash160 } from './hash-160'\nimport { hexToBytes } from '@xrplf/isomorphic/utils'\n\nconst HEX_REGEX = /^[A-F0-9]{40}$/\n\n/**\n * Class defining how to encode and decode an AccountID\n */\nclass AccountID extends Hash160 {\n static readonly defaultAccountID: AccountID = new AccountID(\n new Uint8Array(20),\n )\n\n constructor(bytes?: Uint8Array) {\n super(bytes ?? AccountID.defaultAccountID.bytes)\n }\n\n /**\n * Defines how to construct an AccountID\n *\n * @param value either an existing AccountID, a hex-string, or a base58 r-Address\n * @returns an AccountID object\n */\n static from<T extends Hash160 | string>(value: T): AccountID {\n if (value instanceof AccountID) {\n return value\n }\n\n if (typeof value === 'string') {\n if (value === '') {\n return new AccountID()\n }\n\n return HEX_REGEX.test(value)\n ? new AccountID(hexToBytes(value))\n : this.fromBase58(value)\n }\n\n throw new Error('Cannot construct AccountID from value given')\n }\n\n /**\n * Defines how to build an AccountID from a base58 r-Address\n *\n * @param value a base58 r-Address\n * @returns an AccountID object\n */\n static fromBase58(value: string): AccountID {\n if (isValidXAddress(value)) {\n const classic = xAddressToClassicAddress(value)\n\n if (classic.tag !== false)\n throw new Error('Only allowed to have tag on Account or Destination')\n\n value = classic.classicAddress\n }\n\n return new AccountID(Uint8Array.from(decodeAccountID(value)))\n }\n\n /**\n * Overload of toJSON\n *\n * @returns the base58 string for this AccountID\n */\n toJSON(): string {\n return this.toBase58()\n }\n\n /**\n * Defines how to encode AccountID into a base58 address\n *\n * @returns the base58 string defined by this.bytes\n */\n toBase58(): string {\n return encodeAccountID(this.bytes)\n }\n}\n\nexport { AccountID }\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n type AffinePoint,\n type BasicCurve,\n type Group,\n type GroupConstructor,\n pippenger,\n validateBasic,\n wNAF,\n} from './curve.js';\nimport { Field, mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { abool, ensureBytes, type FHash, type Hex, memoized } from './utils.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n/** Edwards curves must declare params a & d. */\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\nexport type CurveTypeWithLength = Readonly<CurveType & { nByteLength: number; nBitLength: number }>;\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType): CurveTypeWithLength {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n _setWindowSize(windowSize: number): void;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool('phflag', phflag);\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n\n function assertPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.is0() || n === _1n) return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point: ExtPointType = Point.BASE): ExtPointType {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\nimport { isFlagEnabled } from '../utils'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n validateBaseTransaction,\n isAmount,\n parseAmountValue,\n isAccount,\n validateOptionalField,\n Account,\n} from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n/**\n * Transaction Flags for an NFTokenCreateOffer Transaction.\n *\n * @category Transaction Flags\n */\nexport enum NFTokenCreateOfferFlags {\n /**\n * If set, indicates that the offer is a sell offer.\n * Otherwise, it is a buy offer.\n */\n tfSellNFToken = 0x00000001,\n}\n\n/**\n * Map of flags to boolean values representing {@link NFTokenCreateOffer} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface NFTokenCreateOfferFlagsInterface extends GlobalFlagsInterface {\n tfSellNFToken?: boolean\n}\n\n/**\n * The NFTokenCreateOffer transaction creates either an offer to buy an\n * NFT the submitting account does not own, or an offer to sell an NFT\n * the submitting account does own.\n */\nexport interface NFTokenCreateOffer extends BaseTransaction {\n TransactionType: 'NFTokenCreateOffer'\n /**\n * Identifies the NFTokenID of the NFToken object that the\n * offer references.\n */\n NFTokenID: string\n /**\n * Indicates the amount expected or offered for the Token.\n *\n * The amount must be non-zero, except when this is a sell\n * offer and the asset is XRP. This would indicate that the current\n * owner of the token is giving it away free, either to anyone at all,\n * or to the account identified by the Destination field.\n */\n Amount: Amount\n /**\n * Indicates the AccountID of the account that owns the\n * corresponding NFToken.\n *\n * If the offer is to buy a token, this field must be present\n * and it must be different than Account (since an offer to\n * buy a token one already holds is meaningless).\n *\n * If the offer is to sell a token, this field must not be\n * present, as the owner is, implicitly, the same as Account\n * (since an offer to sell a token one doesn't already hold\n * is meaningless).\n */\n Owner?: Account\n /**\n * Indicates the time after which the offer will no longer\n * be valid. The value is the number of seconds since the\n * Ripple Epoch.\n */\n Expiration?: number\n /**\n * If present, indicates that this offer may only be\n * accepted by the specified account. Attempts by other\n * accounts to accept this offer MUST fail.\n */\n Destination?: Account\n Flags?: number | NFTokenCreateOfferFlagsInterface\n}\n\nexport interface NFTokenCreateOfferMetadata extends TransactionMetadataBase {\n // rippled 1.11.0 or later\n offer_id?: string\n}\n\nfunction validateNFTokenSellOfferCases(tx: Record<string, unknown>): void {\n if (tx.Owner != null) {\n throw new ValidationError(\n 'NFTokenCreateOffer: Owner must not be present for sell offers',\n )\n }\n}\n\nfunction validateNFTokenBuyOfferCases(tx: Record<string, unknown>): void {\n if (tx.Owner == null) {\n throw new ValidationError(\n 'NFTokenCreateOffer: Owner must be present for buy offers',\n )\n }\n\n if (parseAmountValue(tx.Amount) <= 0) {\n throw new ValidationError(\n 'NFTokenCreateOffer: Amount must be greater than 0 for buy offers',\n )\n }\n}\n\n/**\n * Verify the form and type of an NFTokenCreateOffer at runtime.\n *\n * @param tx - An NFTokenCreateOffer Transaction.\n * @throws When the NFTokenCreateOffer is Malformed.\n */\nexport function validateNFTokenCreateOffer(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Account === tx.Owner) {\n throw new ValidationError(\n 'NFTokenCreateOffer: Owner and Account must not be equal',\n )\n }\n\n if (tx.Account === tx.Destination) {\n throw new ValidationError(\n 'NFTokenCreateOffer: Destination and Account must not be equal',\n )\n }\n\n validateOptionalField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'Owner', isAccount)\n\n if (tx.NFTokenID == null) {\n throw new ValidationError('NFTokenCreateOffer: missing field NFTokenID')\n }\n\n if (!isAmount(tx.Amount)) {\n throw new ValidationError('NFTokenCreateOffer: invalid Amount')\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- checked in BaseTransaction\n const flags = (tx.Flags ?? 0) as number | NFTokenCreateOfferFlagsInterface\n const isTfSellNFToken =\n typeof flags === 'number'\n ? isFlagEnabled(flags, NFTokenCreateOfferFlags.tfSellNFToken)\n : flags.tfSellNFToken ?? false\n\n if (isTfSellNFToken) {\n validateNFTokenSellOfferCases(tx)\n } else {\n validateNFTokenBuyOfferCases(tx)\n }\n}\n","/* eslint-disable max-lines -- need to work with a lot of transactions in a switch statement */\n/* eslint-disable max-lines-per-function -- need to work with a lot of Tx verifications */\n\nimport { ValidationError } from '../../errors'\nimport { convertTxFlagsToNumber } from '../utils/flags'\n\nimport { AccountDelete, validateAccountDelete } from './accountDelete'\nimport { AccountSet, validateAccountSet } from './accountSet'\nimport { AMMBid, validateAMMBid } from './AMMBid'\nimport { AMMClawback, validateAMMClawback } from './AMMClawback'\nimport { AMMCreate, validateAMMCreate } from './AMMCreate'\nimport { AMMDelete, validateAMMDelete } from './AMMDelete'\nimport { AMMDeposit, validateAMMDeposit } from './AMMDeposit'\nimport { AMMVote, validateAMMVote } from './AMMVote'\nimport { AMMWithdraw, validateAMMWithdraw } from './AMMWithdraw'\nimport { Batch, validateBatch } from './batch'\nimport { CheckCancel, validateCheckCancel } from './checkCancel'\nimport { CheckCash, validateCheckCash } from './checkCash'\nimport { CheckCreate, validateCheckCreate } from './checkCreate'\nimport { Clawback, validateClawback } from './clawback'\nimport {\n BaseTransaction,\n isIssuedCurrencyAmount,\n validateBaseTransaction,\n} from './common'\nimport { CredentialAccept, validateCredentialAccept } from './CredentialAccept'\nimport { CredentialCreate, validateCredentialCreate } from './CredentialCreate'\nimport { CredentialDelete, validateCredentialDelete } from './CredentialDelete'\nimport { DelegateSet, validateDelegateSet } from './delegateSet'\nimport { DepositPreauth, validateDepositPreauth } from './depositPreauth'\nimport { DIDDelete, validateDIDDelete } from './DIDDelete'\nimport { DIDSet, validateDIDSet } from './DIDSet'\nimport { EnableAmendment } from './enableAmendment'\nimport { EscrowCancel, validateEscrowCancel } from './escrowCancel'\nimport { EscrowCreate, validateEscrowCreate } from './escrowCreate'\nimport { EscrowFinish, validateEscrowFinish } from './escrowFinish'\nimport { TransactionMetadata } from './metadata'\nimport { MPTokenAuthorize, validateMPTokenAuthorize } from './MPTokenAuthorize'\nimport {\n MPTokenIssuanceCreate,\n validateMPTokenIssuanceCreate,\n} from './MPTokenIssuanceCreate'\nimport {\n MPTokenIssuanceDestroy,\n validateMPTokenIssuanceDestroy,\n} from './MPTokenIssuanceDestroy'\nimport {\n MPTokenIssuanceSet,\n validateMPTokenIssuanceSet,\n} from './MPTokenIssuanceSet'\nimport {\n NFTokenAcceptOffer,\n validateNFTokenAcceptOffer,\n} from './NFTokenAcceptOffer'\nimport { NFTokenBurn, validateNFTokenBurn } from './NFTokenBurn'\nimport {\n NFTokenCancelOffer,\n validateNFTokenCancelOffer,\n} from './NFTokenCancelOffer'\nimport {\n NFTokenCreateOffer,\n validateNFTokenCreateOffer,\n} from './NFTokenCreateOffer'\nimport { NFTokenMint, validateNFTokenMint } from './NFTokenMint'\nimport { NFTokenModify, validateNFTokenModify } from './NFTokenModify'\nimport { OfferCancel, validateOfferCancel } from './offerCancel'\nimport { OfferCreate, validateOfferCreate } from './offerCreate'\nimport { OracleDelete, validateOracleDelete } from './oracleDelete'\nimport { OracleSet, validateOracleSet } from './oracleSet'\nimport { Payment, validatePayment } from './payment'\nimport {\n PaymentChannelClaim,\n validatePaymentChannelClaim,\n} from './paymentChannelClaim'\nimport {\n PaymentChannelCreate,\n validatePaymentChannelCreate,\n} from './paymentChannelCreate'\nimport {\n PaymentChannelFund,\n validatePaymentChannelFund,\n} from './paymentChannelFund'\nimport {\n PermissionedDomainDelete,\n validatePermissionedDomainDelete,\n} from './permissionedDomainDelete'\nimport {\n PermissionedDomainSet,\n validatePermissionedDomainSet,\n} from './permissionedDomainSet'\nimport { SetFee } from './setFee'\nimport { SetRegularKey, validateSetRegularKey } from './setRegularKey'\nimport { SignerListSet, validateSignerListSet } from './signerListSet'\nimport { TicketCreate, validateTicketCreate } from './ticketCreate'\nimport { TrustSet, validateTrustSet } from './trustSet'\nimport { UNLModify } from './UNLModify'\nimport { VaultClawback, validateVaultClawback } from './vaultClawback'\nimport { VaultCreate, validateVaultCreate } from './vaultCreate'\nimport { VaultDelete, validateVaultDelete } from './vaultDelete'\nimport { VaultDeposit, validateVaultDeposit } from './vaultDeposit'\nimport { VaultSet, validateVaultSet } from './vaultSet'\nimport { VaultWithdraw, validateVaultWithdraw } from './vaultWithdraw'\nimport {\n XChainAccountCreateCommit,\n validateXChainAccountCreateCommit,\n} from './XChainAccountCreateCommit'\nimport {\n XChainAddAccountCreateAttestation,\n validateXChainAddAccountCreateAttestation,\n} from './XChainAddAccountCreateAttestation'\nimport {\n XChainAddClaimAttestation,\n validateXChainAddClaimAttestation,\n} from './XChainAddClaimAttestation'\nimport { XChainClaim, validateXChainClaim } from './XChainClaim'\nimport { XChainCommit, validateXChainCommit } from './XChainCommit'\nimport {\n XChainCreateBridge,\n validateXChainCreateBridge,\n} from './XChainCreateBridge'\nimport {\n XChainCreateClaimID,\n validateXChainCreateClaimID,\n} from './XChainCreateClaimID'\nimport {\n XChainModifyBridge,\n validateXChainModifyBridge,\n} from './XChainModifyBridge'\n\n/**\n * Transactions that can be submitted by clients\n *\n * @category Transaction Models\n */\nexport type SubmittableTransaction =\n | AMMBid\n | AMMClawback\n | AMMCreate\n | AMMDelete\n | AMMDeposit\n | AMMVote\n | AMMWithdraw\n | AccountDelete\n | AccountSet\n | Batch\n | CheckCancel\n | CheckCash\n | CheckCreate\n | Clawback\n | CredentialAccept\n | CredentialCreate\n | CredentialDelete\n | DIDDelete\n | DIDSet\n | DelegateSet\n | DepositPreauth\n | EscrowCancel\n | EscrowCreate\n | EscrowFinish\n | MPTokenAuthorize\n | MPTokenIssuanceCreate\n | MPTokenIssuanceDestroy\n | MPTokenIssuanceSet\n | NFTokenAcceptOffer\n | NFTokenBurn\n | NFTokenCancelOffer\n | NFTokenCreateOffer\n | NFTokenMint\n | NFTokenModify\n | OfferCancel\n | OfferCreate\n | OracleDelete\n | OracleSet\n | Payment\n | PaymentChannelClaim\n | PaymentChannelCreate\n | PaymentChannelFund\n | PermissionedDomainSet\n | PermissionedDomainDelete\n | SetRegularKey\n | SignerListSet\n | TicketCreate\n | TrustSet\n | VaultClawback\n | VaultCreate\n | VaultDelete\n | VaultDeposit\n | VaultSet\n | VaultWithdraw\n | XChainAccountCreateCommit\n | XChainAddAccountCreateAttestation\n | XChainAddClaimAttestation\n | XChainClaim\n | XChainCommit\n | XChainCreateBridge\n | XChainCreateClaimID\n | XChainModifyBridge\n\n/**\n * Transactions that can only be created by validators.\n *\n * @category Transaction Models\n */\nexport type PseudoTransaction = EnableAmendment | SetFee | UNLModify\n\n/**\n * All transactions that can live on the XRPL\n *\n * @category Transaction Models\n */\nexport type Transaction = SubmittableTransaction | PseudoTransaction\n\n/**\n * @category Transaction Models\n */\nexport interface TransactionAndMetadata<\n T extends BaseTransaction = Transaction,\n> {\n transaction: T\n metadata: TransactionMetadata<T>\n}\n\n/**\n * Verifies various Transaction Types.\n * Encode/decode and individual type validation.\n *\n * @param transaction - A Transaction.\n * @throws ValidationError When the Transaction is malformed.\n * @category Utilities\n */\nexport function validate(transaction: Record<string, unknown>): void {\n const tx = { ...transaction }\n\n // should already be done in the tx-specific validation, but doesn't hurt to check again\n validateBaseTransaction(tx)\n\n Object.keys(tx).forEach((key) => {\n const standard_currency_code_len = 3\n const value = tx[key]\n if (value && isIssuedCurrencyAmount(value)) {\n const txCurrency = value.currency\n\n if (\n txCurrency.length === standard_currency_code_len &&\n txCurrency.toUpperCase() === 'XRP'\n ) {\n throw new ValidationError(\n `Cannot have an issued currency with a similar standard code to XRP (received '${txCurrency}'). XRP is not an issued currency.`,\n )\n }\n }\n })\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- okay here\n tx.Flags = convertTxFlagsToNumber(tx as unknown as Transaction)\n switch (tx.TransactionType) {\n case 'AMMBid':\n validateAMMBid(tx)\n break\n\n case 'AMMClawback':\n validateAMMClawback(tx)\n break\n\n case 'AMMCreate':\n validateAMMCreate(tx)\n break\n\n case 'AMMDelete':\n validateAMMDelete(tx)\n break\n\n case 'AMMDeposit':\n validateAMMDeposit(tx)\n break\n\n case 'AMMVote':\n validateAMMVote(tx)\n break\n\n case 'AMMWithdraw':\n validateAMMWithdraw(tx)\n break\n\n case 'AccountDelete':\n validateAccountDelete(tx)\n break\n\n case 'AccountSet':\n validateAccountSet(tx)\n break\n\n case 'Batch':\n validateBatch(tx)\n // This is done here to avoid issues with dependency cycles\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- okay here\n // @ts-expect-error -- already checked\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call -- already checked above\n tx.RawTransactions.forEach((innerTx: Record<string, unknown>) => {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- already checked above\n validate(innerTx.RawTransaction as Record<string, unknown>)\n })\n break\n\n case 'CheckCancel':\n validateCheckCancel(tx)\n break\n\n case 'CheckCash':\n validateCheckCash(tx)\n break\n\n case 'CheckCreate':\n validateCheckCreate(tx)\n break\n\n case 'Clawback':\n validateClawback(tx)\n break\n\n case 'CredentialAccept':\n validateCredentialAccept(tx)\n break\n\n case 'CredentialCreate':\n validateCredentialCreate(tx)\n break\n\n case 'CredentialDelete':\n validateCredentialDelete(tx)\n break\n\n case 'DIDDelete':\n validateDIDDelete(tx)\n break\n\n case 'DIDSet':\n validateDIDSet(tx)\n break\n\n case 'DelegateSet':\n validateDelegateSet(tx)\n break\n\n case 'DepositPreauth':\n validateDepositPreauth(tx)\n break\n\n case 'EscrowCancel':\n validateEscrowCancel(tx)\n break\n\n case 'EscrowCreate':\n validateEscrowCreate(tx)\n break\n\n case 'EscrowFinish':\n validateEscrowFinish(tx)\n break\n\n case 'MPTokenAuthorize':\n validateMPTokenAuthorize(tx)\n break\n\n case 'MPTokenIssuanceCreate':\n validateMPTokenIssuanceCreate(tx)\n break\n\n case 'MPTokenIssuanceDestroy':\n validateMPTokenIssuanceDestroy(tx)\n break\n\n case 'MPTokenIssuanceSet':\n validateMPTokenIssuanceSet(tx)\n break\n\n case 'NFTokenAcceptOffer':\n validateNFTokenAcceptOffer(tx)\n break\n\n case 'NFTokenBurn':\n validateNFTokenBurn(tx)\n break\n\n case 'NFTokenCancelOffer':\n validateNFTokenCancelOffer(tx)\n break\n\n case 'NFTokenCreateOffer':\n validateNFTokenCreateOffer(tx)\n break\n\n case 'NFTokenMint':\n validateNFTokenMint(tx)\n break\n\n case 'NFTokenModify':\n validateNFTokenModify(tx)\n break\n\n case 'OfferCancel':\n validateOfferCancel(tx)\n break\n\n case 'OfferCreate':\n validateOfferCreate(tx)\n break\n\n case 'OracleDelete':\n validateOracleDelete(tx)\n break\n\n case 'OracleSet':\n validateOracleSet(tx)\n break\n\n case 'Payment':\n validatePayment(tx)\n break\n\n case 'PaymentChannelClaim':\n validatePaymentChannelClaim(tx)\n break\n\n case 'PaymentChannelCreate':\n validatePaymentChannelCreate(tx)\n break\n\n case 'PaymentChannelFund':\n validatePaymentChannelFund(tx)\n break\n\n case 'PermissionedDomainSet':\n validatePermissionedDomainSet(tx)\n break\n\n case 'PermissionedDomainDelete':\n validatePermissionedDomainDelete(tx)\n break\n\n case 'SetRegularKey':\n validateSetRegularKey(tx)\n break\n\n case 'SignerListSet':\n validateSignerListSet(tx)\n break\n\n case 'TicketCreate':\n validateTicketCreate(tx)\n break\n\n case 'TrustSet':\n validateTrustSet(tx)\n break\n\n case 'VaultClawback':\n validateVaultClawback(tx)\n break\n\n case 'VaultCreate':\n validateVaultCreate(tx)\n break\n\n case 'VaultDelete':\n validateVaultDelete(tx)\n break\n\n case 'VaultDeposit':\n validateVaultDeposit(tx)\n break\n\n case 'VaultSet':\n validateVaultSet(tx)\n break\n\n case 'VaultWithdraw':\n validateVaultWithdraw(tx)\n break\n\n case 'XChainAccountCreateCommit':\n validateXChainAccountCreateCommit(tx)\n break\n\n case 'XChainAddAccountCreateAttestation':\n validateXChainAddAccountCreateAttestation(tx)\n break\n\n case 'XChainAddClaimAttestation':\n validateXChainAddClaimAttestation(tx)\n break\n\n case 'XChainClaim':\n validateXChainClaim(tx)\n break\n\n case 'XChainCommit':\n validateXChainCommit(tx)\n break\n\n case 'XChainCreateBridge':\n validateXChainCreateBridge(tx)\n break\n\n case 'XChainCreateClaimID':\n validateXChainCreateClaimID(tx)\n break\n\n case 'XChainModifyBridge':\n validateXChainModifyBridge(tx)\n break\n\n default:\n throw new ValidationError(\n `Invalid field TransactionType: ${tx.TransactionType}`,\n )\n }\n}\n","import { ValidationError } from '../../errors'\nimport { ClawbackAmount } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n isIssuedCurrencyAmount,\n isMPTAmount,\n isAccount,\n validateOptionalField,\n isClawbackAmount,\n validateRequiredField,\n} from './common'\n\n/**\n * The Clawback transaction is used by the token issuer to claw back\n * issued tokens from a holder.\n */\nexport interface Clawback extends BaseTransaction {\n TransactionType: 'Clawback'\n /**\n * Indicates the AccountID that submitted this transaction. The account MUST\n * be the issuer of the currency or MPT.\n */\n Account: string\n /**\n * The amount of currency or MPT to clawback, and it must be non-XRP. The nested field\n * names MUST be lower-case. If the amount is IOU, the `issuer` field MUST be the holder's address,\n * whom to be clawed back.\n */\n Amount: ClawbackAmount\n /**\n * Indicates the AccountID that the issuer wants to clawback. This field is only valid for clawing back\n * MPTs.\n */\n Holder?: string\n}\n\n/**\n * Verify the form and type of an Clawback at runtime.\n *\n * @param tx - An Clawback Transaction.\n * @throws When the Clawback is Malformed.\n */\nexport function validateClawback(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n validateRequiredField(tx, 'Amount', isClawbackAmount)\n validateOptionalField(tx, 'Holder', isAccount)\n\n if (!isIssuedCurrencyAmount(tx.Amount) && !isMPTAmount(tx.Amount)) {\n throw new ValidationError('Clawback: invalid Amount')\n }\n\n if (isIssuedCurrencyAmount(tx.Amount) && tx.Account === tx.Amount.issuer) {\n throw new ValidationError('Clawback: invalid holder Account')\n }\n\n if (isMPTAmount(tx.Amount) && tx.Account === tx.Holder) {\n throw new ValidationError('Clawback: invalid holder Account')\n }\n\n if (isIssuedCurrencyAmount(tx.Amount) && tx.Holder) {\n throw new ValidationError('Clawback: cannot have Holder for currency')\n }\n\n if (isMPTAmount(tx.Amount) && !tx.Holder) {\n throw new ValidationError('Clawback: missing Holder')\n }\n}\n","import { Account } from '@xrplf/secret-numbers'\n\nimport ECDSA from '../ECDSA'\n\nimport { Wallet } from '.'\n\n/**\n * Derives a wallet from secret numbers.\n * NOTE: This uses a default encoding algorithm of secp256k1 to match the popular wallet\n * [Xumm (aka Xaman)](https://xumm.app/)'s behavior.\n * This may be different from the DEFAULT_ALGORITHM for other ways to generate a Wallet.\n *\n * @param secretNumbers - A string consisting of 8 times 6 numbers (whitespace delimited) used to derive a wallet.\n * @param opts - (Optional) Options to derive a Wallet.\n * @param opts.masterAddress - Include if a Wallet uses a Regular Key Pair. It must be the master address of the account.\n * @param opts.algorithm - The digital signature algorithm to generate an address for.\n * @returns A Wallet derived from secret numbers.\n * @throws ValidationError if unable to derive private key from secret number input.\n */\nexport function walletFromSecretNumbers(\n secretNumbers: string[] | string,\n opts?: { masterAddress?: string; algorithm?: ECDSA },\n): Wallet {\n const secret = new Account(secretNumbers).getFamilySeed()\n const updatedOpts: { masterAddress?: string; algorithm?: ECDSA } = {\n masterAddress: undefined,\n algorithm: undefined,\n }\n // Use secp256k1 since that's the algorithm used by popular wallets like Xumm when generating secret number accounts\n if (opts === undefined) {\n updatedOpts.algorithm = ECDSA.secp256k1\n } else {\n updatedOpts.masterAddress = opts.masterAddress\n updatedOpts.algorithm = opts.algorithm ?? ECDSA.secp256k1\n }\n return Wallet.fromSecret(secret, updatedOpts)\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA384 as SHA384n,\n sha384 as sha384n,\n sha512_224 as sha512_224n,\n SHA512_224 as SHA512_224n,\n sha512_256 as sha512_256n,\n SHA512_256 as SHA512_256n,\n SHA512 as SHA512n,\n sha512 as sha512n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512: typeof SHA512n = SHA512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512: typeof sha512n = sha512n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA384: typeof SHA384n = SHA384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha384: typeof sha384n = sha384n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_224: typeof SHA512_224n = SHA512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_224: typeof sha512_224n = sha512_224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA512_256: typeof SHA512_256n = SHA512_256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha512_256: typeof sha512_256n = sha512_256n;\n","import { Hash160 } from './hash-160'\nimport { bytesToHex, hexToBytes, hexToString } from '@xrplf/isomorphic/utils'\n\nconst XRP_HEX_REGEX = /^0{40}$/\nconst ISO_REGEX = /^[A-Z0-9a-z?!@#$%^&*(){}[\\]|]{3}$/\nconst HEX_REGEX = /^[A-F0-9]{40}$/\n// eslint-disable-next-line no-control-regex\nconst STANDARD_FORMAT_HEX_REGEX = /^0{24}[\\x00-\\x7F]{6}0{10}$/\n\n/**\n * Convert an ISO code to a currency bytes representation\n */\nfunction isoToBytes(iso: string): Uint8Array {\n const bytes = new Uint8Array(20)\n if (iso !== 'XRP') {\n const isoBytes = iso.split('').map((c) => c.charCodeAt(0))\n bytes.set(isoBytes, 12)\n }\n return bytes\n}\n\n/**\n * Tests if ISO is a valid iso code\n */\nfunction isIsoCode(iso: string): boolean {\n return ISO_REGEX.test(iso)\n}\n\nfunction isoCodeFromHex(code: Uint8Array): string | null {\n const iso = hexToString(bytesToHex(code))\n if (iso === 'XRP') {\n return null\n }\n if (isIsoCode(iso)) {\n return iso\n }\n return null\n}\n\n/**\n * Tests if hex is a valid hex-string\n */\nfunction isHex(hex: string): boolean {\n return HEX_REGEX.test(hex)\n}\n\n/**\n * Tests if a string is a valid representation of a currency\n */\nfunction isStringRepresentation(input: string): boolean {\n return input.length === 3 || isHex(input)\n}\n\n/**\n * Tests if a Uint8Array is a valid representation of a currency\n */\nfunction isBytesArray(bytes: Uint8Array): boolean {\n return bytes.byteLength === 20\n}\n\n/**\n * Ensures that a value is a valid representation of a currency\n */\nfunction isValidRepresentation(input: Uint8Array | string): boolean {\n return input instanceof Uint8Array\n ? isBytesArray(input)\n : isStringRepresentation(input)\n}\n\n/**\n * Generate bytes from a string or UInt8Array representation of a currency\n */\nfunction bytesFromRepresentation(input: string): Uint8Array {\n if (!isValidRepresentation(input)) {\n throw new Error(`Unsupported Currency representation: ${input}`)\n }\n return input.length === 3 ? isoToBytes(input) : hexToBytes(input)\n}\n\n/**\n * Class defining how to encode and decode Currencies\n */\nclass Currency extends Hash160 {\n static readonly XRP = new Currency(new Uint8Array(20))\n private readonly _iso: string | null\n\n constructor(byteBuf: Uint8Array) {\n super(byteBuf ?? Currency.XRP.bytes)\n const hex = bytesToHex(this.bytes)\n\n if (XRP_HEX_REGEX.test(hex)) {\n this._iso = 'XRP'\n } else if (STANDARD_FORMAT_HEX_REGEX.test(hex)) {\n this._iso = isoCodeFromHex(this.bytes.slice(12, 15))\n } else {\n this._iso = null\n }\n }\n\n /**\n * Return the ISO code of this currency\n *\n * @returns ISO code if it exists, else null\n */\n iso(): string | null {\n return this._iso\n }\n\n /**\n * Constructs a Currency object\n *\n * @param val Currency object or a string representation of a currency\n */\n static from<T extends Hash160 | string>(value: T): Currency {\n if (value instanceof Currency) {\n return value\n }\n\n if (typeof value === 'string') {\n return new Currency(bytesFromRepresentation(value))\n }\n\n throw new Error('Cannot construct Currency from value given')\n }\n\n /**\n * Gets the JSON representation of a currency\n *\n * @returns JSON representation\n */\n toJSON(): string {\n const iso = this.iso()\n if (iso !== null) {\n return iso\n }\n return bytesToHex(this.bytes)\n }\n}\n\nexport { Currency }\n","enum ECDSA {\n ed25519 = 'ed25519',\n secp256k1 = 'ecdsa-secp256k1',\n}\n\nexport default ECDSA\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\n\nimport {\n BaseTransaction,\n parseAmountValue,\n validateBaseTransaction,\n} from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n/**\n * The NFTokenOfferAccept transaction is used to accept offers\n * to buy or sell an NFToken. It can either:\n *\n * 1. Allow one offer to be accepted. This is called direct\n * mode.\n * 2. Allow two distinct offers, one offering to buy a\n * given NFToken and the other offering to sell the same\n * NFToken, to be accepted in an atomic fashion. This is\n * called brokered mode.\n *\n * To indicate direct mode, use either the `sell_offer` or\n * `buy_offer` fields, but not both. To indicate brokered mode,\n * use both the `sell_offer` and `buy_offer` fields. If you use\n * neither `sell_offer` nor `buy_offer`, the transaction is invalid.\n */\nexport interface NFTokenAcceptOffer extends BaseTransaction {\n TransactionType: 'NFTokenAcceptOffer'\n /**\n * Identifies the NFTokenOffer that offers to sell the NFToken.\n *\n * In direct mode this field is optional, but either NFTokenSellOffer or\n * NFTokenBuyOffer must be specified. In brokered mode, both NFTokenSellOffer\n * and NFTokenBuyOffer must be specified.\n */\n NFTokenSellOffer?: string\n /**\n * Identifies the NFTokenOffer that offers to buy the NFToken.\n *\n * In direct mode this field is optional, but either NFTokenSellOffer or\n * NFTokenBuyOffer must be specified. In brokered mode, both NFTokenSellOffer\n * and NFTokenBuyOffer must be specified.\n */\n NFTokenBuyOffer?: string\n /**\n * This field is only valid in brokered mode. It specifies the\n * amount that the broker will keep as part of their fee for\n * bringing the two offers together; the remaining amount will\n * be sent to the seller of the NFToken being bought. If\n * specified, the fee must be such that, prior to accounting\n * for the transfer fee charged by the issuer, the amount that\n * the seller would receive is at least as much as the amount\n * indicated in the sell offer.\n *\n * This functionality is intended to allow the owner of an\n * NFToken to offer their token for sale to a third party\n * broker, who may then attempt to sell the NFToken on for a\n * larger amount, without the broker having to own the NFToken\n * or custody funds.\n *\n * Note: in brokered mode, the offers referenced by NFTokenBuyOffer\n * and NFTokenSellOffer must both specify the same NFTokenID; that is,\n * both must be for the same NFToken.\n */\n NFTokenBrokerFee?: Amount\n}\n\nexport interface NFTokenAcceptOfferMetadata extends TransactionMetadataBase {\n // rippled 1.11.0 or later\n nftoken_id?: string\n}\n\nfunction validateNFTokenBrokerFee(tx: Record<string, unknown>): void {\n const value = parseAmountValue(tx.NFTokenBrokerFee)\n if (Number.isNaN(value)) {\n throw new ValidationError('NFTokenAcceptOffer: invalid NFTokenBrokerFee')\n }\n\n if (value <= 0) {\n throw new ValidationError(\n 'NFTokenAcceptOffer: NFTokenBrokerFee must be greater than 0; omit if there is no fee',\n )\n }\n\n if (tx.NFTokenSellOffer == null || tx.NFTokenBuyOffer == null) {\n throw new ValidationError(\n 'NFTokenAcceptOffer: both NFTokenSellOffer and NFTokenBuyOffer must be set if using brokered mode',\n )\n }\n}\n\n/**\n * Verify the form and type of an NFTokenAcceptOffer at runtime.\n *\n * @param tx - An NFTokenAcceptOffer Transaction.\n * @throws When the NFTokenAcceptOffer is Malformed.\n */\nexport function validateNFTokenAcceptOffer(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.NFTokenBrokerFee != null) {\n validateNFTokenBrokerFee(tx)\n }\n\n if (tx.NFTokenSellOffer == null && tx.NFTokenBuyOffer == null) {\n throw new ValidationError(\n 'NFTokenAcceptOffer: must set either NFTokenSellOffer or NFTokenBuyOffer',\n )\n }\n}\n","import { ValidationError } from '../../errors'\nimport { IssuedCurrencyAmount } from '../common'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n isAmount,\n validateBaseTransaction,\n} from './common'\n\n/**\n * Enum representing values of {@link TrustSet} transaction flags.\n *\n * @category Transaction Flags\n */\nexport enum TrustSetFlags {\n /**\n * Authorize the other party to hold currency issued by this account. (No\n * effect unless using the asfRequireAuth AccountSet flag.) Cannot be unset.\n */\n tfSetfAuth = 0x00010000,\n /**\n * Enable the No Ripple flag, which blocks rippling between two trust lines.\n * of the same currency if this flag is enabled on both.\n */\n tfSetNoRipple = 0x00020000,\n /** Disable the No Ripple flag, allowing rippling on this trust line. */\n tfClearNoRipple = 0x00040000,\n /** Freeze the trust line. */\n tfSetFreeze = 0x00100000,\n /** Unfreeze the trust line. */\n tfClearFreeze = 0x00200000,\n /** Deep-Freeze the trustline -- disallow sending and receiving the said IssuedCurrency */\n /** Allowed only if the trustline is already regularly frozen, or if tfSetFreeze is set in the same transaction. */\n tfSetDeepFreeze = 0x00400000,\n /** Clear a Deep-Frozen trustline */\n tfClearDeepFreeze = 0x00800000,\n}\n\n/**\n * Map of flags to boolean values representing {@link TrustSet} transaction\n * flags.\n *\n * @category Transaction Flags\n *\n * @example\n * ```typescript\n *\n * const trustSetTx: TrustSet = {\n * TransactionType: 'TrustSet',\n * Account: wallet2.getClassicAddress(),\n * LimitAmount: {\n * currency: 'FOO',\n * issuer: wallet1.getClassicAddress(),\n * value: '10000000000',\n * },\n * Flags: {\n * tfSetNoRipple: true\n * }\n * }\n *\n * // Autofill the tx to see how flags actually look compared to the interface usage.\n * const autofilledTx = await client.autofill(trustSetTx)\n * console.log(autofilledTx)\n * // {\n * // TransactionType: 'TrustSet',\n * // Account: 'r9dAdQQCBcGajVSeC9CqW3LCugjPDnAkEb',\n * // LimitAmount: {\n * // currency: 'FOO',\n * // issuer: 'rWZzUjo5xGiAoRBqzsndyzonXz47UV8u1',\n * // value: '10000000000'\n * // },\n * // Flags: 131072,\n * // Sequence: 21971483,\n * // Fee: '12',\n * // LastLedgerSequence: 21971503\n * // }\n * ```\n */\nexport interface TrustSetFlagsInterface extends GlobalFlagsInterface {\n /**\n * Authorize the other party to hold currency issued by this account. (No\n * effect unless using the asfRequireAuth AccountSet flag.) Cannot be unset.\n */\n tfSetfAuth?: boolean\n /**\n * Enable the No Ripple flag, which blocks rippling between two trust lines\n * of the same currency if this flag is enabled on both.\n */\n tfSetNoRipple?: boolean\n /** Disable the No Ripple flag, allowing rippling on this trust line. */\n tfClearNoRipple?: boolean\n /** Freeze the trust line. */\n tfSetFreeze?: boolean\n /** Unfreeze the trust line. */\n tfClearFreeze?: boolean\n /** Deep-Freeze the trustline -- disallow sending and receiving the said IssuedCurrency */\n /** Allowed only if the trustline is already regularly frozen, or if tfSetFreeze is set in the same transaction. */\n tfSetDeepFreeze?: boolean\n /** Clear a Deep-Frozen trust line */\n tfClearDeepFreeze?: boolean\n}\n\n/**\n * Create or modify a trust line linking two accounts.\n *\n * @category Transaction Models\n */\nexport interface TrustSet extends BaseTransaction {\n TransactionType: 'TrustSet'\n /**\n * Object defining the trust line to create or modify, in the format of a\n * Currency Amount.\n */\n LimitAmount: IssuedCurrencyAmount\n /**\n * Value incoming balances on this trust line at the ratio of this number per\n * 1,000,000,000 units. A value of 0 is shorthand for treating balances at\n * face value.\n */\n QualityIn?: number\n /**\n * Value outgoing balances on this trust line at the ratio of this number per\n * 1,000,000,000 units. A value of 0 is shorthand for treating balances at\n * face value.\n */\n QualityOut?: number\n Flags?: number | TrustSetFlagsInterface\n}\n\n/**\n * Verify the form and type of a TrustSet at runtime.\n *\n * @param tx - A TrustSet Transaction.\n * @throws When the TrustSet is malformed.\n */\nexport function validateTrustSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n const { LimitAmount, QualityIn, QualityOut } = tx\n\n if (LimitAmount === undefined) {\n throw new ValidationError('TrustSet: missing field LimitAmount')\n }\n\n if (!isAmount(LimitAmount)) {\n throw new ValidationError('TrustSet: invalid LimitAmount')\n }\n\n if (QualityIn !== undefined && typeof QualityIn !== 'number') {\n throw new ValidationError('TrustSet: QualityIn must be a number')\n }\n\n if (QualityOut !== undefined && typeof QualityOut !== 'number') {\n throw new ValidationError('TrustSet: QualityOut must be a number')\n }\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n","import { ValidationError } from '../../errors'\nimport { Amount, Currency, IssuedCurrencyAmount } from '../common'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n isAmount,\n isIssuedCurrency,\n isIssuedCurrencyAmount,\n validateBaseTransaction,\n} from './common'\n\n/**\n * Enum representing values for AMMDeposit Transaction Flags.\n *\n * @category Transaction Flags\n */\nexport enum AMMDepositFlags {\n tfLPToken = 0x00010000,\n tfSingleAsset = 0x00080000,\n tfTwoAsset = 0x00100000,\n tfOneAssetLPToken = 0x00200000,\n tfLimitLPToken = 0x00400000,\n tfTwoAssetIfEmpty = 0x00800000,\n}\n\nexport interface AMMDepositFlagsInterface extends GlobalFlagsInterface {\n tfLPToken?: boolean\n tfSingleAsset?: boolean\n tfTwoAsset?: boolean\n tfOneAssetLPToken?: boolean\n tfLimitLPToken?: boolean\n tfTwoAssetIfEmpty?: boolean\n}\n\n/**\n * Deposit funds into an Automated Market Maker (AMM) instance\n * and receive the AMM's liquidity provider tokens (LP Tokens) in exchange.\n *\n * You can deposit one or both of the assets in the AMM's pool.\n * If successful, this transaction creates a trust line to the AMM Account (limit 0) to hold the LP Tokens.\n */\nexport interface AMMDeposit extends BaseTransaction {\n TransactionType: 'AMMDeposit'\n\n /**\n * The definition for one of the assets in the AMM's pool.\n */\n Asset: Currency\n\n /**\n * The definition for the other asset in the AMM's pool.\n */\n Asset2: Currency\n\n /**\n * The amount of one asset to deposit to the AMM.\n * If present, this must match the type of one of the assets (tokens or XRP) in the AMM's pool.\n */\n Amount?: Amount\n\n /**\n * The amount of another asset to add to the AMM.\n * If present, this must match the type of the other asset in the AMM's pool and cannot be the same asset as Amount.\n */\n Amount2?: Amount\n\n /**\n * The maximum effective price, in the deposit asset, to pay for each LP Token received.\n */\n EPrice?: Amount\n\n /**\n * How many of the AMM's LP Tokens to buy.\n */\n LPTokenOut?: IssuedCurrencyAmount\n}\n\n/**\n * Verify the form and type of an AMMDeposit at runtime.\n *\n * @param tx - An AMMDeposit Transaction.\n * @throws When the AMMDeposit is Malformed.\n */\nexport function validateAMMDeposit(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Asset == null) {\n throw new ValidationError('AMMDeposit: missing field Asset')\n }\n\n if (!isIssuedCurrency(tx.Asset)) {\n throw new ValidationError('AMMDeposit: Asset must be a Currency')\n }\n\n if (tx.Asset2 == null) {\n throw new ValidationError('AMMDeposit: missing field Asset2')\n }\n\n if (!isIssuedCurrency(tx.Asset2)) {\n throw new ValidationError('AMMDeposit: Asset2 must be a Currency')\n }\n\n if (tx.Amount2 != null && tx.Amount == null) {\n throw new ValidationError('AMMDeposit: must set Amount with Amount2')\n } else if (tx.EPrice != null && tx.Amount == null) {\n throw new ValidationError('AMMDeposit: must set Amount with EPrice')\n } else if (tx.LPTokenOut == null && tx.Amount == null) {\n throw new ValidationError(\n 'AMMDeposit: must set at least LPTokenOut or Amount',\n )\n }\n\n if (tx.LPTokenOut != null && !isIssuedCurrencyAmount(tx.LPTokenOut)) {\n throw new ValidationError(\n 'AMMDeposit: LPTokenOut must be an IssuedCurrencyAmount',\n )\n }\n\n if (tx.Amount != null && !isAmount(tx.Amount)) {\n throw new ValidationError('AMMDeposit: Amount must be an Amount')\n }\n\n if (tx.Amount2 != null && !isAmount(tx.Amount2)) {\n throw new ValidationError('AMMDeposit: Amount2 must be an Amount')\n }\n\n if (tx.EPrice != null && !isAmount(tx.EPrice)) {\n throw new ValidationError('AMMDeposit: EPrice must be an Amount')\n }\n}\n","/* eslint-disable @typescript-eslint/no-magic-numbers -- this file mimics\n behavior in rippled. Magic numbers are used for lengths and conditions */\n/* eslint-disable no-bitwise -- this file mimics behavior in rippled. It uses\n bitwise operators for and-ing numbers with a mask and bit shifting. */\n\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\nimport BigNumber from 'bignumber.js'\nimport { decode, encode } from 'ripple-binary-codec'\n\nimport { ValidationError, XrplError } from '../../errors'\nimport { APIVersion } from '../../models'\nimport { LedgerEntry } from '../../models/ledger'\nimport { LedgerVersionMap } from '../../models/ledger/Ledger'\nimport { Transaction, TransactionMetadata } from '../../models/transactions'\nimport { GlobalFlags } from '../../models/transactions/common'\nimport { hasFlag } from '../../models/utils'\n\nimport HashPrefix from './HashPrefix'\nimport sha512Half from './sha512Half'\nimport SHAMap, { NodeType } from './SHAMap'\n\nconst HEX = 16\n\ninterface HashLedgerHeaderOptions {\n computeTreeHashes?: boolean\n}\n\nfunction intToHex(integer: number, byteLength: number): string {\n const foo = Number(integer)\n .toString(HEX)\n .padStart(byteLength * 2, '0')\n\n return foo\n}\n\nfunction bigintToHex(\n integerString: string | number | BigNumber,\n byteLength: number,\n): string {\n const hex = new BigNumber(integerString).toString(HEX)\n return hex.padStart(byteLength * 2, '0')\n}\n\nfunction addLengthPrefix(hex: string): string {\n const length = hex.length / 2\n if (length <= 192) {\n return bytesToHex([length]) + hex\n }\n if (length <= 12480) {\n const prefix = length - 193\n return bytesToHex([193 + (prefix >>> 8), prefix & 0xff]) + hex\n }\n if (length <= 918744) {\n const prefix = length - 12481\n return (\n bytesToHex([\n 241 + (prefix >>> 16),\n (prefix >>> 8) & 0xff,\n prefix & 0xff,\n ]) + hex\n )\n }\n throw new XrplError('Variable integer overflow.')\n}\n\n/**\n * Hashes the Transaction object as the ledger does. Throws if the transaction is unsigned.\n *\n * @param tx - A transaction to hash. Tx may be in binary blob form. Tx must be signed.\n * @returns A hash of tx.\n * @throws ValidationError if the Transaction is unsigned.\n * @category Utilities\n */\nexport function hashSignedTx(tx: Transaction | string): string {\n let txBlob: string\n let txObject: Transaction\n if (typeof tx === 'string') {\n txBlob = tx\n /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Required until updated in binary codec. */\n txObject = decode(tx) as unknown as Transaction\n } else {\n txBlob = encode(tx)\n txObject = tx\n }\n\n if (\n txObject.TxnSignature === undefined &&\n txObject.Signers === undefined &&\n txObject.SigningPubKey === undefined &&\n !hasFlag(txObject, GlobalFlags.tfInnerBatchTxn, 'tfInnerBatchTxn')\n ) {\n throw new ValidationError('The transaction must be signed to hash it.')\n }\n\n const prefix = HashPrefix.TRANSACTION_ID.toString(16).toUpperCase()\n return sha512Half(prefix.concat(txBlob))\n}\n\n/**\n * Compute the hash of a ledger.\n *\n * @param ledgerHeader - Ledger to compute the hash of.\n * @returns The hash of the ledger.\n * @category Utilities\n */\nexport function hashLedgerHeader(\n ledgerHeader: LedgerVersionMap<APIVersion>,\n): string {\n const prefix = HashPrefix.LEDGER.toString(HEX).toUpperCase()\n\n const ledger =\n prefix +\n intToHex(Number(ledgerHeader.ledger_index), 4) +\n bigintToHex(ledgerHeader.total_coins, 8) +\n ledgerHeader.parent_hash +\n ledgerHeader.transaction_hash +\n ledgerHeader.account_hash +\n intToHex(ledgerHeader.parent_close_time, 4) +\n intToHex(ledgerHeader.close_time, 4) +\n intToHex(ledgerHeader.close_time_resolution, 1) +\n intToHex(ledgerHeader.close_flags, 1)\n\n return sha512Half(ledger)\n}\n\n/**\n * Compute the root hash of the SHAMap containing all transactions.\n *\n * @param transactions - List of Transactions.\n * @returns The root hash of the SHAMap.\n * @category Utilities\n */\nexport function hashTxTree(\n transactions: Array<Transaction & { metaData?: TransactionMetadata }>,\n): string {\n const shamap = new SHAMap()\n for (const txJSON of transactions) {\n const txBlobHex = encode(txJSON)\n const metaHex = encode(txJSON.metaData ?? {})\n const txHash = hashSignedTx(txBlobHex)\n const data = addLengthPrefix(txBlobHex) + addLengthPrefix(metaHex)\n shamap.addItem(txHash, data, NodeType.TRANSACTION_METADATA)\n }\n\n return shamap.hash\n}\n\n/**\n * Compute the state hash of a list of LedgerEntries.\n *\n * @param entries - List of LedgerEntries.\n * @returns Hash of SHAMap that consists of all entries.\n * @category Utilities\n */\nexport function hashStateTree(entries: LedgerEntry[]): string {\n const shamap = new SHAMap()\n\n entries.forEach((ledgerEntry) => {\n const data = encode(ledgerEntry)\n shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE)\n })\n\n return shamap.hash\n}\n\nfunction computeTransactionHash(\n ledger: LedgerVersionMap<APIVersion>,\n options: HashLedgerHeaderOptions,\n): string {\n const { transaction_hash } = ledger\n\n if (!options.computeTreeHashes) {\n return transaction_hash\n }\n\n if (ledger.transactions == null) {\n throw new ValidationError('transactions is missing from the ledger')\n }\n\n const transactionHash = hashTxTree(ledger.transactions)\n\n if (transaction_hash !== transactionHash) {\n throw new ValidationError(\n 'transactionHash in header' +\n ' does not match computed hash of transactions',\n {\n transactionHashInHeader: transaction_hash,\n computedHashOfTransactions: transactionHash,\n },\n )\n }\n\n return transactionHash\n}\n\nfunction computeStateHash(\n ledger: LedgerVersionMap<APIVersion>,\n options: HashLedgerHeaderOptions,\n): string {\n const { account_hash } = ledger\n\n if (!options.computeTreeHashes) {\n return account_hash\n }\n\n if (ledger.accountState == null) {\n throw new ValidationError('accountState is missing from the ledger')\n }\n\n const stateHash = hashStateTree(ledger.accountState)\n\n if (account_hash !== stateHash) {\n throw new ValidationError(\n 'stateHash in header does not match computed hash of state',\n )\n }\n\n return stateHash\n}\n\n/**\n * Compute the hash of a ledger.\n *\n * @param ledger - Ledger to compute the hash for.\n * @param options - Allow client to recompute Transaction and State Hashes.\n * @param options.computeTreeHashes - Whether to recompute the Transaction and State Hashes.\n * @returns The has of ledger.\n * @category Utilities\n */\nfunction hashLedger(\n ledger: LedgerVersionMap<APIVersion>,\n options: {\n computeTreeHashes?: boolean\n } = {},\n): string {\n const subhashes = {\n transaction_hash: computeTransactionHash(ledger, options),\n account_hash: computeStateHash(ledger, options),\n }\n return hashLedgerHeader({ ...ledger, ...subhashes })\n}\n\nexport default hashLedger\n","import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, validateBaseTransaction } from './common'\n\n/**\n * Cancels an unredeemed Check, removing it from the ledger without sending any\n * money. The source or the destination of the check can cancel a Check at any\n * time using this transaction type. If the Check has expired, any address can\n * cancel it.\n *\n * @category Transaction Models\n */\nexport interface CheckCancel extends BaseTransaction {\n TransactionType: 'CheckCancel'\n /**\n * The ID of the Check ledger object to cancel as a 64-character hexadecimal\n * string.\n */\n CheckID: string\n}\n\n/**\n * Verify the form and type of an CheckCancel at runtime.\n *\n * @param tx - An CheckCancel Transaction.\n * @throws When the CheckCancel is Malformed.\n */\nexport function validateCheckCancel(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.CheckID !== undefined && typeof tx.CheckID !== 'string') {\n throw new ValidationError('CheckCancel: invalid CheckID')\n }\n}\n","import { concat, equal, hexToBytes } from '@xrplf/isomorphic/utils'\n\nimport {\n codec,\n encodeSeed,\n decodeSeed,\n encodeAccountID,\n decodeAccountID,\n encodeNodePublic,\n decodeNodePublic,\n encodeAccountPublic,\n decodeAccountPublic,\n isValidClassicAddress,\n} from './xrp-codec'\n\nconst PREFIX_BYTES = {\n // 5, 68\n main: Uint8Array.from([0x05, 0x44]),\n // 4, 147\n test: Uint8Array.from([0x04, 0x93]),\n}\n\nconst MAX_32_BIT_UNSIGNED_INT = 4294967295\n\nfunction classicAddressToXAddress(\n classicAddress: string,\n tag: number | false,\n test: boolean,\n): string {\n const accountId = decodeAccountID(classicAddress)\n return encodeXAddress(accountId, tag, test)\n}\n\nfunction encodeXAddress(\n accountId: Uint8Array,\n tag: number | false,\n test: boolean,\n): string {\n if (accountId.length !== 20) {\n // RIPEMD160 is 160 bits = 20 bytes\n throw new Error('Account ID must be 20 bytes')\n }\n if (tag !== false && tag > MAX_32_BIT_UNSIGNED_INT) {\n throw new Error('Invalid tag')\n }\n const theTag = tag || 0\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Passing null is a common js mistake\n const flag = tag === false || tag == null ? 0 : 1\n /* eslint-disable no-bitwise ---\n * need to use bitwise operations here */\n const bytes = concat([\n test ? PREFIX_BYTES.test : PREFIX_BYTES.main,\n accountId,\n Uint8Array.from([\n // 0x00 if no tag, 0x01 if 32-bit tag\n flag,\n // first byte\n theTag & 0xff,\n // second byte\n (theTag >> 8) & 0xff,\n // third byte\n (theTag >> 16) & 0xff,\n // fourth byte\n (theTag >> 24) & 0xff,\n 0,\n 0,\n 0,\n // four zero bytes (reserved for 64-bit tags)\n 0,\n ]),\n ])\n /* eslint-enable no-bitwise */\n return codec.encodeChecked(bytes)\n}\n\nfunction xAddressToClassicAddress(xAddress: string): {\n classicAddress: string\n tag: number | false\n test: boolean\n} {\n /* eslint-disable @typescript-eslint/naming-convention --\n * TODO 'test' should be something like 'isTest', do this later\n */\n const { accountId, tag, test } = decodeXAddress(xAddress)\n /* eslint-enable @typescript-eslint/naming-convention */\n const classicAddress = encodeAccountID(accountId)\n return {\n classicAddress,\n tag,\n test,\n }\n}\n\nfunction decodeXAddress(xAddress: string): {\n accountId: Uint8Array\n tag: number | false\n test: boolean\n} {\n const decoded = codec.decodeChecked(xAddress)\n /* eslint-disable @typescript-eslint/naming-convention --\n * TODO 'test' should be something like 'isTest', do this later\n */\n const test = isUint8ArrayForTestAddress(decoded)\n /* eslint-enable @typescript-eslint/naming-convention */\n const accountId = decoded.slice(2, 22)\n const tag = tagFromUint8Array(decoded)\n return {\n accountId,\n tag,\n test,\n }\n}\n\nfunction isUint8ArrayForTestAddress(buf: Uint8Array): boolean {\n const decodedPrefix = buf.slice(0, 2)\n if (equal(PREFIX_BYTES.main, decodedPrefix)) {\n return false\n }\n if (equal(PREFIX_BYTES.test, decodedPrefix)) {\n return true\n }\n\n throw new Error('Invalid X-address: bad prefix')\n}\n\nfunction tagFromUint8Array(buf: Uint8Array): number | false {\n const flag = buf[22]\n if (flag >= 2) {\n // No support for 64-bit tags at this time\n throw new Error('Unsupported X-address')\n }\n if (flag === 1) {\n // Little-endian to big-endian\n return buf[23] + buf[24] * 0x100 + buf[25] * 0x10000 + buf[26] * 0x1000000\n }\n if (flag !== 0) {\n throw new Error('flag must be zero to indicate no tag')\n }\n if (!equal(hexToBytes('0000000000000000'), buf.slice(23, 23 + 8))) {\n throw new Error('remaining bytes must be zero')\n }\n return false\n}\n\nfunction isValidXAddress(xAddress: string): boolean {\n try {\n decodeXAddress(xAddress)\n } catch (_error) {\n return false\n }\n return true\n}\n\nexport {\n // Codec with XRP alphabet\n codec,\n // Encode entropy as a \"seed\"\n encodeSeed,\n // Decode a seed into an object with its version, type, and bytes\n decodeSeed,\n // Encode bytes as a classic address (r...)\n encodeAccountID,\n // Decode a classic address to its raw bytes\n decodeAccountID,\n // Encode bytes to XRP Ledger node public key format\n encodeNodePublic,\n // Decode an XRP Ledger node public key into its raw bytes\n decodeNodePublic,\n // Encode a public key, as for payment channels\n encodeAccountPublic,\n // Decode a public key, as for payment channels\n decodeAccountPublic,\n // Check whether a classic address (r...) is valid\n isValidClassicAddress,\n // Derive X-address from classic address, tag, and network ID\n classicAddressToXAddress,\n // Encode account ID, tag, and network ID to X-address\n encodeXAddress,\n // Decode X-address to account ID, tag, and network ID\n xAddressToClassicAddress,\n // Convert X-address to classic address, tag, and network ID\n decodeXAddress,\n // Check whether an X-address (X...) is valid\n isValidXAddress,\n}\n","import { stringToHex, hexToString } from '@xrplf/isomorphic/utils'\n\n/**\n * Converts a string to its hex equivalent. Useful for Memos.\n *\n * @param string - The string to convert to Hex.\n * @returns The Hex equivalent of the string.\n *\n * @deprecated use `@xrplf/isomorphic/utils`'s `stringToHex`\n *\n * @category Utilities\n */\nfunction convertStringToHex(string: string): string {\n return stringToHex(string)\n}\n\n/**\n * Converts hex to its string equivalent. Useful to read the Domain field and some Memos.\n *\n * @param hex - The hex to convert to a string.\n * @param encoding - The encoding to use. Defaults to 'utf8' (UTF-8). 'ascii' is also allowed.\n * @returns The converted string.\n *\n * @deprecated use `@xrplf/isomorphic/utils`'s `hexToString`\n *\n * @category Utilities\n */\nfunction convertHexToString(hex: string, encoding = 'utf8'): string {\n return hexToString(hex, encoding)\n}\n\nexport { convertHexToString, convertStringToHex }\n","import { AccountLinesTrustline, Balance } from '../models'\n\n/**\n * Formats an array of trustlines into an array of balances.\n *\n * @param trustlines - The array of trustlines to format.\n * @returns An array of balances, each containing the value, currency, and issuer.\n */\nexport function formatBalances(trustlines: AccountLinesTrustline[]): Balance[] {\n return trustlines.map((trustline) => ({\n value: trustline.balance,\n currency: trustline.currency,\n issuer: trustline.account,\n }))\n}\n","import BigNumber from 'bignumber.js'\n\nimport { type Client } from '..'\nimport { XrplError } from '../errors'\n\nconst NUM_DECIMAL_PLACES = 6\nconst BASE_10 = 10\n\n/**\n * Calculates the current transaction fee for the ledger.\n * Note: This is a public API that can be called directly.\n *\n * @param client - The Client used to connect to the ledger.\n * @param cushion - The fee cushion to use.\n * @returns The transaction fee.\n */\nexport default async function getFeeXrp(\n client: Client,\n cushion?: number,\n): Promise<string> {\n const feeCushion = cushion ?? client.feeCushion\n\n const serverInfo = (\n await client.request({\n command: 'server_info',\n })\n ).result.info\n\n const baseFee = serverInfo.validated_ledger?.base_fee_xrp\n\n if (baseFee == null) {\n throw new XrplError(\n 'getFeeXrp: Could not get base_fee_xrp from server_info',\n )\n }\n\n const baseFeeXrp = new BigNumber(baseFee)\n if (serverInfo.load_factor == null) {\n // https://github.com/ripple/rippled/issues/3812#issuecomment-816871100\n serverInfo.load_factor = 1\n }\n let fee = baseFeeXrp.times(serverInfo.load_factor).times(feeCushion)\n\n // Cap fee to `client.maxFeeXRP`\n fee = BigNumber.min(fee, client.maxFeeXRP)\n // Round fee to 6 decimal places\n return new BigNumber(fee.toFixed(NUM_DECIMAL_PLACES)).toString(BASE_10)\n}\n","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n */\nimport { HashMD } from './_md.ts';\nimport u64 from './_u64.ts';\nimport { type CHash, wrapConstructor } from './utils.ts';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x6a09e667 | 0;\n protected Al: number = 0xf3bcc908 | 0;\n protected Bh: number = 0xbb67ae85 | 0;\n protected Bl: number = 0x84caa73b | 0;\n protected Ch: number = 0x3c6ef372 | 0;\n protected Cl: number = 0xfe94f82b | 0;\n protected Dh: number = 0xa54ff53a | 0;\n protected Dl: number = 0x5f1d36f1 | 0;\n protected Eh: number = 0x510e527f | 0;\n protected El: number = 0xade682d1 | 0;\n protected Fh: number = 0x9b05688c | 0;\n protected Fl: number = 0x2b3e6c1f | 0;\n protected Gh: number = 0x1f83d9ab | 0;\n protected Gl: number = 0xfb41bd6b | 0;\n protected Hh: number = 0x5be0cd19 | 0;\n protected Hl: number = 0x137e2179 | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy(): void {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x8c3d37c8 | 0;\n protected Al: number = 0x19544da2 | 0;\n protected Bh: number = 0x73e19966 | 0;\n protected Bl: number = 0x89dcd4d6 | 0;\n protected Ch: number = 0x1dfab7ae | 0;\n protected Cl: number = 0x32ff9c82 | 0;\n protected Dh: number = 0x679dd514 | 0;\n protected Dl: number = 0x582f9fcf | 0;\n protected Eh: number = 0x0f6d2b69 | 0;\n protected El: number = 0x7bd44da8 | 0;\n protected Fh: number = 0x77e36f73 | 0;\n protected Fl: number = 0x04c48942 | 0;\n protected Gh: number = 0x3f9d85a8 | 0;\n protected Gl: number = 0x6a1d36c8 | 0;\n protected Hh: number = 0x1112e6ad | 0;\n protected Hl: number = 0x91d692a1 | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0x22312194 | 0;\n protected Al: number = 0xfc2bf72c | 0;\n protected Bh: number = 0x9f555fa3 | 0;\n protected Bl: number = 0xc84c64c2 | 0;\n protected Ch: number = 0x2393b86b | 0;\n protected Cl: number = 0x6f53b151 | 0;\n protected Dh: number = 0x96387719 | 0;\n protected Dl: number = 0x5940eabd | 0;\n protected Eh: number = 0x96283ee2 | 0;\n protected El: number = 0xa88effe3 | 0;\n protected Fh: number = 0xbe5e1e25 | 0;\n protected Fl: number = 0x53863992 | 0;\n protected Gh: number = 0x2b0199fc | 0;\n protected Gl: number = 0x2c85b8aa | 0;\n protected Hh: number = 0x0eb72ddc | 0;\n protected Hl: number = 0x81c52ca2 | 0;\n\n constructor() {\n super(32);\n }\n}\n\nexport class SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = 0xcbbb9d5d | 0;\n protected Al: number = 0xc1059ed8 | 0;\n protected Bh: number = 0x629a292a | 0;\n protected Bl: number = 0x367cd507 | 0;\n protected Ch: number = 0x9159015a | 0;\n protected Cl: number = 0x3070dd17 | 0;\n protected Dh: number = 0x152fecd8 | 0;\n protected Dl: number = 0xf70e5939 | 0;\n protected Eh: number = 0x67332667 | 0;\n protected El: number = 0xffc00b31 | 0;\n protected Fh: number = 0x8eb44a87 | 0;\n protected Fl: number = 0x68581511 | 0;\n protected Gh: number = 0xdb0c2e0d | 0;\n protected Gl: number = 0x64f98fa7 | 0;\n protected Hh: number = 0x47b5481d | 0;\n protected Hl: number = 0xbefa4fa4 | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/** SHA2-512 hash function. */\nexport const sha512: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512());\n/** SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_224: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\n/** SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_256: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\n/** SHA2-384 hash function. */\nexport const sha384: CHash = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n","/**\n * RIPEMD-160 legacy hash function.\n * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n * @module\n * @deprecated\n */\nimport { RIPEMD160 as RIPEMD160n, ripemd160 as ripemd160n } from './legacy.ts';\n/** @deprecated Use import from `noble/hashes/legacy` module */\nexport const RIPEMD160: typeof RIPEMD160n = RIPEMD160n;\n/** @deprecated Use import from `noble/hashes/legacy` module */\nexport const ripemd160: typeof ripemd160n = ripemd160n;\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport type { CHash } from './abstract/utils.js';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.js';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","import { decode } from 'ripple-binary-codec'\n\nimport { NFToken } from '../models/ledger/NFTokenPage'\nimport {\n CreatedNode,\n isCreatedNode,\n isModifiedNode,\n ModifiedNode,\n TransactionMetadata,\n} from '../models/transactions/metadata'\n\n/**\n * Ensures that the metadata is in a deserialized format to parse.\n *\n * @param meta - the metadata from a `tx` method call. Can be in json format or binary format.\n * @returns the metadata in a deserialized format.\n */\nfunction ensureDecodedMeta(\n meta: TransactionMetadata | string,\n): TransactionMetadata {\n if (typeof meta === 'string') {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Meta is either metadata or serialized metadata.\n return decode(meta) as unknown as TransactionMetadata\n }\n return meta\n}\n\n/**\n * Gets the NFTokenID for an NFT recently minted with NFTokenMint.\n *\n * @param meta - Metadata from the response to submitting and waiting for an NFTokenMint transaction or from a `tx` method call.\n * @returns The NFTokenID for the minted NFT.\n * @throws if meta is not TransactionMetadata.\n */\n// eslint-disable-next-line max-lines-per-function -- This function has a lot of documentation\nexport default function getNFTokenID(\n meta: TransactionMetadata | string | undefined,\n): string | undefined {\n if (typeof meta !== 'string' && meta?.AffectedNodes === undefined) {\n throw new TypeError(`Unable to parse the parameter given to getNFTokenID.\n 'meta' must be the metadata from an NFTokenMint transaction. Received ${JSON.stringify(\n meta,\n )} instead.`)\n }\n\n const decodedMeta = ensureDecodedMeta(meta)\n\n /*\n * When a mint results in splitting an existing page,\n * it results in a created page and a modified node. Sometimes,\n * the created node needs to be linked to a third page, resulting\n * in modifying that third page's PreviousPageMin or NextPageMin\n * field changing, but no NFTs within that page changing. In this\n * case, there will be no previous NFTs and we need to skip.\n * However, there will always be NFTs listed in the final fields,\n * as rippled outputs all fields in final fields even if they were\n * not changed. Thus why we add the additional condition to check\n * if the PreviousFields contains NFTokens\n */\n const affectedNodes = decodedMeta.AffectedNodes.filter((node) => {\n if (isCreatedNode(node)) {\n return node.CreatedNode.LedgerEntryType === 'NFTokenPage'\n }\n if (isModifiedNode(node)) {\n return (\n node.ModifiedNode.LedgerEntryType === 'NFTokenPage' &&\n Boolean(node.ModifiedNode.PreviousFields?.NFTokens)\n )\n }\n return false\n })\n /* eslint-disable @typescript-eslint/consistent-type-assertions -- Necessary for parsing metadata */\n const previousTokenIDSet = new Set(\n affectedNodes\n .flatMap((node) => {\n const nftokens = isModifiedNode(node)\n ? (node.ModifiedNode.PreviousFields?.NFTokens as NFToken[])\n : []\n return nftokens.map((token) => token.NFToken.NFTokenID)\n })\n .filter((id) => Boolean(id)),\n )\n\n /* eslint-disable @typescript-eslint/no-unnecessary-condition -- Cleaner to read */\n const finalTokenIDs = affectedNodes\n .flatMap((node) =>\n (\n (((node as ModifiedNode).ModifiedNode?.FinalFields?.NFTokens ??\n (node as CreatedNode).CreatedNode?.NewFields\n ?.NFTokens) as NFToken[]) ?? []\n ).map((token) => token.NFToken.NFTokenID),\n )\n .filter((nftokenID) => Boolean(nftokenID))\n /* eslint-enable @typescript-eslint/consistent-type-assertions -- Necessary for parsing metadata */\n /* eslint-enable @typescript-eslint/no-unnecessary-condition -- Cleaner to read */\n const nftokenID = finalTokenIDs.find((id) => !previousTokenIDSet.has(id))\n\n return nftokenID\n}\n","import { ValidationError } from '../../errors'\nimport { Signer } from '../common'\nimport { hasFlag } from '../utils'\n\nimport {\n BaseTransaction,\n GlobalFlags,\n GlobalFlagsInterface,\n isArray,\n isRecord,\n isString,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\nimport type { SubmittableTransaction } from './transaction'\n\n/**\n * Enum representing values of {@link Batch} transaction flags.\n *\n * @category Transaction Flags\n */\nexport enum BatchFlags {\n tfAllOrNothing = 0x00010000,\n tfOnlyOne = 0x00020000,\n tfUntilFailure = 0x00040000,\n tfIndependent = 0x00080000,\n}\n\n/**\n * Map of flags to boolean values representing {@link Batch} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface BatchFlagsInterface extends GlobalFlagsInterface {\n tfAllOrNothing?: boolean\n tfOnlyOne?: boolean\n tfUntilFailure?: boolean\n tfIndependent?: boolean\n}\n\nexport type BatchInnerTransaction = SubmittableTransaction & {\n Fee?: '0'\n\n SigningPubKey?: ''\n\n TxnSignature?: never\n\n Signers?: never\n\n LastLedgerSequence?: never\n}\n\nexport interface BatchSigner {\n BatchSigner: {\n Account: string\n\n SigningPubKey?: string\n\n TxnSignature?: string\n\n Signers?: Signer[]\n }\n}\n\n/**\n * @category Transaction Models\n */\nexport interface Batch extends BaseTransaction {\n TransactionType: 'Batch'\n\n BatchSigners?: BatchSigner[]\n\n RawTransactions: Array<{\n RawTransaction: BatchInnerTransaction\n }>\n}\n\n/**\n * Verify the form and type of a Batch at runtime.\n *\n * @param tx - A Batch Transaction.\n * @throws When the Batch is malformed.\n */\n// eslint-disable-next-line max-lines-per-function -- needed here due to the complexity\nexport function validateBatch(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'RawTransactions', isArray)\n\n tx.RawTransactions.forEach((rawTxObj, index) => {\n if (!isRecord(rawTxObj)) {\n throw new ValidationError(\n `Batch: RawTransactions[${index}] is not object.`,\n )\n }\n validateRequiredField(rawTxObj, 'RawTransaction', isRecord, {\n paramName: `RawTransactions[${index}].RawTransaction`,\n txType: 'Batch',\n })\n\n const rawTx = rawTxObj.RawTransaction\n if (rawTx.TransactionType === 'Batch') {\n throw new ValidationError(\n `Batch: RawTransactions[${index}] is a Batch transaction. Cannot nest Batch transactions.`,\n )\n }\n\n // Check for the `tfInnerBatchTxn` flag in the inner transactions\n if (!hasFlag(rawTx, GlobalFlags.tfInnerBatchTxn, 'tfInnerBatchTxn')) {\n throw new ValidationError(\n `Batch: RawTransactions[${index}] must contain the \\`tfInnerBatchTxn\\` flag.`,\n )\n }\n\n // Full validation of each `RawTransaction` object is done in `validate` to avoid dependency cycles\n })\n\n validateOptionalField(tx, 'BatchSigners', isArray)\n\n tx.BatchSigners?.forEach((signerObj, index) => {\n if (!isRecord(signerObj)) {\n throw new ValidationError(`Batch: BatchSigners[${index}] is not object.`)\n }\n\n const signerRecord = signerObj\n validateRequiredField(signerRecord, 'BatchSigner', isRecord, {\n paramName: `BatchSigners[${index}].BatchSigner`,\n txType: 'Batch',\n })\n\n const signer = signerRecord.BatchSigner\n validateRequiredField(signer, 'Account', isString, {\n paramName: `BatchSigners[${index}].Account`,\n txType: 'Batch',\n })\n validateOptionalField(signer, 'SigningPubKey', isString, {\n paramName: `BatchSigners[${index}].SigningPubKey`,\n txType: 'Batch',\n })\n validateOptionalField(signer, 'TxnSignature', isString, {\n paramName: `BatchSigners[${index}].TxnSignature`,\n txType: 'Batch',\n })\n validateOptionalField(signer, 'Signers', isArray, {\n paramName: `BatchSigners[${index}].Signers`,\n txType: 'Batch',\n })\n })\n}\n","import { ValidationError } from '../../errors'\n\nimport {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateCredentialType,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * Deletes a Credential object.\n *\n * @category Transaction Models\n * */\nexport interface CredentialDelete extends BaseTransaction {\n TransactionType: 'CredentialDelete'\n\n /** The transaction submitter. */\n Account: string\n\n /** A hex-encoded value to identify the type of credential from the issuer. */\n CredentialType: string\n\n /** The person that the credential is for. If omitted, Account is assumed to be the subject. */\n Subject?: string\n\n /** The issuer of the credential. If omitted, Account is assumed to be the issuer. */\n Issuer?: string\n}\n\n/**\n * Verify the form and type of a CredentialDelete at runtime.\n *\n * @param tx - A CredentialDelete Transaction.\n * @throws When the CredentialDelete is Malformed.\n */\nexport function validateCredentialDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (!tx.Subject && !tx.Issuer) {\n throw new ValidationError(\n 'CredentialDelete: either `Issuer` or `Subject` must be provided',\n )\n }\n\n validateRequiredField(tx, 'Account', isString)\n\n validateCredentialType(tx)\n\n validateOptionalField(tx, 'Subject', isString)\n\n validateOptionalField(tx, 'Issuer', isString)\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","import { Hash } from './hash'\n\n/**\n * Hash with a width of 192 bits\n */\nclass Hash192 extends Hash {\n static readonly width = 24\n static readonly ZERO_192: Hash192 = new Hash192(new Uint8Array(Hash192.width))\n\n constructor(bytes?: Uint8Array) {\n if (bytes && bytes.byteLength === 0) {\n bytes = Hash192.ZERO_192.bytes\n }\n\n super(bytes ?? Hash192.ZERO_192.bytes)\n }\n}\n\nexport { Hash192 }\n","import { AccountID } from './account-id'\nimport { Amount } from './amount'\nimport { Blob } from './blob'\nimport { Currency } from './currency'\nimport { Hash128 } from './hash-128'\nimport { Hash160 } from './hash-160'\nimport { Hash192 } from './hash-192'\nimport { Hash256 } from './hash-256'\nimport { Issue } from './issue'\nimport { STNumber } from './st-number'\nimport { PathSet } from './path-set'\nimport { STArray } from './st-array'\nimport { STObject } from './st-object'\nimport { UInt16 } from './uint-16'\nimport { UInt32 } from './uint-32'\nimport { UInt64 } from './uint-64'\nimport { UInt8 } from './uint-8'\nimport { Vector256 } from './vector-256'\nimport { XChainBridge } from './xchain-bridge'\nimport { type SerializedType } from './serialized-type'\nimport { DEFAULT_DEFINITIONS } from '../enums'\n\nconst coreTypes: Record<string, typeof SerializedType> = {\n AccountID,\n Amount,\n Blob,\n Currency,\n Hash128,\n Hash160,\n Hash192,\n Hash256,\n Issue,\n Number: STNumber,\n PathSet,\n STArray,\n STObject,\n UInt8,\n UInt16,\n UInt32,\n UInt64,\n Vector256,\n XChainBridge,\n}\n\n// Ensures that the DEFAULT_DEFINITIONS object connects these types to fields for serializing/deserializing\n// This is done here instead of in enums/index.ts to avoid a circular dependency\n// because some of the above types depend on BinarySerializer which depends on enums/index.ts.\nDEFAULT_DEFINITIONS.associateTypes(coreTypes)\n\nexport {\n coreTypes,\n AccountID,\n Amount,\n Blob,\n Currency,\n Hash128,\n Hash160,\n Hash192,\n Hash256,\n PathSet,\n STArray,\n STObject,\n UInt8,\n UInt16,\n UInt32,\n UInt64,\n Vector256,\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n","import { BaseLedgerEntry, HasOptionalPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The unique id for the FeeSettings object https://xrpl.org/feesettings.html#feesettings-id-format\n */\nexport const FEE_SETTINGS_ID =\n '4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A651'\n\nexport interface FeeSettingsPreAmendmentFields {\n /** The transaction cost of the \"reference transaction\" in drops of XRP as hexadecimal. */\n BaseFee: string\n /** The BaseFee translated into \"fee units\". */\n ReferenceFeeUnits: number\n /** The base reserve for an account in the XRP Ledger, as drops of XRP. */\n ReserveBase: number\n /** The incremental owner reserve for owning objects, as drops of XRP. */\n ReserveIncrement: number\n}\n\nexport interface FeeSettingsPostAmendmentFields {\n /** The transaction cost of the \"reference transaction\" in drops of XRP as hexadecimal. */\n BaseFeeDrops: string\n /** The base reserve for an account in the XRP Ledger, as drops of XRP. */\n ReserveBaseDrops: string\n /** The incremental owner reserve for owning objects, as drops of XRP. */\n ReserveIncrementDrops: string\n\n ExtensionComputeLimit: number\n\n ExtensionSizeLimit: number\n}\n\nexport interface FeeSettingsBase\n extends BaseLedgerEntry,\n HasOptionalPreviousTxnID {\n LedgerEntryType: 'FeeSettings'\n /**\n * A bit-map of boolean flags for this object. No flags are defined for this type.\n */\n Flags: 0\n}\n\n/**\n * The FeeSettings object type contains the current base transaction cost and\n * reserve amounts as determined by fee voting.\n *\n * The fields will be based on the status of the `XRPFees` amendment.\n * - Before: {@link FeeSettingsPreAmendmentFields}\n * - After: {@link FeeSettingsPostAmendmentFields}\n *\n * @interface\n *\n * @category Ledger Entries\n */\ntype FeeSettings = FeeSettingsBase &\n (FeeSettingsPreAmendmentFields | FeeSettingsPostAmendmentFields)\n\nexport default FeeSettings\n","import { ValidationError } from '../../errors'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * Return escrowed XRP to the sender.\n *\n * @category Transaction Models\n */\nexport interface EscrowCancel extends BaseTransaction {\n TransactionType: 'EscrowCancel'\n /** Address of the source account that funded the escrow payment. */\n Owner: Account\n /**\n * Transaction sequence (or Ticket number) of EscrowCreate transaction that.\n * created the escrow to cancel.\n */\n OfferSequence: number | string\n}\n\n/**\n * Verify the form and type of an EscrowCancel at runtime.\n *\n * @param tx - An EscrowCancel Transaction.\n * @throws When the EscrowCancel is Malformed.\n */\nexport function validateEscrowCancel(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Owner', isAccount)\n\n if (tx.OfferSequence == null) {\n throw new ValidationError('EscrowCancel: missing OfferSequence')\n }\n\n if (\n (typeof tx.OfferSequence !== 'number' &&\n typeof tx.OfferSequence !== 'string') ||\n Number.isNaN(Number(tx.OfferSequence))\n ) {\n throw new ValidationError('EscrowCancel: OfferSequence must be a number')\n }\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash } from './_assert.ts';\nimport { Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n","import { isValidClassicAddress } from 'ripple-address-codec'\n\nimport type { Client } from '../client'\nimport { XRPLFaucetError } from '../errors'\n\nimport { FaucetWallet, getFaucetHost, getFaucetPath } from './defaultFaucets'\n\nimport { Wallet } from '.'\n\n// Interval to check an account balance\nconst INTERVAL_SECONDS = 1\n// Maximum attempts to retrieve a balance\nconst MAX_ATTEMPTS = 20\n\nexport interface FundingOptions {\n /**\n * A custom amount to fund, if undefined or null, the default amount will be 1000.\n */\n amount?: string\n /**\n * A custom host for a faucet server. On devnet, testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct server automatically. In other environments, or if you would like to customize\n * the faucet host in devnet or testnet, you should provide the host using this option.\n */\n faucetHost?: string\n /**\n * A custom path for a faucet server. On devnet,\n * testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct path automatically. In other environments,\n * or if you would like to customize the faucet path in devnet or testnet,\n * you should provide the path using this option.\n * Ex: client.fundWallet(null,{'faucet.altnet.rippletest.net', '/accounts'})\n * specifies a request to 'faucet.altnet.rippletest.net/accounts' to fund a new wallet.\n */\n faucetPath?: string\n /**\n * An optional field to indicate the use case context of the faucet transaction\n * Ex: integration test, code snippets.\n */\n usageContext?: string\n}\n\n/**\n * Parameters to pass into a faucet request to fund an XRP account.\n */\nexport interface FaucetRequestBody {\n /**\n * The address to fund. If no address is provided the faucet will fund a random account.\n */\n destination?: string\n /**\n * The total amount of XRP to fund the account with.\n */\n xrpAmount?: string\n /**\n * An optional field to indicate the use case context of the faucet transaction\n * Ex: integration test, code snippets.\n */\n usageContext?: string\n /**\n * Information about the context of where the faucet is being called from.\n * Ex: xrpl.js or xrpl-py\n */\n userAgent: string\n}\n\n/**\n * Generate a new wallet to fund if no existing wallet is provided or its address is invalid.\n *\n * @param wallet - Optional existing wallet.\n * @returns The wallet to fund.\n */\nexport function generateWalletToFund(wallet?: Wallet | null): Wallet {\n if (wallet && isValidClassicAddress(wallet.classicAddress)) {\n return wallet\n }\n return Wallet.generate()\n}\n\n/**\n * Get the starting balance of the wallet.\n *\n * @param client - The client object.\n * @param classicAddress - The classic address of the wallet.\n * @returns The starting balance.\n */\nexport async function getStartingBalance(\n client: Client,\n classicAddress: string,\n): Promise<number> {\n let startingBalance = 0\n try {\n startingBalance = Number(await client.getXrpBalance(classicAddress))\n } catch {\n // startingBalance remains '0'\n }\n return startingBalance\n}\n\nexport interface FundWalletOptions {\n faucetHost?: string\n faucetPath?: string\n amount?: string\n usageContext?: string\n}\n\n/**\n *\n * Helper function to request funding from a faucet. Should not be called directly from outside the xrpl.js library.\n *\n * @param options - See below\n * @param options.faucetHost - A custom host for a faucet server. On devnet,\n * testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct server automatically. In other environments,\n * or if you would like to customize the faucet host in devnet or testnet,\n * you should provide the host using this option.\n * @param options.faucetPath - A custom path for a faucet server. On devnet,\n * testnet, AMM devnet, and HooksV3 testnet, `fundWallet` will\n * attempt to determine the correct path automatically. In other environments,\n * or if you would like to customize the faucet path in devnet or testnet,\n * you should provide the path using this option.\n * Ex: client.fundWallet(null,{'faucet.altnet.rippletest.net', '/accounts'})\n * specifies a request to 'faucet.altnet.rippletest.net/accounts' to fund a new wallet.\n * @param options.amount - A custom amount to fund, if undefined or null, the default amount will be 1000.\n * @param client - A connection to the XRPL to send requests and transactions.\n * @param startingBalance - The amount of XRP in the given walletToFund on ledger already.\n * @param walletToFund - An existing XRPL Wallet to fund.\n * @param postBody - The content to send the faucet to indicate which address to fund, how much to fund it, and\n * where the request is coming from.\n * @returns A promise that resolves to a funded wallet and the balance within it.\n */\n// eslint-disable-next-line max-params -- Helper function created for organizational purposes\nexport async function requestFunding(\n options: FundingOptions,\n client: Client,\n startingBalance: number,\n walletToFund: Wallet,\n postBody: FaucetRequestBody,\n): Promise<{\n wallet: Wallet\n balance: number\n}> {\n const hostname = options.faucetHost ?? getFaucetHost(client)\n if (!hostname) {\n throw new XRPLFaucetError('No faucet hostname could be derived')\n }\n const pathname = options.faucetPath ?? getFaucetPath(hostname)\n const response = await fetch(`https://${hostname}${pathname}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(postBody),\n })\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- it can be anything\n const body = await response.json()\n if (\n response.ok &&\n response.headers.get('Content-Type')?.startsWith('application/json')\n ) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- It's a FaucetWallet\n const classicAddress = (body as FaucetWallet).account.classicAddress\n return processSuccessfulResponse(\n client,\n classicAddress,\n walletToFund,\n startingBalance,\n )\n }\n return processError(response, body)\n}\n\n// eslint-disable-next-line max-params -- Only used as a helper function, lines inc due to added balance.\nasync function processSuccessfulResponse(\n client: Client,\n classicAddress: string | undefined,\n walletToFund: Wallet,\n startingBalance: number,\n): Promise<{\n wallet: Wallet\n balance: number\n}> {\n if (!classicAddress) {\n return Promise.reject(\n new XRPLFaucetError(`The faucet account is undefined`),\n )\n }\n // Check at regular interval if the address is enabled on the XRPL and funded\n const updatedBalance = await getUpdatedBalance(\n client,\n classicAddress,\n startingBalance,\n )\n\n if (updatedBalance > startingBalance) {\n return {\n wallet: walletToFund,\n balance: updatedBalance,\n }\n }\n throw new XRPLFaucetError(\n `Unable to fund address with faucet after waiting ${\n INTERVAL_SECONDS * MAX_ATTEMPTS\n } seconds`,\n )\n}\n\nasync function processError(response: Response, body): Promise<never> {\n return Promise.reject(\n new XRPLFaucetError(\n `Request failed: ${JSON.stringify({\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- json response could be anything\n body: body || {},\n contentType: response.headers.get('Content-Type'),\n statusCode: response.status,\n })}`,\n ),\n )\n}\n\n/**\n * Check at regular interval if the address is enabled on the XRPL and funded.\n *\n * @param client - Client.\n * @param address - The account address to check.\n * @param originalBalance - The initial balance before the funding.\n * @returns A Promise boolean.\n */\nasync function getUpdatedBalance(\n client: Client,\n address: string,\n originalBalance: number,\n): Promise<number> {\n return new Promise((resolve, reject) => {\n let attempts = MAX_ATTEMPTS\n // eslint-disable-next-line @typescript-eslint/no-misused-promises -- Not actually misused here, different resolve\n const interval = setInterval(async () => {\n if (attempts < 0) {\n clearInterval(interval)\n resolve(originalBalance)\n } else {\n attempts -= 1\n }\n\n try {\n let newBalance\n try {\n newBalance = Number(await client.getXrpBalance(address))\n } catch {\n /* newBalance remains undefined */\n }\n\n if (newBalance > originalBalance) {\n clearInterval(interval)\n resolve(newBalance)\n }\n } catch (err) {\n clearInterval(interval)\n if (err instanceof Error) {\n reject(\n new XRPLFaucetError(\n `Unable to check if the address ${address} balance has increased. Error: ${err.message}`,\n ),\n )\n }\n reject(err)\n }\n }, INTERVAL_SECONDS * 1000)\n })\n}\n","import { Hash } from './hash'\n\n/**\n * Hash with a width of 160 bits\n */\nclass Hash160 extends Hash {\n static readonly width = 20\n static readonly ZERO_160: Hash160 = new Hash160(new Uint8Array(Hash160.width))\n\n constructor(bytes?: Uint8Array) {\n if (bytes && bytes.byteLength === 0) {\n bytes = Hash160.ZERO_160.bytes\n }\n\n super(bytes ?? Hash160.ZERO_160.bytes)\n }\n}\n\nexport { Hash160 }\n","import { ValidationError } from '../../errors'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n validateBaseTransaction,\n validateCredentialsList,\n validateRequiredField,\n MAX_AUTHORIZED_CREDENTIALS,\n} from './common'\n\n/**\n * Deliver XRP from a held payment to the recipient.\n *\n * @category Transaction Models\n */\nexport interface EscrowFinish extends BaseTransaction {\n TransactionType: 'EscrowFinish'\n /** Address of the source account that funded the held payment. */\n Owner: Account\n /**\n * Transaction sequence of EscrowCreate transaction that created the held.\n * payment to finish.\n */\n OfferSequence: number | string\n /**\n * Hex value matching the previously-supplied PREIMAGE-SHA-256.\n * crypto-condition of the held payment.\n */\n Condition?: string\n /**\n * Hex value of the PREIMAGE-SHA-256 crypto-condition fulfillment matching.\n * the held payment's Condition.\n */\n Fulfillment?: string\n /** Credentials associated with the sender of this transaction.\n * The credentials included must not be expired.\n */\n CredentialIDs?: string[]\n\n ComputationAllowance?: number\n}\n\n/**\n * Verify the form and type of an EscrowFinish at runtime.\n *\n * @param tx - An EscrowFinish Transaction.\n * @throws When the EscrowFinish is Malformed.\n */\nexport function validateEscrowFinish(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Owner', isAccount)\n\n validateCredentialsList(\n tx.CredentialIDs,\n tx.TransactionType,\n true,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n\n if (tx.OfferSequence == null) {\n throw new ValidationError('EscrowFinish: missing field OfferSequence')\n }\n\n if (\n (typeof tx.OfferSequence !== 'number' &&\n typeof tx.OfferSequence !== 'string') ||\n Number.isNaN(Number(tx.OfferSequence))\n ) {\n throw new ValidationError('EscrowFinish: OfferSequence must be a number')\n }\n\n if (tx.Condition !== undefined && typeof tx.Condition !== 'string') {\n throw new ValidationError('EscrowFinish: Condition must be a string')\n }\n\n if (tx.Fulfillment !== undefined && typeof tx.Fulfillment !== 'string') {\n throw new ValidationError('EscrowFinish: Fulfillment must be a string')\n }\n}\n","import { writeUInt32BE } from './utils'\n\n/**\n * Write a 32 bit integer to a Uint8Array\n *\n * @param uint32 32 bit integer to write to Uint8Array\n * @returns a Uint8Array with the bytes representation of uint32\n */\nfunction bytes(uint32: number): Uint8Array {\n const result = new Uint8Array(4)\n writeUInt32BE(result, uint32, 0)\n return result\n}\n\n/**\n * Maps HashPrefix names to their byte representation\n */\nconst HashPrefix: Record<string, Uint8Array> = {\n transactionID: bytes(0x54584e00),\n // transaction plus metadata\n transaction: bytes(0x534e4400),\n // account state\n accountStateEntry: bytes(0x4d4c4e00),\n // inner node in tree\n innerNode: bytes(0x4d494e00),\n // ledger master data for signing\n ledgerHeader: bytes(0x4c575200),\n // inner transaction to sign\n transactionSig: bytes(0x53545800),\n // inner transaction to sign\n transactionMultiSig: bytes(0x534d5400),\n // validation for signing\n validation: bytes(0x56414c00),\n // proposal for signing\n proposal: bytes(0x50525000),\n // payment channel claim\n paymentChannelClaim: bytes(0x434c4d00),\n // batch\n batch: bytes(0x42434800),\n}\n\nexport { HashPrefix }\n","import { sha256 as nobleImpl } from '@noble/hashes/sha256'\n\nimport wrapNoble from '../internal/wrapNoble'\n\n/**\n * Wrap noble-libs's sha256 implementation in HashFn\n */\nexport const sha256 = wrapNoble(nobleImpl)\n","import { HashPrefix } from './hash-prefixes'\nimport { Hash256 } from './types'\nimport { BytesList } from './serdes/binary-serializer'\nimport { sha512 } from '@xrplf/isomorphic/sha512'\n\n/**\n * Class for hashing with SHA512\n * @extends BytesList So SerializedTypes can write bytes to a Sha512Half\n */\nclass Sha512Half extends BytesList {\n private hash = sha512.create()\n\n /**\n * Construct a new Sha512Hash and write bytes this.hash\n *\n * @param bytes bytes to write to this.hash\n * @returns the new Sha512Hash object\n */\n static put(bytes: Uint8Array): Sha512Half {\n return new Sha512Half().put(bytes)\n }\n\n /**\n * Write bytes to an existing Sha512Hash\n *\n * @param bytes bytes to write to object\n * @returns the Sha512 object\n */\n put(bytes: Uint8Array): Sha512Half {\n this.hash.update(bytes)\n return this\n }\n\n /**\n * Compute SHA512 hash and slice in half\n *\n * @returns half of a SHA512 hash\n */\n finish256(): Uint8Array {\n return Uint8Array.from(this.hash.digest().slice(0, 32))\n }\n\n /**\n * Constructs a Hash256 from the Sha512Half object\n *\n * @returns a Hash256 object\n */\n finish(): Hash256 {\n return new Hash256(this.finish256())\n }\n}\n\n/**\n * compute SHA512 hash of a list of bytes\n *\n * @param args zero or more arguments to hash\n * @returns the sha512half hash of the arguments.\n */\nfunction sha512Half(...args: Uint8Array[]): Uint8Array {\n const hash = new Sha512Half()\n args.forEach((a) => hash.put(a))\n return hash.finish256()\n}\n\n/**\n * Construct a transactionID from a Serialized Transaction\n *\n * @param serialized bytes to hash\n * @returns a Hash256 object\n */\nfunction transactionID(serialized: Uint8Array): Hash256 {\n return new Hash256(sha512Half(HashPrefix.transactionID, serialized))\n}\n\nexport { Sha512Half, sha512Half, transactionID }\n","import { BaseTransaction } from './common'\n\n/**\n * Transaction Flags for an EnableAmendment Transaction.\n *\n * @category Transaction Flags\n */\nexport enum EnableAmendmentFlags {\n /** Support for this amendment increased to at least 80% of trusted validators starting with this ledger version. */\n tfGotMajority = 0x00010000,\n /** Support for this amendment decreased to less than 80% of trusted validators starting with this ledger version. */\n tfLostMajority = 0x00020000,\n}\n\n/**\n * Mark a change in the status of a proposed amendment when it gains majority, looses majority, or is enabled.\n *\n * @category Pseudo Transaction Models\n */\nexport interface EnableAmendment extends BaseTransaction {\n TransactionType: 'EnableAmendment'\n /** A unique identifier for the amendment. */\n Amendment: string\n /** The ledger index where this pseudo-transaction appears. */\n LedgerSequence: number\n}\n","import { ValidationError } from '../../errors'\nimport { isHex } from '../utils'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n isAccount,\n isString,\n validateOptionalField,\n Account,\n validateRequiredField,\n} from './common'\n\n/**\n * The NFTokenModify transaction modifies an NFToken's URI\n * if its tfMutable is set to true.\n */\nexport interface NFTokenModify extends BaseTransaction {\n TransactionType: 'NFTokenModify'\n /**\n * Identifies the NFTokenID of the NFToken object that the\n * offer references.\n */\n NFTokenID: string\n /**\n * Indicates the AccountID of the account that owns the corresponding NFToken.\n * Can be omitted if the owner is the account submitting this transaction\n */\n Owner?: Account\n /**\n * URI that points to the data and/or metadata associated with the NFT.\n * This field need not be an HTTP or HTTPS URL; it could be an IPFS URI, a\n * magnet link, immediate data encoded as an RFC2379 \"data\" URL, or even an\n * opaque issuer-specific encoding. The URI is NOT checked for validity, but\n * the field is limited to a maximum length of 256 bytes.\n *\n * This field must be hex-encoded. You can use `convertStringToHex` to\n * convert this field to the proper encoding.\n *\n * This field must not be an empty string. Omit it from the transaction or\n * set to `null` if you do not use it.\n */\n URI?: string | null\n}\n\n/**\n * Verify the form and type of an NFTokenModify at runtime.\n *\n * @param tx - An NFTokenModify Transaction.\n * @throws When the NFTokenModify is Malformed.\n */\nexport function validateNFTokenModify(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'NFTokenID', isString)\n validateOptionalField(tx, 'Owner', isAccount)\n validateOptionalField(tx, 'URI', isString)\n\n if (tx.URI !== undefined && typeof tx.URI === 'string') {\n if (tx.URI === '') {\n throw new ValidationError('NFTokenModify: URI must not be empty string')\n }\n if (!isHex(tx.URI)) {\n throw new ValidationError('NFTokenModify: URI must be in hex format')\n }\n }\n}\n","import { ValidationError } from '../../errors'\n\nimport { BaseTransaction, isArray, validateBaseTransaction } from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n/**\n * The NFTokenCancelOffer transaction deletes existing NFTokenOffer objects.\n * It is useful if you want to free up space on your account to lower your\n * reserve requirement.\n *\n * The transaction can be executed by the account that originally created\n * the NFTokenOffer, the account in the `Recipient` field of the NFTokenOffer\n * (if present), or any account if the NFTokenOffer has an `Expiration` and\n * the NFTokenOffer has already expired.\n */\nexport interface NFTokenCancelOffer extends BaseTransaction {\n TransactionType: 'NFTokenCancelOffer'\n /**\n * An array of identifiers of NFTokenOffer objects that should be cancelled\n * by this transaction.\n *\n * It is an error if an entry in this list points to an\n * object that is not an NFTokenOffer object. It is not an\n * error if an entry in this list points to an object that\n * does not exist. This field is required.\n */\n NFTokenOffers: string[]\n}\n\nexport interface NFTokenCancelOfferMetadata extends TransactionMetadataBase {\n // rippled 1.11.0 or later\n nftoken_ids?: string[]\n}\n\n/**\n * Verify the form and type of an NFTokenCancelOffer at runtime.\n *\n * @param tx - An NFTokenCancelOffer Transaction.\n * @throws When the NFTokenCancelOffer is Malformed.\n */\nexport function validateNFTokenCancelOffer(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (!isArray(tx.NFTokenOffers)) {\n throw new ValidationError('NFTokenCancelOffer: missing field NFTokenOffers')\n }\n\n if (tx.NFTokenOffers.length < 1) {\n throw new ValidationError('NFTokenCancelOffer: empty field NFTokenOffers')\n }\n}\n","import { HEX_REGEX } from '@xrplf/isomorphic/utils'\n\nimport { ValidationError } from '../../errors'\n\nimport {\n BaseTransaction,\n isNumber,\n isString,\n validateBaseTransaction,\n validateCredentialType,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\nconst MAX_URI_LENGTH = 256\n\n/**\n * Creates a Credential object. It must be sent by the issuer.\n *\n * @category Transaction Models\n * */\nexport interface CredentialCreate extends BaseTransaction {\n TransactionType: 'CredentialCreate'\n\n /** The issuer of the credential. */\n Account: string\n\n /** The subject of the credential. */\n Subject: string\n\n /** A hex-encoded value to identify the type of credential from the issuer. */\n CredentialType: string\n\n /** Credential expiration. */\n Expiration?: number\n\n /** Additional data about the credential (such as a link to the VC document). */\n URI?: string\n}\n\n/**\n * Verify the form and type of a CredentialCreate at runtime.\n *\n * @param tx - A CredentialCreate Transaction.\n * @throws When the CredentialCreate is Malformed.\n */\nexport function validateCredentialCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Account', isString)\n\n validateRequiredField(tx, 'Subject', isString)\n\n validateCredentialType(tx)\n\n validateOptionalField(tx, 'Expiration', isNumber)\n\n validateURI(tx.URI)\n}\n\nfunction validateURI(URI: unknown): void {\n if (URI === undefined) {\n return\n }\n\n if (typeof URI !== 'string') {\n throw new ValidationError('CredentialCreate: invalid field URI')\n }\n\n if (URI.length === 0) {\n throw new ValidationError('CredentialCreate: URI cannot be an empty string')\n } else if (URI.length > MAX_URI_LENGTH) {\n throw new ValidationError(\n `CredentialCreate: URI length must be <= ${MAX_URI_LENGTH}`,\n )\n }\n\n if (!HEX_REGEX.test(URI)) {\n throw new ValidationError('CredentialCreate: URI must be encoded in hex')\n }\n}\n","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport {\n aInRange,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\ntype Hex = string | Uint8Array;\n\nexport type CurveType = {\n P: bigint; // finite field prime\n nByteLength: number;\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n a: bigint;\n montgomeryBits: number;\n powPminus2?: (x: bigint) => bigint;\n xyToU?: (x: bigint, y: bigint) => bigint;\n Gu: bigint;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n};\n\nexport type CurveFn = {\n scalarMult: (scalar: Hex, u: Hex) => Uint8Array;\n scalarMultBase: (scalar: Hex) => Uint8Array;\n getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n utils: { randomPrivateKey: () => Uint8Array };\n GuBytes: Uint8Array;\n};\n\nfunction validateOpts(curve: CurveType) {\n validateObject(\n curve,\n {\n a: 'bigint',\n },\n {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n }\n );\n // Set defaults\n return Object.freeze({ ...curve } as const);\n}\n\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n: bigint) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));\n\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u: bigint, scalar: bigint): bigint {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw: [bigint, bigint];\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n\n function encodeUCoordinate(u: bigint): Uint8Array {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n\n function decodeUCoordinate(uEnc: Hex): bigint {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32) u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n: Hex): bigint {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen) {\n let valid = '' + montgomeryBytes + ' or ' + fieldLen;\n throw new Error('invalid scalar, expected ' + valid + ' bytes, got ' + len);\n }\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar: Hex, u: Hex): Uint8Array {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar: Hex): Uint8Array {\n return scalarMult(scalar, GuBytes);\n }\n\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n","export * from './submit'\n\nexport * from './utils'\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isAmount,\n isNumber,\n isString,\n isXChainBridge,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainAddAccountCreateAttestation transaction provides an attestation\n * from a witness server that a {@link XChainAccountCreateCommit} transaction\n * occurred on the other chain.\n *\n * @category Transaction Models\n */\nexport interface XChainAddAccountCreateAttestation extends BaseTransaction {\n TransactionType: 'XChainAddAccountCreateAttestation'\n\n /**\n * The amount committed by the {@link XChainAccountCreateCommit} transaction\n * on the source chain.\n */\n Amount: Amount\n\n /**\n * The account that should receive this signer's share of the SignatureReward.\n */\n AttestationRewardAccount: Account\n\n /**\n * The account on the door account's signer list that is signing the transaction.\n */\n AttestationSignerAccount: Account\n\n /**\n * The destination account for the funds on the destination chain.\n */\n Destination: Account\n\n /**\n * The account on the source chain that submitted the {@link XChainAccountCreateCommit}\n * transaction that triggered the event associated with the attestation.\n */\n OtherChainSource: Account\n\n /**\n * The public key used to verify the signature.\n */\n PublicKey: string\n\n /**\n * The signature attesting to the event on the other chain.\n */\n Signature: string\n\n /**\n * The signature reward paid in the {@link XChainAccountCreateCommit} transaction.\n */\n SignatureReward: Amount\n\n /**\n * A boolean representing the chain where the event occurred.\n */\n WasLockingChainSend: 0 | 1\n\n /**\n * The counter that represents the order that the claims must be processed in.\n */\n XChainAccountCreateCount: number | string\n\n /**\n * The bridge associated with the attestation.\n */\n XChainBridge: XChainBridge\n}\n\n/**\n * Verify the form and type of an XChainAddAccountCreateAttestation at runtime.\n *\n * @param tx - An XChainAddAccountCreateAttestation Transaction.\n * @throws When the XChainAddAccountCreateAttestation is malformed.\n */\nexport function validateXChainAddAccountCreateAttestation(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Amount', isAmount)\n\n validateRequiredField(tx, 'AttestationRewardAccount', isAccount)\n\n validateRequiredField(tx, 'AttestationSignerAccount', isAccount)\n\n validateRequiredField(tx, 'Destination', isAccount)\n\n validateRequiredField(tx, 'OtherChainSource', isAccount)\n\n validateRequiredField(tx, 'PublicKey', isString)\n\n validateRequiredField(tx, 'Signature', isString)\n\n validateRequiredField(tx, 'SignatureReward', isAmount)\n\n validateRequiredField(\n tx,\n 'WasLockingChainSend',\n (inp: unknown): inp is 0 | 1 => inp === 0 || inp === 1,\n )\n\n validateRequiredField(\n tx,\n 'XChainAccountCreateCount',\n (inp: unknown): inp is number | string => isNumber(inp) || isString(inp),\n )\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n}\n","import { BaseLedgerEntry, HasOptionalPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The unique id for the Amendments object https://xrpl.org/amendments-object.html#amendments-id-format\n */\nexport const AMENDMENTS_ID =\n '7DB0788C020F02780A673DC74757F23823FA3014C1866E72CC4CD8B226CD6EF4'\n\nexport interface Majority {\n Majority: {\n /** The Amendment ID of the pending amendment. */\n Amendment: string\n /**\n * The `close_time` field of the ledger version where this amendment most\n * recently gained a majority.\n */\n CloseTime: number\n }\n}\n\n/**\n * The Amendments object type contains a list of Amendments that are currently\n * active.\n *\n * @category Ledger Entries\n */\nexport default interface Amendments\n extends BaseLedgerEntry,\n HasOptionalPreviousTxnID {\n LedgerEntryType: 'Amendments'\n /**\n * Array of 256-bit amendment IDs for all currently-enabled amendments. If\n * omitted, there are no enabled amendments.\n */\n Amendments?: string[]\n /**\n * Array of objects describing the status of amendments that have majority\n * support but are not yet enabled. If omitted, there are no pending\n * amendments with majority support.\n */\n Majorities?: Majority[]\n /**\n * A bit-map of boolean flags. No flags are defined for the Amendments object\n * type, so this value is always 0.\n */\n Flags: 0\n}\n","import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'\n\n/**\n * If an address is an X-Address, converts it to a classic address.\n *\n * @param account - A classic address or X-address.\n * @returns The account's classic address.\n * @throws Error if the X-Address has an associated tag.\n */\nexport function ensureClassicAddress(account: string): string {\n if (isValidXAddress(account)) {\n const { classicAddress, tag } = xAddressToClassicAddress(account)\n\n /*\n * Except for special cases, X-addresses used for requests\n * must not have an embedded tag. In other words,\n * `tag` should be `false`.\n */\n if (tag !== false) {\n throw new Error(\n 'This command does not support the use of a tag. Use an address without a tag.',\n )\n }\n\n // For rippled requests that use an account, always use a classic address.\n return classicAddress\n }\n return account\n}\n","import { FieldInstance } from '../enums'\nimport { type SerializedType } from '../types/serialized-type'\nimport { bytesToHex, concat } from '@xrplf/isomorphic/utils'\n\n/**\n * Bytes list is a collection of Uint8Array objects\n */\nclass BytesList {\n private bytesArray: Array<Uint8Array> = []\n\n /**\n * Get the total number of bytes in the BytesList\n *\n * @return the number of bytes\n */\n public getLength(): number {\n return concat(this.bytesArray).byteLength\n }\n\n /**\n * Put bytes in the BytesList\n *\n * @param bytesArg A Uint8Array\n * @return this BytesList\n */\n public put(bytesArg: Uint8Array): BytesList {\n const bytes = Uint8Array.from(bytesArg) // Temporary, to catch instances of Uint8Array being passed in\n this.bytesArray.push(bytes)\n return this\n }\n\n /**\n * Write this BytesList to the back of another bytes list\n *\n * @param list The BytesList to write to\n */\n public toBytesSink(list: BytesList): void {\n list.put(this.toBytes())\n }\n\n public toBytes(): Uint8Array {\n return concat(this.bytesArray)\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes())\n }\n}\n\n/**\n * BinarySerializer is used to write fields and values to Uint8Arrays\n */\nclass BinarySerializer {\n private sink: BytesList = new BytesList()\n\n constructor(sink: BytesList) {\n this.sink = sink\n }\n\n /**\n * Write a value to this BinarySerializer\n *\n * @param value a SerializedType value\n */\n write(value: SerializedType): void {\n value.toBytesSink(this.sink)\n }\n\n /**\n * Write bytes to this BinarySerializer\n *\n * @param bytes the bytes to write\n */\n put(bytes: Uint8Array): void {\n this.sink.put(bytes)\n }\n\n /**\n * Write a value of a given type to this BinarySerializer\n *\n * @param type the type to write\n * @param value a value of that type\n */\n writeType(type: typeof SerializedType, value: SerializedType): void {\n this.write(type.from(value))\n }\n\n /**\n * Write BytesList to this BinarySerializer\n *\n * @param bl BytesList to write to BinarySerializer\n */\n writeBytesList(bl: BytesList): void {\n bl.toBytesSink(this.sink)\n }\n\n /**\n * Calculate the header of Variable Length encoded bytes\n *\n * @param length the length of the bytes\n */\n private encodeVariableLength(length: number): Uint8Array {\n const lenBytes = new Uint8Array(3)\n if (length <= 192) {\n lenBytes[0] = length\n return lenBytes.slice(0, 1)\n } else if (length <= 12480) {\n length -= 193\n lenBytes[0] = 193 + (length >>> 8)\n lenBytes[1] = length & 0xff\n return lenBytes.slice(0, 2)\n } else if (length <= 918744) {\n length -= 12481\n lenBytes[0] = 241 + (length >>> 16)\n lenBytes[1] = (length >> 8) & 0xff\n lenBytes[2] = length & 0xff\n return lenBytes.slice(0, 3)\n }\n throw new Error('Overflow error')\n }\n\n /**\n * Write field and value to BinarySerializer\n *\n * @param field field to write to BinarySerializer\n * @param value value to write to BinarySerializer\n */\n writeFieldAndValue(\n field: FieldInstance,\n value: SerializedType,\n isUnlModifyWorkaround = false,\n ): void {\n const associatedValue = field.associatedType.from(value)\n if (associatedValue.toBytesSink === undefined || field.name === undefined) {\n throw new Error()\n }\n\n this.sink.put(field.header)\n\n if (field.isVariableLengthEncoded) {\n this.writeLengthEncoded(associatedValue, isUnlModifyWorkaround)\n } else {\n associatedValue.toBytesSink(this.sink)\n }\n }\n\n /**\n * Write a variable length encoded value to the BinarySerializer\n *\n * @param value length encoded value to write to BytesList\n */\n public writeLengthEncoded(\n value: SerializedType,\n isUnlModifyWorkaround = false,\n ): void {\n const bytes = new BytesList()\n if (!isUnlModifyWorkaround) {\n // this part doesn't happen for the Account field in a UNLModify transaction\n value.toBytesSink(bytes)\n }\n this.put(this.encodeVariableLength(bytes.getLength()))\n this.writeBytesList(bytes)\n }\n}\n\nexport { BytesList, BinarySerializer }\n","import {\n bytesToHex,\n concat,\n hexToBytes,\n randomBytes,\n} from '@xrplf/isomorphic/utils'\n\nfunction randomEntropy(): Uint8Array {\n return randomBytes(16)\n}\n\nfunction calculateChecksum(position: number, value: number): number {\n return (value * (position * 2 + 1)) % 9\n}\n\nfunction checkChecksum(\n position: number,\n value: number | string,\n checksum?: number,\n): boolean {\n let normalizedChecksum: number\n let normalizedValue: number\n\n if (typeof value === 'string') {\n if (value.length !== 6) {\n throw new Error('value must have a length of 6')\n }\n normalizedChecksum = parseInt(value.slice(5), 10)\n normalizedValue = parseInt(value.slice(0, 5), 10)\n } else {\n if (typeof checksum !== 'number') {\n throw new Error('checksum must be a number when value is a number')\n }\n normalizedChecksum = checksum\n normalizedValue = value\n }\n return (normalizedValue * (position * 2 + 1)) % 9 === normalizedChecksum\n}\n\nfunction entropyToSecret(entropy: Uint8Array): string[] {\n const len = new Array(Math.ceil(entropy.length / 2))\n const chunks = Array.from(len, (_a, chunk) => {\n const buffChunk = entropy.slice(chunk * 2, (chunk + 1) * 2)\n const no = parseInt(bytesToHex(buffChunk), 16)\n const fill = '0'.repeat(5 - String(no).length)\n return fill + String(no) + String(calculateChecksum(chunk, no))\n })\n if (chunks.length !== 8) {\n throw new Error('Chucks must have 8 digits')\n }\n return chunks\n}\n\nfunction randomSecret(): string[] {\n return entropyToSecret(randomEntropy())\n}\n\nfunction secretToEntropy(secret: string[]): Uint8Array {\n return concat(\n secret.map((chunk, i) => {\n const no = Number(chunk.slice(0, 5))\n const checksum = Number(chunk.slice(5))\n if (chunk.length !== 6) {\n throw new Error('Invalid secret: number invalid')\n }\n if (!checkChecksum(i, no, checksum)) {\n throw new Error('Invalid secret part: checksum invalid')\n }\n const hex = `0000${no.toString(16)}`.slice(-4)\n return hexToBytes(hex)\n }),\n )\n}\n\nfunction parseSecretString(secret: string): string[] {\n const normalizedSecret = secret.replace(/[^0-9]/gu, '')\n if (normalizedSecret.length !== 48) {\n throw new Error(\n 'Invalid secret string (should contain 8 blocks of 6 digits',\n )\n }\n return Array.from(new Array(8), (_a, index) => {\n return normalizedSecret.slice(index * 6, (index + 1) * 6)\n })\n}\n\nexport {\n randomEntropy,\n randomSecret,\n entropyToSecret,\n secretToEntropy,\n calculateChecksum,\n checkChecksum,\n parseSecretString,\n}\n","export const TYPE_WIDTH = 2 // UInt16\nexport const LEDGER_ENTRY_WIDTH = 2 // UInt16\nexport const TRANSACTION_TYPE_WIDTH = 2 // UInt16\nexport const TRANSACTION_RESULT_WIDTH = 1 // UInt8\nexport const DELEGATABLE_PERMISSIONS_WIDTH = 4 // UInt32\n","import { coreTypes } from './types'\nimport BigNumber from 'bignumber.js'\nimport { bytesToHex, hexToBytes } from '@xrplf/isomorphic/utils'\n\n/**\n * class for encoding and decoding quality\n */\nclass quality {\n /**\n * Encode quality amount\n *\n * @param arg string representation of an amount\n * @returns Serialized quality\n */\n static encode(quality: string): Uint8Array {\n const decimal = BigNumber(quality)\n const exponent = (decimal?.e || 0) - 15\n const qualityString = decimal.times(`1e${-exponent}`).abs().toString()\n const bytes = coreTypes.UInt64.from(BigInt(qualityString)).toBytes()\n bytes[0] = exponent + 100\n return bytes\n }\n\n /**\n * Decode quality amount\n *\n * @param arg hex-string denoting serialized quality\n * @returns deserialized quality\n */\n static decode(quality: string): BigNumber {\n const bytes = hexToBytes(quality).slice(-8)\n const exponent = bytes[0] - 100\n const mantissa = new BigNumber(`0x${bytesToHex(bytes.slice(1))}`)\n return mantissa.times(`1e${exponent}`)\n }\n}\n\nexport { quality }\n","import { DEFAULT_DEFINITIONS, XrplDefinitionsBase } from '../enums'\nimport { SerializedType, JsonObject } from './serialized-type'\nimport { STObject } from './st-object'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { concat } from '@xrplf/isomorphic/utils'\n\nconst ARRAY_END_MARKER = Uint8Array.from([0xf1])\nconst ARRAY_END_MARKER_NAME = 'ArrayEndMarker'\n\nconst OBJECT_END_MARKER = Uint8Array.from([0xe1])\n\n/**\n * TypeGuard for Array<JsonObject>\n */\nfunction isObjects(args): args is Array<JsonObject> {\n return (\n Array.isArray(args) &&\n args.every(\n (arg) =>\n typeof arg === 'object' &&\n Object.keys(arg).length === 1 &&\n typeof Object.values(arg)[0] === 'object',\n )\n )\n}\n\n/**\n * Class for serializing and deserializing Arrays of Objects\n */\nclass STArray extends SerializedType {\n /**\n * Construct an STArray from a BinaryParser\n *\n * @param parser BinaryParser to parse an STArray from\n * @returns An STArray Object\n */\n static fromParser(parser: BinaryParser): STArray {\n const bytes: Array<Uint8Array> = []\n\n while (!parser.end()) {\n const field = parser.readField()\n if (field.name === ARRAY_END_MARKER_NAME) {\n break\n }\n\n bytes.push(\n field.header,\n parser.readFieldValue(field).toBytes(),\n OBJECT_END_MARKER,\n )\n }\n\n bytes.push(ARRAY_END_MARKER)\n return new STArray(concat(bytes))\n }\n\n /**\n * Construct an STArray from an Array of JSON Objects\n *\n * @param value STArray or Array of Objects to parse into an STArray\n * @param definitions optional, types and values to use to encode/decode a transaction\n * @returns An STArray object\n */\n static from<T extends STArray | Array<JsonObject>>(\n value: T,\n definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n ): STArray {\n if (value instanceof STArray) {\n return value\n }\n\n if (isObjects(value)) {\n const bytes: Array<Uint8Array> = []\n value.forEach((obj) => {\n bytes.push(STObject.from(obj, undefined, definitions).toBytes())\n })\n\n bytes.push(ARRAY_END_MARKER)\n return new STArray(concat(bytes))\n }\n\n throw new Error('Cannot construct STArray from value given')\n }\n\n /**\n * Return the JSON representation of this.bytes\n *\n * @param definitions optional, types and values to use to encode/decode a transaction\n * @returns An Array of JSON objects\n */\n toJSON(\n definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n ): Array<JsonObject> {\n const result: Array<JsonObject> = []\n\n const arrayParser = new BinaryParser(this.toString(), definitions)\n\n while (!arrayParser.end()) {\n const field = arrayParser.readField()\n if (field.name === ARRAY_END_MARKER_NAME) {\n break\n }\n\n const outer = {}\n outer[field.name] = STObject.fromParser(arrayParser).toJSON(definitions)\n result.push(outer)\n }\n\n return result\n }\n}\n\nexport { STArray }\n","import { Hash } from './hash'\n\n/**\n * Hash with a width of 256 bits\n */\nclass Hash256 extends Hash {\n static readonly width = 32\n static readonly ZERO_256 = new Hash256(new Uint8Array(Hash256.width))\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? Hash256.ZERO_256.bytes)\n }\n}\n\nexport { Hash256 }\n","import { ValidationError } from '../../errors'\n\nimport {\n BaseTransaction,\n isString,\n validateBaseTransaction,\n validateOptionalField,\n} from './common'\n\n// TODO: add docs\n\n/**\n * @category Transaction Models\n */\nexport interface DIDSet extends BaseTransaction {\n TransactionType: 'DIDSet'\n\n Data?: string\n\n DIDDocument?: string\n\n URI?: string\n}\n\n/**\n * Verify the form and type of a DIDSet at runtime.\n *\n * @param tx - A DIDSet Transaction.\n * @throws When the DIDSet is malformed.\n */\nexport function validateDIDSet(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateOptionalField(tx, 'Data', isString)\n\n validateOptionalField(tx, 'DIDDocument', isString)\n\n validateOptionalField(tx, 'URI', isString)\n\n if (\n tx.Data === undefined &&\n tx.DIDDocument === undefined &&\n tx.URI === undefined\n ) {\n throw new ValidationError(\n 'DIDSet: Must have at least one of `Data`, `DIDDocument`, and `URI`',\n )\n }\n}\n","import { Amount, XChainBridge } from '../common'\n\nimport {\n Account,\n BaseTransaction,\n isAccount,\n isAmount,\n isNumber,\n isString,\n isXChainBridge,\n validateBaseTransaction,\n validateOptionalField,\n validateRequiredField,\n} from './common'\n\n/**\n * The XChainClaim transaction completes a cross-chain transfer of value. It\n * allows a user to claim the value on the destination chain - the equivalent\n * of the value locked on the source chain.\n *\n * @category Transaction Models\n */\nexport interface XChainClaim extends BaseTransaction {\n TransactionType: 'XChainClaim'\n\n /**\n * The bridge to use for the transfer.\n */\n XChainBridge: XChainBridge\n\n /**\n * The unique integer ID for the cross-chain transfer that was referenced in the\n * corresponding {@link XChainCommit} transaction.\n */\n XChainClaimID: number | string\n\n /**\n * The destination account on the destination chain. It must exist or the\n * transaction will fail. However, if the transaction fails in this case, the\n * sequence number and collected signatures won't be destroyed, and the\n * transaction can be rerun with a different destination.\n */\n Destination: Account\n\n /**\n * An integer destination tag.\n */\n DestinationTag?: number\n\n /**\n * The amount to claim on the destination chain. This must match the amount\n * attested to on the attestations associated with this XChainClaimID.\n */\n Amount: Amount\n}\n\n/**\n * Verify the form and type of an XChainClaim at runtime.\n *\n * @param tx - An XChainClaim Transaction.\n * @throws When the XChainClaim is malformed.\n */\nexport function validateXChainClaim(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'XChainBridge', isXChainBridge)\n\n validateRequiredField(\n tx,\n 'XChainClaimID',\n (inp: unknown): inp is number | string => isNumber(inp) || isString(inp),\n )\n\n validateRequiredField(tx, 'Destination', isAccount)\n\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n validateRequiredField(tx, 'Amount', isAmount)\n}\n","import { BaseTransaction, validateBaseTransaction } from './common'\n\n// TODO: add docs\n\n/**\n * @category Transaction Models\n */\nexport interface DIDDelete extends BaseTransaction {\n TransactionType: 'DIDDelete'\n}\n\n/**\n * Verify the form and type of a DIDDelete at runtime.\n *\n * @param tx - A DIDDelete Transaction.\n * @throws When the DIDDelete is malformed.\n */\nexport function validateDIDDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n}\n","import { coreTypes } from './types'\nimport { HashPrefix } from './hash-prefixes'\nimport { Sha512Half } from './hashes'\nimport { Hash256 } from './types/hash-256'\nimport { BytesList } from './serdes/binary-serializer'\n\n/**\n * Abstract class describing a SHAMapNode\n */\nabstract class ShaMapNode {\n abstract hashPrefix(): Uint8Array\n abstract isLeaf(): boolean\n abstract isInner(): boolean\n abstract toBytesSink(list: BytesList): void\n abstract hash(): Hash256\n}\n\n/**\n * Class describing a Leaf of SHAMap\n */\nclass ShaMapLeaf extends ShaMapNode {\n constructor(public index: Hash256, public item?: ShaMapNode) {\n super()\n }\n\n /**\n * @returns true as ShaMapLeaf is a leaf node\n */\n isLeaf(): boolean {\n return true\n }\n\n /**\n * @returns false as ShaMapLeaf is not an inner node\n */\n isInner(): boolean {\n return false\n }\n\n /**\n * Get the prefix of the this.item\n *\n * @returns The hash prefix, unless this.item is undefined, then it returns an empty Uint8Array\n */\n hashPrefix(): Uint8Array {\n return this.item === undefined ? new Uint8Array(0) : this.item.hashPrefix()\n }\n\n /**\n * Hash the bytes representation of this\n *\n * @returns hash of this.item concatenated with this.index\n */\n hash(): Hash256 {\n const hash = Sha512Half.put(this.hashPrefix())\n this.toBytesSink(hash)\n return hash.finish()\n }\n\n /**\n * Write the bytes representation of this to a BytesList\n * @param list BytesList to write bytes to\n */\n toBytesSink(list: BytesList): void {\n if (this.item !== undefined) {\n this.item.toBytesSink(list)\n }\n this.index.toBytesSink(list)\n }\n}\n\n/**\n * Class defining an Inner Node of a SHAMap\n */\nclass ShaMapInner extends ShaMapNode {\n private slotBits = 0\n private branches: Array<ShaMapNode> = Array(16)\n\n constructor(private depth: number = 0) {\n super()\n }\n\n /**\n * @returns true as ShaMapInner is an inner node\n */\n isInner(): boolean {\n return true\n }\n\n /**\n * @returns false as ShaMapInner is not a leaf node\n */\n isLeaf(): boolean {\n return false\n }\n\n /**\n * Get the hash prefix for this node\n *\n * @returns hash prefix describing an inner node\n */\n hashPrefix(): Uint8Array {\n return HashPrefix.innerNode\n }\n\n /**\n * Set a branch of this node to be another node\n *\n * @param slot Slot to add branch to this.branches\n * @param branch Branch to add\n */\n setBranch(slot: number, branch: ShaMapNode): void {\n this.slotBits = this.slotBits | (1 << slot)\n this.branches[slot] = branch\n }\n\n /**\n * @returns true if node is empty\n */\n empty(): boolean {\n return this.slotBits === 0\n }\n\n /**\n * Compute the hash of this node\n *\n * @returns The hash of this node\n */\n hash(): Hash256 {\n if (this.empty()) {\n return (coreTypes.Hash256 as typeof Hash256).ZERO_256\n }\n const hash = Sha512Half.put(this.hashPrefix())\n this.toBytesSink(hash)\n return hash.finish()\n }\n\n /**\n * Writes the bytes representation of this node to a BytesList\n *\n * @param list BytesList to write bytes to\n */\n toBytesSink(list: BytesList): void {\n for (let i = 0; i < this.branches.length; i++) {\n const branch = this.branches[i]\n const hash = branch\n ? branch.hash()\n : (coreTypes.Hash256 as typeof Hash256).ZERO_256\n hash.toBytesSink(list)\n }\n }\n\n /**\n * Add item to the SHAMap\n *\n * @param index Hash of the index of the item being inserted\n * @param item Item to insert in the map\n * @param leaf Leaf node to insert when branch doesn't exist\n */\n addItem(index?: Hash256, item?: ShaMapNode, leaf?: ShaMapLeaf): void {\n if (index === undefined) {\n throw new Error()\n }\n if (index !== undefined) {\n const nibble = index.nibblet(this.depth)\n const existing = this.branches[nibble]\n\n if (existing === undefined) {\n this.setBranch(nibble, leaf || new ShaMapLeaf(index, item))\n } else if (existing instanceof ShaMapLeaf) {\n const newInner = new ShaMapInner(this.depth + 1)\n newInner.addItem(existing.index, undefined, existing)\n newInner.addItem(index, item, leaf)\n this.setBranch(nibble, newInner)\n } else if (existing instanceof ShaMapInner) {\n existing.addItem(index, item, leaf)\n } else {\n throw new Error('invalid ShaMap.addItem call')\n }\n }\n }\n}\n\nclass ShaMap extends ShaMapInner {}\n\nexport { ShaMap, ShaMapNode, ShaMapLeaf }\n","import { classicAddressToXAddress } from 'ripple-address-codec'\nimport { deriveKeypair, deriveAddress } from 'ripple-keypairs'\n\n/**\n * Derive an X-Address from a public key and a destination tag.\n *\n * @param options - Public key and destination tag to encode as an X-Address.\n * @param options.publicKey - The public key corresponding to an address.\n * @param options.tag - A destination tag to encode into an X-address. False indicates no destination tag.\n * @param options.test - Whether this address is for use in Testnet.\n * @returns X-Address.\n * @category Utilities\n */\nfunction deriveXAddress(options: {\n publicKey: string\n tag: number | false\n test: boolean\n}): string {\n const classicAddress = deriveAddress(options.publicKey)\n return classicAddressToXAddress(classicAddress, options.tag, options.test)\n}\n\nexport { deriveKeypair, deriveAddress, deriveXAddress }\n","import { BaseLedgerEntry, HasPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The AccountRoot object type describes a single account, its settings, and\n * XRP balance.\n *\n * @category Ledger Entries\n */\nexport default interface AccountRoot extends BaseLedgerEntry, HasPreviousTxnID {\n LedgerEntryType: 'AccountRoot'\n /** The identifying (classic) address of this account. */\n Account: string\n /** The account's current XRP balance in drops, represented as a string. */\n Balance: string\n /** A bit-map of boolean flags enabled for this account. */\n Flags: number\n /**\n * The number of objects this account owns in the ledger, which contributes\n * to its owner reserve.\n */\n OwnerCount: number\n /** The sequence number of the next valid transaction for this account. */\n Sequence: number\n /**\n * The identifying hash of the transaction most recently sent by this\n * account. This field must be enabled to use the AccountTxnID transaction\n * field. To enable it, send an AccountSet transaction with the.\n * `asfAccountTxnID` flag enabled.\n */\n AccountTxnID?: string\n /**\n * The ledger entry ID of the corresponding AMM ledger entry.\n * Set during account creation; cannot be modified.\n * If present, indicates that this is a special AMM AccountRoot; always omitted on non-AMM accounts.\n */\n AMMID?: string\n /**\n * A domain associated with this account. In JSON, this is the hexadecimal\n * for the ASCII representation of the domain.\n */\n Domain?: string\n /** The md5 hash of an email address. */\n EmailHash?: string\n /**\n * A public key that may be used to send encrypted messages to this account\n * in JSON, uses hexadecimal.\n */\n MessageKey?: string\n /**\n * The address of a key pair that can be used to sign transactions for this\n * account instead of the master key. Use a SetRegularKey transaction to\n * change this value.\n */\n RegularKey?: string\n /**\n * How many Tickets this account owns in the ledger. This is updated\n * automatically to ensure that the account stays within the hard limit of 250.\n * Tickets at a time.\n */\n TicketCount?: number\n /**\n * How many significant digits to use for exchange rates of Offers involving\n * currencies issued by this address. Valid values are 3 to 15, inclusive.\n */\n TickSize?: number\n /**\n * A transfer fee to charge other users for sending currency issued by this\n * account to each other.\n */\n TransferRate?: number\n /** An arbitrary 256-bit value that users can set. */\n WalletLocator?: string\n /** Total NFTokens this account's issued that have been burned. This number is always equal or less than MintedNFTokens. */\n BurnedNFTokens?: number\n /** The sequence that the account first minted an NFToken */\n FirstNFTokenSequence?: number\n /** Total NFTokens have been minted by and on behalf of this account. */\n MintedNFTokens?: number\n /** Another account that can mint NFTokens on behalf of this account. */\n NFTokenMinter?: string\n}\n\n/**\n * A boolean map of AccountRootFlags for simplified code checking AccountRoot settings.\n * For submitting settings flags to the ledger, use AccountRootFlags instead.\n */\nexport interface AccountRootFlagsInterface {\n /**\n * The account has used its free SetRegularKey transaction.\n */\n lsfPasswordSpent?: boolean\n /**\n * Requires incoming payments to specify a Destination Tag.\n */\n lsfRequireDestTag?: boolean\n /**\n * This account must individually approve other users for those users to hold this account's issued currencies.\n */\n lsfRequireAuth?: boolean\n /**\n * Client applications should not send XRP to this account. Not enforced by rippled.\n */\n lsfDisallowXRP?: boolean\n /**\n * Disallows use of the master key to sign transactions for this account.\n */\n lsfDisableMaster?: boolean\n /**\n * This address cannot freeze trust lines connected to it. Once enabled, cannot be disabled.\n */\n lsfNoFreeze?: boolean\n /**\n * All assets issued by this address are frozen.\n */\n lsfGlobalFreeze?: boolean\n /**\n * Enable rippling on this address's trust lines by default. Required for issuing addresses; discouraged for others.\n */\n lsfDefaultRipple?: boolean\n /**\n * This account can only receive funds from transactions it sends, and from preauthorized accounts.\n * (It has DepositAuth enabled.)\n */\n lsfDepositAuth?: boolean\n /**\n * This account is an Automated Market Maker (AMM) instance.\n */\n lsfAMM?: boolean\n /**\n * Disallow incoming NFTOffers from other accounts.\n */\n lsfDisallowIncomingNFTokenOffer?: boolean\n /**\n * Disallow incoming Checks from other accounts.\n */\n lsfDisallowIncomingCheck?: boolean\n /**\n * Disallow incoming PayChannels from other accounts.\n */\n lsfDisallowIncomingPayChan?: boolean\n /**\n * Disallow incoming Trustlines from other accounts.\n */\n lsfDisallowIncomingTrustline?: boolean\n /**\n * This address can claw back issued IOUs. Once enabled, cannot be disabled.\n */\n lsfAllowTrustLineClawback?: boolean\n}\n\nexport enum AccountRootFlags {\n /**\n * The account has used its free SetRegularKey transaction.\n */\n lsfPasswordSpent = 0x00010000,\n /**\n * Requires incoming payments to specify a Destination Tag.\n */\n lsfRequireDestTag = 0x00020000,\n /**\n * This account must individually approve other users for those users to hold this account's issued currencies.\n */\n lsfRequireAuth = 0x00040000,\n /**\n * Client applications should not send XRP to this account. Not enforced by rippled.\n */\n lsfDisallowXRP = 0x00080000,\n /**\n * Disallows use of the master key to sign transactions for this account.\n */\n lsfDisableMaster = 0x00100000,\n /**\n * This address cannot freeze trust lines connected to it. Once enabled, cannot be disabled.\n */\n lsfNoFreeze = 0x00200000,\n /**\n * All assets issued by this address are frozen.\n */\n lsfGlobalFreeze = 0x00400000,\n /**\n * Enable rippling on this address's trust lines by default. Required for issuing addresses; discouraged for others.\n */\n lsfDefaultRipple = 0x00800000,\n /**\n * This account can only receive funds from transactions it sends, and from preauthorized accounts.\n * (It has DepositAuth enabled.)\n */\n lsfDepositAuth = 0x01000000,\n /**\n * This account is an Automated Market Maker (AMM) instance.\n */\n lsfAMM = 0x02000000,\n /**\n * Disallow incoming NFTOffers from other accounts.\n */\n lsfDisallowIncomingNFTokenOffer = 0x04000000,\n /**\n * Disallow incoming Checks from other accounts.\n */\n lsfDisallowIncomingCheck = 0x08000000,\n /**\n * Disallow incoming PayChannels from other accounts.\n */\n lsfDisallowIncomingPayChan = 0x10000000,\n /**\n * Disallow incoming Trustlines from other accounts.\n */\n lsfDisallowIncomingTrustline = 0x20000000,\n /**\n * This address can claw back issued IOUs. Once enabled, cannot be disabled.\n */\n lsfAllowTrustLineClawback = 0x80000000,\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { type AffinePoint, type Group, pippenger } from './abstract/curve.js';\nimport { type CurveFn, type ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport {\n createHasher,\n expand_message_xmd,\n type htfBasicOpts,\n type HTFMethod,\n} from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery, type CurveFn as XCurveFn } from './abstract/montgomery.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n type Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>): RistPoint {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n static msm(points: RistPoint[], scalars: bigint[]): RistPoint {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint: typeof RistPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts): RistPoint => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint =\n hashToRistretto255; // legacy\n","/**\n * RIPEMD-160 legacy hash function.\n * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n * @module\n */\nimport { HashMD } from './_md.ts';\nimport { rotl, wrapConstructor, type CHash } from './utils.ts';\n\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((_, i) => i));\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++) for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k]));\n\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n else if (group === 1) return (x & y) | (~x & z);\n else if (group === 2) return (x | ~y) ^ z;\n else if (group === 3) return (x & z) | (y & ~z);\n else return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst R_BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD<RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) R_BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + R_BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + R_BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n R_BUF.fill(0);\n }\n destroy(): void {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/** RIPEMD-160 - a legacy hash function from 1990s. */\nexport const ripemd160: CHash = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n","import {\n Account,\n BaseTransaction,\n isAccount,\n isNumber,\n validateBaseTransaction,\n validateCredentialsList,\n validateOptionalField,\n validateRequiredField,\n MAX_AUTHORIZED_CREDENTIALS,\n} from './common'\n\n/**\n * An AccountDelete transaction deletes an account and any objects it owns in\n * the XRP Ledger, if possible, sending the account's remaining XRP to a\n * specified destination account.\n *\n * @category Transaction Models\n */\nexport interface AccountDelete extends BaseTransaction {\n TransactionType: 'AccountDelete'\n /**\n * The address of an account to receive any leftover XRP after deleting the\n * sending account. Must be a funded account in the ledger, and must not be.\n * the sending account.\n */\n Destination: Account\n /**\n * Arbitrary destination tag that identifies a hosted recipient or other.\n * information for the recipient of the deleted account's leftover XRP.\n */\n DestinationTag?: number\n /**\n * Credentials associated with sender of this transaction. The credentials included\n * must not be expired. The list must not be empty when specified and cannot contain\n * more than 8 credentials.\n */\n CredentialIDs?: string[]\n}\n\n/**\n * Verify the form and type of an AccountDelete at runtime.\n *\n * @param tx - An AccountDelete Transaction.\n * @throws When the AccountDelete is Malformed.\n */\nexport function validateAccountDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'Destination', isAccount)\n validateOptionalField(tx, 'DestinationTag', isNumber)\n\n validateCredentialsList(\n tx.CredentialIDs,\n tx.TransactionType,\n true,\n MAX_AUTHORIZED_CREDENTIALS,\n )\n}\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\nimport { isHex } from '../utils'\n\nimport {\n Account,\n BaseTransaction,\n GlobalFlagsInterface,\n isAccount,\n isAmount,\n isNumber,\n validateBaseTransaction,\n validateOptionalField,\n} from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n/**\n * Transaction Flags for an NFTokenMint Transaction.\n *\n * @category Transaction Flags\n */\nexport enum NFTokenMintFlags {\n /**\n * If set, indicates that the minted token may be burned by the issuer even\n * if the issuer does not currently hold the token. The current holder of\n * the token may always burn it.\n */\n tfBurnable = 0x00000001,\n /**\n * If set, indicates that the token may only be offered or sold for XRP.\n */\n tfOnlyXRP = 0x00000002,\n /**\n * If set, indicates that the issuer wants a trustline to be automatically\n * created.\n */\n tfTrustLine = 0x00000004,\n /**\n * If set, indicates that this NFT can be transferred. This flag has no\n * effect if the token is being transferred from the issuer or to the\n * issuer.\n */\n tfTransferable = 0x00000008,\n /**\n * If set, indicates that this NFT's URI can be modified.\n */\n tfMutable = 0x00000010,\n}\n\n/**\n * Map of flags to boolean values representing {@link NFTokenMint} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface NFTokenMintFlagsInterface extends GlobalFlagsInterface {\n tfBurnable?: boolean\n tfOnlyXRP?: boolean\n tfTrustLine?: boolean\n tfTransferable?: boolean\n tfMutable?: boolean\n}\n\n/**\n * The NFTokenMint transaction creates an NFToken object and adds it to the\n * relevant NFTokenPage object of the minter. If the transaction is\n * successful, the newly minted token will be owned by the minter account\n * specified by the transaction.\n */\nexport interface NFTokenMint extends BaseTransaction {\n TransactionType: 'NFTokenMint'\n /**\n * Indicates the taxon associated with this token. The taxon is generally a\n * value chosen by the minter of the token and a given taxon may be used for\n * multiple tokens. The implementation reserves taxon identifiers greater\n * than or equal to 2147483648 (0x80000000). If you have no use for this\n * field, set it to 0.\n */\n NFTokenTaxon: number\n /**\n * Indicates the account that should be the issuer of this token. This value\n * is optional and should only be specified if the account executing the\n * transaction is not the `Issuer` of the `NFToken` object. If it is\n * present, the `MintAccount` field in the `AccountRoot` of the `Issuer`\n * field must match the `Account`, otherwise the transaction will fail.\n */\n Issuer?: Account\n /**\n * Specifies the fee charged by the issuer for secondary sales of the Token,\n * if such sales are allowed. Valid values for this field are between 0 and\n * 50000 inclusive, allowing transfer rates between 0.000% and 50.000% in\n * increments of 0.001%. This field must NOT be present if the\n * `tfTransferable` flag is not set.\n */\n TransferFee?: number\n /**\n * URI that points to the data and/or metadata associated with the NFT.\n * This field need not be an HTTP or HTTPS URL; it could be an IPFS URI, a\n * magnet link, immediate data encoded as an RFC2379 \"data\" URL, or even an\n * opaque issuer-specific encoding. The URI is NOT checked for validity, but\n * the field is limited to a maximum length of 256 bytes.\n *\n * This field must be hex-encoded. You can use `convertStringToHex` to\n * convert this field to the proper encoding.\n *\n * This field must not be an empty string. Omit it from the transaction or\n * set to `undefined` value if you do not use it.\n */\n URI?: string | null\n /**\n * Indicates the amount expected for the Token.\n *\n * The amount can be zero. This would indicate that the account is giving\n * the token away free, either to anyone at all, or to the account identified\n * by the Destination field.\n */\n Amount?: Amount\n /**\n * Indicates the time after which the offer will no longer\n * be valid. The value is the number of seconds since the\n * Ripple Epoch.\n */\n Expiration?: number\n /**\n * If present, indicates that this offer may only be\n * accepted by the specified account. Attempts by other\n * accounts to accept this offer MUST fail.\n */\n Destination?: Account\n Flags?: number | NFTokenMintFlagsInterface\n}\n\nexport interface NFTokenMintMetadata extends TransactionMetadataBase {\n // rippled 1.11.0 or later\n nftoken_id?: string\n // if Amount is present\n offer_id?: string\n}\n\n/**\n * Verify the form and type of an NFTokenMint at runtime.\n *\n * @param tx - An NFTokenMint Transaction.\n * @throws When the NFTokenMint is Malformed.\n */\nexport function validateNFTokenMint(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Account === tx.Issuer) {\n throw new ValidationError(\n 'NFTokenMint: Issuer must not be equal to Account',\n )\n }\n\n validateOptionalField(tx, 'Issuer', isAccount)\n\n if (typeof tx.URI === 'string' && tx.URI === '') {\n throw new ValidationError('NFTokenMint: URI must not be empty string')\n }\n\n if (typeof tx.URI === 'string' && !isHex(tx.URI)) {\n throw new ValidationError('NFTokenMint: URI must be in hex format')\n }\n\n if (tx.NFTokenTaxon == null) {\n throw new ValidationError('NFTokenMint: missing field NFTokenTaxon')\n }\n\n if (tx.Amount == null) {\n if (tx.Expiration != null || tx.Destination != null) {\n throw new ValidationError(\n 'NFTokenMint: Amount is required when Expiration or Destination is present',\n )\n }\n }\n\n validateOptionalField(tx, 'Amount', isAmount)\n validateOptionalField(tx, 'Expiration', isNumber)\n validateOptionalField(tx, 'Destination', isAccount)\n}\n","import { BinaryParser } from '../serdes/binary-parser'\nimport { SerializedType } from './serialized-type'\nimport { writeInt32BE, writeInt64BE, readInt32BE, readInt64BE } from '../utils'\n\n/**\n * Constants for mantissa and exponent normalization per XRPL Number spec.\n * These define allowed magnitude for mantissa and exponent after normalization.\n */\nconst MIN_MANTISSA = BigInt('1000000000000000')\nconst MAX_MANTISSA = BigInt('9999999999999999')\nconst MIN_EXPONENT = -32768\nconst MAX_EXPONENT = 32768\nconst DEFAULT_VALUE_EXPONENT = -2147483648\n\n/**\n * Extract mantissa, exponent, and sign from a number string.\n *\n * @param val - The string representing the number (may be integer, decimal, or scientific notation).\n * @returns Object containing mantissa (BigInt), exponent (number), and isNegative (boolean).\n * @throws Error if the string cannot be parsed as a valid number.\n *\n * Examples:\n * '123' -> { mantissa: 123n, exponent: 0, isNegative: false }\n * '-00123.45' -> { mantissa: -12345n, exponent: -2, isNegative: true }\n * '+7.1e2' -> { mantissa: 71n, exponent: -1 + 2 = 1, isNegative: false }\n */\nfunction extractNumberPartsFromString(val: string): {\n mantissa: bigint\n exponent: number\n isNegative: boolean\n} {\n /**\n * Regex for parsing decimal/float/scientific number strings with optional sign, integer, decimal, and exponent parts.\n *\n * Pattern: /^([-+]?)([0-9]+)(?:\\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/\n *\n * Breakdown:\n * 1. ([-+]?) - Optional '+' or '-' sign at the start.\n * 2. ([0-9]+) - Integer part: one or more digits (leading zeros allowed).\n * 3. (?:\\.([0-9]+))? - Optional decimal point followed by one or more digits.\n * 4. (?:[eE]([+-]?[0-9]+))? - Optional exponent, starting with 'e' or 'E', optional sign, and digits.\n *\n * Notes:\n * - Leading zeros are accepted and normalized by code after parsing.\n * - Empty decimal ('123.') and missing integer ('.456') are NOT matched—must be fully specified.\n */\n const regex = /^([-+]?)([0-9]+)(?:\\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/\n const match = regex.exec(val)\n if (!match) throw new Error(`Unable to parse number from string: ${val}`)\n\n const [, sign, intPart, fracPart, expPart] = match\n // Remove leading zeros (unless the entire intPart is zeros)\n const cleanIntPart = intPart.replace(/^0+(?=\\d)/, '') || '0'\n\n let mantissaStr = cleanIntPart\n let exponent = 0\n\n if (fracPart) {\n mantissaStr += fracPart\n exponent -= fracPart.length\n }\n if (expPart) exponent += parseInt(expPart, 10)\n\n let mantissa = BigInt(mantissaStr)\n if (sign === '-') mantissa = -mantissa\n const isNegative = mantissa < BigInt(0)\n\n return { mantissa, exponent, isNegative }\n}\n\n/**\n * Normalize the mantissa and exponent to XRPL constraints.\n *\n * Ensures that after normalization, the mantissa is between MIN_MANTISSA and MAX_MANTISSA (unless zero).\n * Adjusts the exponent as needed by shifting the mantissa left/right (multiplying/dividing by 10).\n *\n * @param mantissa - The unnormalized mantissa (BigInt).\n * @param exponent - The unnormalized exponent (number).\n * @returns An object with normalized mantissa and exponent.\n * @throws Error if the number cannot be normalized within allowed exponent range.\n */\nfunction normalize(\n mantissa: bigint,\n exponent: number,\n): { mantissa: bigint; exponent: number } {\n let m = mantissa < BigInt(0) ? -mantissa : mantissa\n const isNegative = mantissa < BigInt(0)\n\n while (m !== BigInt(0) && m < MIN_MANTISSA && exponent > MIN_EXPONENT) {\n exponent -= 1\n m *= BigInt(10)\n }\n while (m > MAX_MANTISSA) {\n if (exponent >= MAX_EXPONENT)\n throw new Error('Mantissa and exponent are too large')\n exponent += 1\n m /= BigInt(10)\n }\n if (isNegative) m = -m\n return { mantissa: m, exponent }\n}\n\n/**\n * STNumber: Encodes XRPL's \"Number\" type.\n *\n * - Always encoded as 12 bytes: 8-byte signed mantissa, 4-byte signed exponent, both big-endian.\n * - Can only be constructed from a valid number string or another STNumber instance.\n *\n * Usage:\n * STNumber.from(\"1.2345e5\")\n * STNumber.from(\"-123\")\n * STNumber.fromParser(parser)\n */\nexport class STNumber extends SerializedType {\n /** 12 zero bytes, represents canonical zero. */\n static defaultBytes = new Uint8Array(12)\n\n /**\n * Construct a STNumber from 12 bytes (8 for mantissa, 4 for exponent).\n * @param bytes - 12-byte Uint8Array\n * @throws Error if input is not a Uint8Array of length 12.\n */\n constructor(bytes?: Uint8Array) {\n const used = bytes ?? STNumber.defaultBytes\n if (!(used instanceof Uint8Array) || used.length !== 12) {\n throw new Error(\n `STNumber must be constructed from a 12-byte Uint8Array, got ${used?.length}`,\n )\n }\n super(used)\n }\n\n /**\n * Construct from a number string (or another STNumber).\n *\n * @param value - A string, or STNumber instance.\n * @returns STNumber instance.\n * @throws Error if not a string or STNumber.\n */\n static from(value: unknown): STNumber {\n if (value instanceof STNumber) {\n return value\n }\n if (typeof value === 'string') {\n return STNumber.fromValue(value)\n }\n throw new Error(\n 'STNumber.from: Only string or STNumber instance is supported',\n )\n }\n\n /**\n * Construct from a number string (integer, decimal, or scientific notation).\n * Handles normalization to XRPL Number constraints.\n *\n * @param val - The number as a string (e.g. '1.23', '-123e5').\n * @returns STNumber instance\n * @throws Error if val is not a valid number string.\n */\n static fromValue(val: string): STNumber {\n const { mantissa, exponent, isNegative } = extractNumberPartsFromString(val)\n let normalizedMantissa: bigint\n let normalizedExponent: number\n\n if (mantissa === BigInt(0) && exponent === 0 && !isNegative) {\n normalizedMantissa = BigInt(0)\n normalizedExponent = DEFAULT_VALUE_EXPONENT\n } else {\n ;({ mantissa: normalizedMantissa, exponent: normalizedExponent } =\n normalize(mantissa, exponent))\n }\n\n const bytes = new Uint8Array(12)\n writeInt64BE(bytes, normalizedMantissa, 0)\n writeInt32BE(bytes, normalizedExponent, 8)\n return new STNumber(bytes)\n }\n\n /**\n * Read a STNumber from a BinaryParser stream (12 bytes).\n * @param parser - BinaryParser positioned at the start of a number\n * @returns STNumber instance\n */\n static fromParser(parser: BinaryParser): STNumber {\n return new STNumber(parser.read(12))\n }\n\n /**\n * Convert this STNumber to a normalized string representation.\n * The output is decimal or scientific notation, depending on exponent range.\n * Follows XRPL convention: zero is \"0\", other values are normalized to a canonical string.\n *\n * @returns String representation of the value\n */\n // eslint-disable-next-line complexity -- required\n toJSON(): string {\n const b = this.bytes\n if (!b || b.length !== 12)\n throw new Error('STNumber internal bytes not set or wrong length')\n\n // Signed 64-bit mantissa\n const mantissa = readInt64BE(b, 0)\n // Signed 32-bit exponent\n const exponent = readInt32BE(b, 8)\n\n // Special zero: XRPL encodes canonical zero as mantissa=0, exponent=DEFAULT_VALUE_EXPONENT.\n if (mantissa === BigInt(0) && exponent === DEFAULT_VALUE_EXPONENT) {\n return '0'\n }\n if (exponent === 0) return mantissa.toString()\n\n // Use scientific notation for small/large exponents, decimal otherwise\n if (exponent < -25 || exponent > -5) {\n return `${mantissa}e${exponent}`\n }\n\n // Decimal rendering for -25 <= exp <= -5\n const isNegative = mantissa < BigInt(0)\n const mantissaAbs = mantissa < BigInt(0) ? -mantissa : mantissa\n\n const padPrefix = 27\n const padSuffix = 23\n const mantissaStr = mantissaAbs.toString()\n const rawValue = '0'.repeat(padPrefix) + mantissaStr + '0'.repeat(padSuffix)\n const OFFSET = exponent + 43\n const integerPart = rawValue.slice(0, OFFSET).replace(/^0+/, '') || '0'\n const fractionPart = rawValue.slice(OFFSET).replace(/0+$/, '')\n\n return `${isNegative ? '-' : ''}${integerPart}${\n fractionPart ? '.' + fractionPart : ''\n }`\n }\n}\n","import { SerializedType } from '../types/serialized-type'\nimport { Bytes, BytesLookup } from './bytes'\nimport { FieldInfo, FieldLookup, FieldInstance } from './field'\nimport {\n TYPE_WIDTH,\n LEDGER_ENTRY_WIDTH,\n TRANSACTION_TYPE_WIDTH,\n TRANSACTION_RESULT_WIDTH,\n DELEGATABLE_PERMISSIONS_WIDTH,\n} from './constants'\n\ninterface DefinitionsData {\n TYPES: Record<string, number>\n LEDGER_ENTRY_TYPES: Record<string, number>\n FIELDS: (string | FieldInfo)[][]\n TRANSACTION_RESULTS: Record<string, number>\n TRANSACTION_TYPES: Record<string, number>\n}\n\n/**\n * Stores the various types and fields for rippled to be used to encode/decode information later on.\n * XrplDefinitions should be instantiated instead of this class.\n */\nclass XrplDefinitionsBase {\n // A collection of fields that can be included in transactions\n field: FieldLookup\n // A collection of ids corresponding to types of ledger objects\n ledgerEntryType: BytesLookup\n // A collection of type flags used to determine how to serialize a field's data\n type: BytesLookup\n // Errors and result codes for transactions\n transactionResult: BytesLookup\n // Defined transactions that can be submitted to the ledger\n transactionType: BytesLookup\n // Valid transaction names\n transactionNames: string[]\n // Maps serializable types to their TypeScript class implementation\n dataTypes: Record<string, typeof SerializedType>\n // Maps granular permissions names to their corresponding integer ids\n granularPermissions: Record<string, number>\n // Defined delegatable permissions\n delegatablePermissions: BytesLookup\n\n /**\n * Present rippled types in a typed and updatable format.\n * For an example of the input format see `definitions.json`.\n * To generate a new definitions file from rippled source code, use the tool at\n * `packages/ripple-binary-codec/tools/generateDefinitions.js`.\n *\n * See the definitions.test.js file for examples of how to create your own updated definitions.json.\n *\n * @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.\n * @param types - A list of type objects with the same name as the fields defined.\n * You can use the coreTypes object if you are not adding new types.\n */\n constructor(\n enums: DefinitionsData,\n types: Record<string, typeof SerializedType>,\n ) {\n this.type = new BytesLookup(enums.TYPES, TYPE_WIDTH)\n this.ledgerEntryType = new BytesLookup(\n enums.LEDGER_ENTRY_TYPES,\n LEDGER_ENTRY_WIDTH,\n )\n this.transactionType = new BytesLookup(\n enums.TRANSACTION_TYPES,\n TRANSACTION_TYPE_WIDTH,\n )\n this.transactionResult = new BytesLookup(\n enums.TRANSACTION_RESULTS,\n TRANSACTION_RESULT_WIDTH,\n )\n this.field = new FieldLookup(\n enums.FIELDS as Array<[string, FieldInfo]>,\n enums.TYPES,\n )\n this.transactionNames = Object.entries(enums.TRANSACTION_TYPES)\n .filter(([_key, value]) => value >= 0)\n .map(([key, _value]) => key)\n\n this.dataTypes = {} // Filled in via associateTypes\n this.associateTypes(types)\n\n this.granularPermissions = {\n TrustlineAuthorize: 65537,\n TrustlineFreeze: 65538,\n TrustlineUnfreeze: 65539,\n AccountDomainSet: 65540,\n AccountEmailHashSet: 65541,\n AccountMessageKeySet: 65542,\n AccountTransferRateSet: 65543,\n AccountTickSizeSet: 65544,\n PaymentMint: 65545,\n PaymentBurn: 65546,\n MPTokenIssuanceLock: 65547,\n MPTokenIssuanceUnlock: 65548,\n }\n\n const incrementedTransactionTypes = Object.fromEntries(\n Object.entries(enums.TRANSACTION_TYPES).map(([key, value]) => [\n key,\n value + 1,\n ]),\n )\n const combinedPermissions = {\n ...this.granularPermissions,\n ...incrementedTransactionTypes,\n }\n this.delegatablePermissions = new BytesLookup(\n combinedPermissions,\n DELEGATABLE_PERMISSIONS_WIDTH,\n )\n }\n\n /**\n * Associates each Field to a corresponding class that TypeScript can recognize.\n *\n * @param types a list of type objects with the same name as the fields defined.\n * Defaults to xrpl.js's core type definitions.\n */\n public associateTypes(types: Record<string, typeof SerializedType>): void {\n // Overwrite any existing type definitions with the given types\n this.dataTypes = Object.assign({}, this.dataTypes, types)\n\n Object.values(this.field).forEach((field) => {\n field.associatedType = this.dataTypes[field.type.name]\n })\n\n this.field['TransactionType'].associatedType = this.transactionType\n this.field['TransactionResult'].associatedType = this.transactionResult\n this.field['LedgerEntryType'].associatedType = this.ledgerEntryType\n if (this.field['PermissionValue']) {\n this.field['PermissionValue'].associatedType = this.delegatablePermissions\n }\n }\n\n public getAssociatedTypes(): Record<string, typeof SerializedType> {\n return this.dataTypes\n }\n}\n\nexport {\n DefinitionsData,\n XrplDefinitionsBase,\n FieldLookup,\n FieldInfo,\n FieldInstance,\n Bytes,\n BytesLookup,\n}\n","import AccountRoot, {\n AccountRootFlags,\n AccountRootFlagsInterface,\n} from './AccountRoot'\nimport Amendments, { Majority, AMENDMENTS_ID } from './Amendments'\nimport AMM, { VoteSlot } from './AMM'\nimport Bridge from './Bridge'\nimport Check from './Check'\nimport Credential from './Credential'\nimport Delegate from './Delegate'\nimport DepositPreauth from './DepositPreauth'\nimport DID from './DID'\nimport DirectoryNode from './DirectoryNode'\nimport Escrow from './Escrow'\nimport FeeSettings, {\n FeeSettingsPreAmendmentFields,\n FeeSettingsPostAmendmentFields,\n FEE_SETTINGS_ID,\n} from './FeeSettings'\nimport { Ledger, LedgerV1 } from './Ledger'\nimport { LedgerEntry, LedgerEntryFilter } from './LedgerEntry'\nimport LedgerHashes from './LedgerHashes'\nimport { MPToken } from './MPToken'\nimport { MPTokenIssuance } from './MPTokenIssuance'\nimport NegativeUNL, { NEGATIVE_UNL_ID } from './NegativeUNL'\nimport { NFTokenOffer } from './NFTokenOffer'\nimport { NFToken, NFTokenPage } from './NFTokenPage'\nimport Offer, { OfferFlags } from './Offer'\nimport Oracle from './Oracle'\nimport PayChannel from './PayChannel'\nimport RippleState, { RippleStateFlags } from './RippleState'\nimport SignerList, { SignerListFlags } from './SignerList'\nimport Ticket from './Ticket'\nimport Vault from './Vault'\nimport XChainOwnedClaimID from './XChainOwnedClaimID'\nimport XChainOwnedCreateAccountClaimID from './XChainOwnedCreateAccountClaimID'\n\nexport {\n AccountRoot,\n AccountRootFlags,\n AccountRootFlagsInterface,\n AMENDMENTS_ID,\n Amendments,\n AMM,\n Bridge,\n Check,\n Credential,\n Delegate,\n DepositPreauth,\n DirectoryNode,\n DID,\n Escrow,\n FEE_SETTINGS_ID,\n FeeSettings,\n FeeSettingsPreAmendmentFields,\n FeeSettingsPostAmendmentFields,\n Ledger,\n LedgerV1,\n LedgerEntryFilter,\n LedgerEntry,\n LedgerHashes,\n Majority,\n NEGATIVE_UNL_ID,\n NegativeUNL,\n MPTokenIssuance,\n MPToken,\n NFTokenOffer,\n NFTokenPage,\n NFToken,\n Offer,\n OfferFlags,\n Oracle,\n PayChannel,\n RippleState,\n RippleStateFlags,\n SignerList,\n SignerListFlags,\n Ticket,\n Vault,\n VoteSlot,\n XChainOwnedClaimID,\n XChainOwnedCreateAccountClaimID,\n}\n","import {\n DEFAULT_DEFINITIONS,\n FieldInstance,\n Bytes,\n XrplDefinitionsBase,\n} from '../enums'\nimport { SerializedType, JsonObject } from './serialized-type'\nimport { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'\nimport { BinaryParser } from '../serdes/binary-parser'\nimport { BinarySerializer, BytesList } from '../serdes/binary-serializer'\n\nimport { STArray } from './st-array'\nimport { UInt64 } from './uint-64'\n\nconst OBJECT_END_MARKER_BYTE = Uint8Array.from([0xe1])\nconst OBJECT_END_MARKER = 'ObjectEndMarker'\nconst ST_OBJECT = 'STObject'\nconst DESTINATION = 'Destination'\nconst ACCOUNT = 'Account'\nconst SOURCE_TAG = 'SourceTag'\nconst DEST_TAG = 'DestinationTag'\n\n/**\n * Break down an X-Address into an account and a tag\n *\n * @param field Name of field\n * @param xAddress X-Address corresponding to the field\n */\nfunction handleXAddress(field: string, xAddress: string): JsonObject {\n const decoded = xAddressToClassicAddress(xAddress)\n\n let tagName\n if (field === DESTINATION) tagName = DEST_TAG\n else if (field === ACCOUNT) tagName = SOURCE_TAG\n else if (decoded.tag !== false)\n throw new Error(`${field} cannot have an associated tag`)\n\n return decoded.tag !== false\n ? { [field]: decoded.classicAddress, [tagName]: decoded.tag }\n : { [field]: decoded.classicAddress }\n}\n\n/**\n * Validate that two objects don't both have the same tag fields\n *\n * @param obj1 First object to check for tags\n * @param obj2 Second object to check for tags\n * @throws When both objects have SourceTag or DestinationTag\n */\nfunction checkForDuplicateTags(obj1: JsonObject, obj2: JsonObject): void {\n if (!(obj1[SOURCE_TAG] === undefined || obj2[SOURCE_TAG] === undefined))\n throw new Error('Cannot have Account X-Address and SourceTag')\n if (!(obj1[DEST_TAG] === undefined || obj2[DEST_TAG] === undefined))\n throw new Error('Cannot have Destination X-Address and DestinationTag')\n}\n\n/**\n * Class for Serializing/Deserializing objects\n */\nclass STObject extends SerializedType {\n /**\n * Construct a STObject from a BinaryParser\n *\n * @param parser BinaryParser to read STObject from\n * @returns A STObject object\n */\n static fromParser(parser: BinaryParser): STObject {\n const list: BytesList = new BytesList()\n const bytes: BinarySerializer = new BinarySerializer(list)\n\n while (!parser.end()) {\n const field = parser.readField()\n if (field.name === OBJECT_END_MARKER) {\n break\n }\n\n const associatedValue = parser.readFieldValue(field)\n\n bytes.writeFieldAndValue(field, associatedValue)\n if (field.type.name === ST_OBJECT) {\n bytes.put(OBJECT_END_MARKER_BYTE)\n }\n }\n\n return new STObject(list.toBytes())\n }\n\n /**\n * Construct a STObject from a JSON object\n *\n * @param value An object to include\n * @param filter optional, denote which field to include in serialized object\n * @param definitions optional, types and values to use to encode/decode a transaction\n * @returns a STObject object\n */\n static from<T extends STObject | JsonObject>(\n value: T,\n filter?: (...any) => boolean,\n definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n ): STObject {\n if (value instanceof STObject) {\n return value\n }\n\n const list: BytesList = new BytesList()\n const bytes: BinarySerializer = new BinarySerializer(list)\n\n let isUnlModify = false\n\n const xAddressDecoded = Object.entries(value).reduce((acc, [key, val]) => {\n let handled: JsonObject | undefined = undefined\n if (val && isValidXAddress(val.toString())) {\n handled = handleXAddress(key, val.toString())\n checkForDuplicateTags(handled, value)\n }\n return Object.assign(acc, handled ?? { [key]: val })\n }, {})\n\n function isValidFieldInstance(\n f: FieldInstance | undefined,\n ): f is FieldInstance {\n return (\n f !== undefined &&\n xAddressDecoded[f.name] !== undefined &&\n f.isSerialized\n )\n }\n\n let sorted = Object.keys(xAddressDecoded)\n .map((f: string): FieldInstance | undefined => {\n if (!(f in definitions.field)) {\n if (f[0] === f[0].toLowerCase()) return undefined\n throw new Error(`Field ${f} is not defined in the definitions`)\n }\n return definitions.field[f] as FieldInstance\n })\n .filter(isValidFieldInstance)\n .sort((a, b) => {\n return a.ordinal - b.ordinal\n })\n\n if (filter !== undefined) {\n sorted = sorted.filter(filter)\n }\n\n sorted.forEach((field) => {\n const associatedValue =\n field.type.name === ST_OBJECT\n ? this.from(xAddressDecoded[field.name], undefined, definitions)\n : field.type.name === 'STArray'\n ? STArray.from(xAddressDecoded[field.name], definitions)\n : field.type.name === 'UInt64'\n ? UInt64.from(xAddressDecoded[field.name], field.name)\n : field.associatedType?.from\n ? field.associatedType.from(xAddressDecoded[field.name])\n : (() => {\n throw new Error(\n `Type ${field.type.name} for field ${field.name} is missing associatedType.from`,\n )\n })()\n\n if (associatedValue == undefined) {\n throw new TypeError(\n `Unable to interpret \"${field.name}: ${\n xAddressDecoded[field.name]\n }\".`,\n )\n }\n\n if ((associatedValue as unknown as Bytes).name === 'UNLModify') {\n // triggered when the TransactionType field has a value of 'UNLModify'\n isUnlModify = true\n }\n // true when in the UNLModify pseudotransaction (after the transaction type has been processed) and working with the\n // Account field\n // The Account field must not be a part of the UNLModify pseudotransaction encoding, due to a bug in rippled\n const isUnlModifyWorkaround = field.name == 'Account' && isUnlModify\n bytes.writeFieldAndValue(field, associatedValue, isUnlModifyWorkaround)\n if (field.type.name === ST_OBJECT) {\n bytes.put(OBJECT_END_MARKER_BYTE)\n }\n })\n\n return new STObject(list.toBytes())\n }\n\n /**\n * Get the JSON interpretation of this.bytes\n * @param definitions rippled definitions used to parse the values of transaction types and such.\n * Can be customized for sidechains and amendments.\n * @returns a JSON object\n */\n toJSON(definitions?: XrplDefinitionsBase): JsonObject {\n const objectParser = new BinaryParser(this.toString(), definitions)\n const accumulator = {}\n\n while (!objectParser.end()) {\n const field = objectParser.readField()\n if (field.name === OBJECT_END_MARKER) {\n break\n }\n\n accumulator[field.name] = objectParser\n .readFieldValue(field)\n .toJSON(definitions, field.name)\n }\n\n return accumulator\n }\n}\n\nexport { STObject }\n","import { IssuedCurrencyAmount } from '../common'\n\nimport { BaseLedgerEntry, HasPreviousTxnID } from './BaseLedgerEntry'\n\n/**\n * The RippleState object type connects two accounts in a single currency.\n *\n * @category Ledger Entries\n */\nexport default interface RippleState extends BaseLedgerEntry, HasPreviousTxnID {\n LedgerEntryType: 'RippleState'\n /** A bit-map of boolean options enabled for this object. */\n Flags: number\n /**\n * The balance of the trust line, from the perspective of the low account. A\n * negative balance indicates that the low account has issued currency to the\n * high account. The issuer is always the neutral value ACCOUNT_ONE.\n */\n Balance: IssuedCurrencyAmount\n /**\n * The limit that the low account has set on the trust line. The issuer is\n * the address of the low account that set this limit.\n */\n LowLimit: IssuedCurrencyAmount\n /**\n * The limit that the high account has set on the trust line. The issuer is\n * the address of the high account that set this limit.\n */\n HighLimit: IssuedCurrencyAmount\n /**\n * A hint indicating which page of the low account's owner directory links to\n * this object, in case the directory consists of multiple pages.\n */\n LowNode?: string\n /**\n * A hint indicating which page of the high account's owner directory links\n * to this object, in case the directory consists of multiple pages.\n */\n HighNode?: string\n /**\n * The inbound quality set by the low account, as an integer in the implied\n * ratio LowQualityIn:1,000,000,000. As a special case, the value 0 is\n * equivalent to 1 billion, or face value.\n */\n LowQualityIn?: number\n /**\n * The outbound quality set by the low account, as an integer in the implied\n * ratio LowQualityOut:1,000,000,000. As a special case, the value 0 is\n * equivalent to 1 billion, or face value.\n */\n LowQualityOut?: number\n /**\n * The inbound quality set by the high account, as an integer in the implied\n * ratio HighQualityIn:1,000,000,000. As a special case, the value 0 is\n * equivalent to 1 billion, or face value.\n */\n HighQualityIn?: number\n /**\n * The outbound quality set by the high account, as an integer in the implied\n * ratio HighQualityOut:1,000,000,000. As a special case, the value 0 is\n * equivalent to 1 billion, or face value.\n */\n HighQualityOut?: number\n}\n\nexport enum RippleStateFlags {\n // True, if entry counts toward reserve.\n lsfLowReserve = 0x00010000,\n lsfHighReserve = 0x00020000,\n lsfLowAuth = 0x00040000,\n lsfHighAuth = 0x00080000,\n lsfLowNoRipple = 0x00100000,\n lsfHighNoRipple = 0x00200000,\n // True, low side has set freeze flag\n lsfLowFreeze = 0x00400000,\n // True, high side has set freeze flag\n lsfHighFreeze = 0x00800000,\n // True, trust line to AMM. Used by client apps to identify payments via AMM.\n lsfAMMNode = 0x01000000,\n // True, low side has set deep freeze flag\n lsfLowDeepFreeze = 0x02000000,\n // True, high side has set deep freeze flag\n lsfHighDeepFreeze = 0x04000000,\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport Sha512 from '../../utils/Sha512'\n\nconst ZERO = BigInt(0)\n\nfunction deriveScalar(bytes: Uint8Array, discrim?: number): bigint {\n const order = secp256k1.CURVE.n\n for (let i = 0; i <= 0xffff_ffff; i++) {\n // We hash the bytes to find a 256-bit number, looping until we are sure it\n // is less than the order of the curve.\n const hasher = new Sha512().add(bytes)\n // If the optional discriminator index was passed in, update the hash.\n if (discrim !== undefined) {\n hasher.addU32(discrim)\n }\n hasher.addU32(i)\n const key = hasher.first256BigInt()\n /* istanbul ignore else */\n if (key > ZERO && key < order) {\n return key\n }\n }\n // This error is practically impossible to reach.\n // The order of the curve describes the (finite) amount of points on the curve\n // https://github.com/indutny/elliptic/blob/master/lib/elliptic/curves.js#L182\n // How often will an (essentially) random number generated by Sha512 be larger than that?\n // There's 2^32 chances (the for loop) to get a number smaller than the order,\n // and it's rare that you'll even get past the first loop iteration.\n // Note that in TypeScript we actually need the throw, otherwise the function signature would be bigint | undefined\n //\n /* istanbul ignore next */\n throw new Error('impossible unicorn ;)')\n}\n\n/**\n * @param seed - Bytes.\n * @param [opts] - Object.\n * @param [opts.accountIndex=0] - The account number to generate.\n * @param [opts.validator=false] - Generate root key-pair,\n * as used by validators.\n * @returns {bigint} 256 bit scalar value.\n *\n */\nexport function derivePrivateKey(\n seed: Uint8Array,\n opts: {\n validator?: boolean\n accountIndex?: number\n } = {},\n): bigint {\n const root = opts.validator\n const order = secp256k1.CURVE.n\n\n // This private generator represents the `root` private key, and is what's\n // used by validators for signing when a keypair is generated from a seed.\n const privateGen = deriveScalar(seed)\n if (root) {\n // As returned by validation_create for a given seed\n return privateGen\n }\n const publicGen =\n secp256k1.ProjectivePoint.BASE.multiply(privateGen).toRawBytes(true)\n // A seed can generate many keypairs as a function of the seed and a uint32.\n // Almost everyone just uses the first account, `0`.\n const accountIndex = opts.accountIndex || 0\n return (deriveScalar(publicGen, accountIndex) + privateGen) % order\n}\n\nexport function accountPublicFromPublicGenerator(publicGenBytes: Uint8Array) {\n const rootPubPoint = secp256k1.ProjectivePoint.fromHex(publicGenBytes)\n const scalar = deriveScalar(publicGenBytes, 0)\n const point = secp256k1.ProjectivePoint.BASE.multiply(scalar)\n const offset = rootPubPoint.add(point)\n return offset.toRawBytes(true)\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.js';\nimport { createHasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.js';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n *\n * @example\n * import { secp256k1 } from '@noble/curves/secp256k1';\n *\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7),\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n\n/** secp256k1 hash-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => htf.hashToCurve)();\n\n/** secp256k1 encode-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => htf.encodeToCurve)();\n","import { ClawbackAmount } from '../common'\n\nimport {\n BaseTransaction,\n validateBaseTransaction,\n validateRequiredField,\n isString,\n Account,\n isAccount,\n validateOptionalField,\n isClawbackAmount,\n} from './common'\n\n/**\n * The VaultClawback transaction performs a Clawback from the Vault, exchanging the shares of an account.\n *\n * Conceptually, the transaction performs VaultWithdraw on behalf of the Holder, sending the funds to the\n * Issuer account of the asset. In case there are insufficient funds for the entire Amount the transaction\n * will perform a partial Clawback, up to the Vault.AssetsAvailable. The Clawback transaction must respect\n * any future fees or penalties.\n *\n * @category Transaction Models\n */\nexport interface VaultClawback extends BaseTransaction {\n TransactionType: 'VaultClawback'\n\n /**\n * The ID of the vault from which assets are withdrawn.\n */\n VaultID: string\n\n /**\n * The account ID from which to clawback the assets.\n */\n Holder: Account\n\n /**\n * The asset amount to clawback. When Amount is 0 clawback all funds, up to the total shares the Holder owns.\n */\n Amount?: ClawbackAmount\n}\n\n/**\n * Verify the form and type of a {@link VaultClawback} at runtime.\n *\n * @param tx - A {@link VaultClawback} Transaction.\n * @throws When the {@link VaultClawback} is malformed.\n */\nexport function validateVaultClawback(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'VaultID', isString)\n validateRequiredField(tx, 'Holder', isAccount)\n validateOptionalField(tx, 'Amount', isClawbackAmount)\n}\n","type ValueOf<T> = T[keyof T]\n\n/**\n * Creates an object composed of keys generated from the results of running each element of collection thru iteratee.\n * The order of grouped values is determined by the order they occur in collection.\n * The corresponding value of each key is an array of elements responsible for generating the key.\n *\n * Similar to lodash's groupBy\n *\n * @param array - array to iterate over\n * @param iteratee - function that returns key of the group to place the item\n *\n * @returns a map of arrays\n */\nexport function groupBy<T>(\n array: T[],\n iteratee: (value: T, index: number, array: T[]) => string | number,\n): Record<string | number, T[]> {\n // eslint-disable-next-line max-params -- need all the params for the fallback\n function predicate(\n acc: Record<string | number, T[]>,\n value: T,\n index: number,\n arrayReference: T[],\n ): Record<string | number, T[]> {\n const key = iteratee(value, index, arrayReference) || 0\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Find existing group or create a new one\n const group = acc[key] || []\n group.push(value)\n acc[key] = group\n return acc\n }\n\n return array.reduce(predicate, {})\n}\n\n/**\n * Creates an object composed of the own and inherited enumerable string keyed properties of object that\n * predicate doesn't return truthy for.\n *\n * @param obj - Object to have properties removed.\n * @param predicate - function that returns whether the property should be removed from the obj.\n *\n * @returns object\n */\nexport function omitBy<T extends object>(\n obj: T,\n predicate: (objElement: ValueOf<T>, k: string | number | symbol) => boolean,\n): Partial<T> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We know the keys are properties of T\n const keys: Array<keyof T> = Object.keys(obj) as Array<keyof T>\n const keysToKeep = keys.filter((kb) => !predicate(obj[kb], kb))\n return keysToKeep.reduce((acc: Partial<T>, key: keyof T) => {\n acc[key] = obj[key]\n return acc\n }, {})\n}\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n validateBaseTransaction,\n isAmount,\n} from './common'\n\n/**\n * Transaction Flags for an OfferCreate Transaction.\n *\n * @category Transaction Flags\n */\nexport enum OfferCreateFlags {\n /**\n * If enabled, the offer does not consume offers that exactly match it, and\n * instead becomes an Offer object in the ledger. It still consumes offers\n * that cross it.\n */\n tfPassive = 0x00010000,\n /**\n * Treat the offer as an Immediate or Cancel order. If enabled, the offer\n * never becomes a ledger object: it only tries to match existing offers in\n * the ledger. If the offer cannot match any offers immediately, it executes\n * \"successfully\" without trading any currency. In this case, the transaction\n * has the result code tesSUCCESS, but creates no Offer objects in the ledger.\n */\n tfImmediateOrCancel = 0x00020000,\n /**\n * Treat the offer as a Fill or Kill order . Only try to match existing\n * offers in the ledger, and only do so if the entire TakerPays quantity can\n * be obtained. If the fix1578 amendment is enabled and the offer cannot be\n * executed when placed, the transaction has the result code tecKILLED;\n * otherwise, the transaction uses the result code tesSUCCESS even when it was\n * killed without trading any currency.\n */\n tfFillOrKill = 0x00040000,\n /**\n * Exchange the entire TakerGets amount, even if it means obtaining more than\n * the TakerPays amount in exchange.\n */\n tfSell = 0x00080000,\n}\n\n/**\n * Map of flags to boolean values representing {@link OfferCreate} transaction\n * flags.\n *\n * @category Transaction Flags\n *\n * @example\n * ```typescript\n * const tx: OfferCreate = {\n * Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',\n * TakerGets: '43000.51',\n * TakerPays: '12928290425',\n * TransactionType: 'OfferCreate',\n * Flags: {\n * tfPassive: true,\n * tfFillOrKill: true,\n * },\n * }\n *\n * // Autofill the tx to see how flags actually look compared to the interface usage.\n * const autofilledTx = await client.autofill(tx)\n * console.log(autofilledTx)\n * // {\n * // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',\n * // TakerGets: '43000.51',\n * // TakerPays: '12928290425',\n * // TransactionType: 'OfferCreate',\n * // Flags: 327680,\n * // Sequence: 21970384,\n * // Fee: '12',\n * // LastLedgerSequence: 21970404\n * // }\n * ```\n */\nexport interface OfferCreateFlagsInterface extends GlobalFlagsInterface {\n tfPassive?: boolean\n tfImmediateOrCancel?: boolean\n tfFillOrKill?: boolean\n tfSell?: boolean\n}\n\n/**\n * An OfferCreate transaction is effectively a limit order . It defines an\n * intent to exchange currencies, and creates an Offer object if not completely.\n * Fulfilled when placed. Offers can be partially fulfilled.\n *\n * @category Transaction Models\n */\nexport interface OfferCreate extends BaseTransaction {\n TransactionType: 'OfferCreate'\n Flags?: number | OfferCreateFlagsInterface\n /**\n * Time after which the offer is no longer active, in seconds since the.\n * Ripple Epoch.\n */\n Expiration?: number\n /** An offer to delete first, specified in the same way as OfferCancel. */\n OfferSequence?: number\n /** The amount and type of currency being provided by the offer creator. */\n TakerGets: Amount\n /** The amount and type of currency being requested by the offer creator. */\n TakerPays: Amount\n}\n\n/**\n * Verify the form and type of an OfferCreate at runtime.\n *\n * @param tx - An OfferCreate Transaction.\n * @throws When the OfferCreate is Malformed.\n */\nexport function validateOfferCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.TakerGets === undefined) {\n throw new ValidationError('OfferCreate: missing field TakerGets')\n }\n\n if (tx.TakerPays === undefined) {\n throw new ValidationError('OfferCreate: missing field TakerPays')\n }\n\n if (typeof tx.TakerGets !== 'string' && !isAmount(tx.TakerGets)) {\n throw new ValidationError('OfferCreate: invalid TakerGets')\n }\n\n if (typeof tx.TakerPays !== 'string' && !isAmount(tx.TakerPays)) {\n throw new ValidationError('OfferCreate: invalid TakerPays')\n }\n\n if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') {\n throw new ValidationError('OfferCreate: invalid Expiration')\n }\n\n if (tx.OfferSequence !== undefined && typeof tx.OfferSequence !== 'number') {\n throw new ValidationError('OfferCreate: invalid OfferSequence')\n }\n}\n","/**\n * Prefix for hashing functions.\n *\n * These prefixes are inserted before the source material used to\n * generate various hashes. This is done to put each hash in its own\n * \"space.\" This way, two different types of objects with the\n * same binary data will produce different hashes.\n *\n * Each prefix is a 4-byte value with the last byte set to zero\n * and the first three bytes formed from the ASCII equivalent of\n * some arbitrary string. For example \"TXN\".\n */\n\nenum HashPrefix {\n // transaction plus signature to give transaction ID 'TXN'\n TRANSACTION_ID = 0x54584e00,\n\n // transaction plus metadata 'TND'\n TRANSACTION_NODE = 0x534e4400,\n\n // inner node in tree 'MIN'\n INNER_NODE = 0x4d494e00,\n\n // leaf node in tree 'MLN'\n LEAF_NODE = 0x4d4c4e00,\n\n // inner transaction to sign 'STX'\n TRANSACTION_SIGN = 0x53545800,\n\n // inner transaction to sign (TESTNET) 'stx'\n TRANSACTION_SIGN_TESTNET = 0x73747800,\n\n // inner transaction to multisign 'SMT'\n TRANSACTION_MULTISIGN = 0x534d5400,\n\n // ledger 'LWR'\n LEDGER = 0x4c575200,\n}\n\nexport default HashPrefix\n","import { BinaryParser } from '../serdes/binary-parser'\n\nimport { AccountID } from './account-id'\nimport { Currency } from './currency'\nimport { JsonObject, SerializedType } from './serialized-type'\nimport BigNumber from 'bignumber.js'\nimport { bytesToHex, concat, hexToBytes } from '@xrplf/isomorphic/utils'\nimport { readUInt32BE, writeUInt32BE } from '../utils'\nimport { Hash192 } from './hash-192'\n\n/**\n * Constants for validating amounts\n */\nconst MIN_IOU_EXPONENT = -96\nconst MAX_IOU_EXPONENT = 80\nconst MAX_IOU_PRECISION = 16\nconst MAX_DROPS = new BigNumber('1e17')\nconst MIN_XRP = new BigNumber('1e-6')\nconst mask = BigInt(0x00000000ffffffff)\nconst mptMask = BigInt(0x8000000000000000)\n\n/**\n * BigNumber configuration for Amount IOUs\n */\nBigNumber.config({\n EXPONENTIAL_AT: [\n MIN_IOU_EXPONENT - MAX_IOU_PRECISION,\n MAX_IOU_EXPONENT + MAX_IOU_PRECISION,\n ],\n})\n\ninterface AmountObjectIOU extends JsonObject {\n value: string\n currency: string\n issuer: string\n}\n\ninterface AmountObjectMPT extends JsonObject {\n value: string\n mpt_issuance_id: string\n}\n\n/**\n * Interface for JSON objects that represent amounts\n */\ntype AmountObject = AmountObjectIOU | AmountObjectMPT\n\n/**\n * Type guard for AmountObjectIOU\n */\nfunction isAmountObjectIOU(arg): arg is AmountObjectIOU {\n const keys = Object.keys(arg).sort()\n\n return (\n keys.length === 3 &&\n keys[0] === 'currency' &&\n keys[1] === 'issuer' &&\n keys[2] === 'value'\n )\n}\n\n/**\n * Type guard for AmountObjectMPT\n */\nfunction isAmountObjectMPT(arg): arg is AmountObjectMPT {\n const keys = Object.keys(arg).sort()\n\n return (\n keys.length === 2 && keys[0] === 'mpt_issuance_id' && keys[1] === 'value'\n )\n}\n\n/**\n * Class for serializing/Deserializing Amounts\n */\nclass Amount extends SerializedType {\n static defaultAmount: Amount = new Amount(hexToBytes('4000000000000000'))\n\n constructor(bytes: Uint8Array) {\n super(bytes ?? Amount.defaultAmount.bytes)\n }\n\n /**\n * Construct an amount from an IOU, MPT or string amount\n *\n * @param value An Amount, object representing an IOU, or a string\n * representing an integer amount\n * @returns An Amount object\n */\n static from<T extends Amount | AmountObject | string>(value: T): Amount {\n if (value instanceof Amount) {\n return value\n }\n\n let amount = new Uint8Array(8)\n if (typeof value === 'string') {\n Amount.assertXrpIsValid(value)\n\n const number = BigInt(value)\n\n const intBuf = [new Uint8Array(4), new Uint8Array(4)]\n writeUInt32BE(intBuf[0], Number(number >> BigInt(32)), 0)\n writeUInt32BE(intBuf[1], Number(number & BigInt(mask)), 0)\n\n amount = concat(intBuf)\n\n amount[0] |= 0x40\n\n return new Amount(amount)\n }\n\n if (isAmountObjectIOU(value)) {\n const number = new BigNumber(value.value)\n Amount.assertIouIsValid(number)\n\n if (number.isZero()) {\n amount[0] |= 0x80\n } else {\n const integerNumberString = number\n .times(`1e${-((number.e || 0) - 15)}`)\n .abs()\n .toString()\n\n const num = BigInt(integerNumberString)\n const intBuf = [new Uint8Array(4), new Uint8Array(4)]\n writeUInt32BE(intBuf[0], Number(num >> BigInt(32)), 0)\n writeUInt32BE(intBuf[1], Number(num & BigInt(mask)), 0)\n\n amount = concat(intBuf)\n\n amount[0] |= 0x80\n\n if (number.gt(new BigNumber(0))) {\n amount[0] |= 0x40\n }\n\n const exponent = (number.e || 0) - 15\n const exponentByte = 97 + exponent\n amount[0] |= exponentByte >>> 2\n amount[1] |= (exponentByte & 0x03) << 6\n }\n\n const currency = Currency.from(value.currency).toBytes()\n const issuer = AccountID.from(value.issuer).toBytes()\n return new Amount(concat([amount, currency, issuer]))\n }\n\n if (isAmountObjectMPT(value)) {\n Amount.assertMptIsValid(value.value)\n\n let leadingByte = new Uint8Array(1)\n leadingByte[0] |= 0x60\n\n const num = BigInt(value.value)\n\n const intBuf = [new Uint8Array(4), new Uint8Array(4)]\n writeUInt32BE(intBuf[0], Number(num >> BigInt(32)), 0)\n writeUInt32BE(intBuf[1], Number(num & BigInt(mask)), 0)\n\n amount = concat(intBuf)\n\n const mptIssuanceID = Hash192.from(value.mpt_issuance_id).toBytes()\n return new Amount(concat([leadingByte, amount, mptIssuanceID]))\n }\n\n throw new Error('Invalid type to construct an Amount')\n }\n\n /**\n * Read an amount from a BinaryParser\n *\n * @param parser BinaryParser to read the Amount from\n * @returns An Amount object\n */\n static fromParser(parser: BinaryParser): Amount {\n const isIOU = parser.peek() & 0x80\n if (isIOU) return new Amount(parser.read(48))\n\n // the amount can be either MPT or XRP at this point\n const isMPT = parser.peek() & 0x20\n const numBytes = isMPT ? 33 : 8\n return new Amount(parser.read(numBytes))\n }\n\n /**\n * Get the JSON representation of this Amount\n *\n * @returns the JSON interpretation of this.bytes\n */\n toJSON(): AmountObject | string {\n if (this.isNative()) {\n const bytes = this.bytes\n const isPositive = bytes[0] & 0x40\n const sign = isPositive ? '' : '-'\n bytes[0] &= 0x3f\n\n const msb = BigInt(readUInt32BE(bytes.slice(0, 4), 0))\n const lsb = BigInt(readUInt32BE(bytes.slice(4), 0))\n const num = (msb << BigInt(32)) | lsb\n\n return `${sign}${num.toString()}`\n }\n\n if (this.isIOU()) {\n const parser = new BinaryParser(this.toString())\n const mantissa = parser.read(8)\n const currency = Currency.fromParser(parser) as Currency\n const issuer = AccountID.fromParser(parser) as AccountID\n\n const b1 = mantissa[0]\n const b2 = mantissa[1]\n\n const isPositive = b1 & 0x40\n const sign = isPositive ? '' : '-'\n const exponent = ((b1 & 0x3f) << 2) + ((b2 & 0xff) >> 6) - 97\n\n mantissa[0] = 0\n mantissa[1] &= 0x3f\n const value = new BigNumber(`${sign}0x${bytesToHex(mantissa)}`).times(\n `1e${exponent}`,\n )\n Amount.assertIouIsValid(value)\n\n return {\n value: value.toString(),\n currency: currency.toJSON(),\n issuer: issuer.toJSON(),\n }\n }\n\n if (this.isMPT()) {\n const parser = new BinaryParser(this.toString())\n const leadingByte = parser.read(1)\n const amount = parser.read(8)\n const mptID = Hash192.fromParser(parser) as Hash192\n\n const isPositive = leadingByte[0] & 0x40\n const sign = isPositive ? '' : '-'\n\n const msb = BigInt(readUInt32BE(amount.slice(0, 4), 0))\n const lsb = BigInt(readUInt32BE(amount.slice(4), 0))\n const num = (msb << BigInt(32)) | lsb\n\n return {\n value: `${sign}${num.toString()}`,\n mpt_issuance_id: mptID.toString(),\n }\n }\n\n throw new Error('Invalid amount to construct JSON')\n }\n\n /**\n * Validate XRP amount\n *\n * @param amount String representing XRP amount\n * @returns void, but will throw if invalid amount\n */\n private static assertXrpIsValid(amount: string): void {\n if (amount.indexOf('.') !== -1) {\n throw new Error(`${amount.toString()} is an illegal amount`)\n }\n\n const decimal = new BigNumber(amount)\n if (!decimal.isZero()) {\n if (decimal.lt(MIN_XRP) || decimal.gt(MAX_DROPS)) {\n throw new Error(`${amount.toString()} is an illegal amount`)\n }\n }\n }\n\n /**\n * Validate IOU.value amount\n *\n * @param decimal BigNumber object representing IOU.value\n * @returns void, but will throw if invalid amount\n */\n private static assertIouIsValid(decimal: BigNumber): void {\n if (!decimal.isZero()) {\n const p = decimal.precision()\n const e = (decimal.e || 0) - 15\n if (\n p > MAX_IOU_PRECISION ||\n e > MAX_IOU_EXPONENT ||\n e < MIN_IOU_EXPONENT\n ) {\n throw new Error('Decimal precision out of range')\n }\n this.verifyNoDecimal(decimal)\n }\n }\n\n /**\n * Validate MPT.value amount\n *\n * @param decimal BigNumber object representing MPT.value\n * @returns void, but will throw if invalid amount\n */\n private static assertMptIsValid(amount: string): void {\n if (amount.indexOf('.') !== -1) {\n throw new Error(`${amount.toString()} is an illegal amount`)\n }\n\n const decimal = new BigNumber(amount)\n if (!decimal.isZero()) {\n if (decimal < BigNumber(0)) {\n throw new Error(`${amount.toString()} is an illegal amount`)\n }\n\n if (Number(BigInt(amount) & BigInt(mptMask)) != 0) {\n throw new Error(`${amount.toString()} is an illegal amount`)\n }\n }\n }\n\n /**\n * Ensure that the value after being multiplied by the exponent does not\n * contain a decimal.\n *\n * @param decimal a Decimal object\n * @returns a string of the object without a decimal\n */\n private static verifyNoDecimal(decimal: BigNumber): void {\n const integerNumberString = decimal\n .times(`1e${-((decimal.e || 0) - 15)}`)\n .abs()\n .toString()\n\n if (integerNumberString.indexOf('.') !== -1) {\n throw new Error('Decimal place found in integerNumberString')\n }\n }\n\n /**\n * Test if this amount is in units of Native Currency(XRP)\n *\n * @returns true if Native (XRP)\n */\n private isNative(): boolean {\n return (this.bytes[0] & 0x80) === 0 && (this.bytes[0] & 0x20) === 0\n }\n\n /**\n * Test if this amount is in units of MPT\n *\n * @returns true if MPT\n */\n private isMPT(): boolean {\n return (this.bytes[0] & 0x80) === 0 && (this.bytes[0] & 0x20) !== 0\n }\n\n /**\n * Test if this amount is in units of IOU\n *\n * @returns true if IOU\n */\n private isIOU(): boolean {\n return (this.bytes[0] & 0x80) !== 0\n }\n}\n\nexport { Amount, AmountObject }\n","/* eslint-disable func-style */\n\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\nimport { coreTypes } from './types'\nimport { BinaryParser } from './serdes/binary-parser'\nimport { AccountID } from './types/account-id'\nimport { HashPrefix } from './hash-prefixes'\nimport { BinarySerializer, BytesList } from './serdes/binary-serializer'\nimport { sha512Half, transactionID } from './hashes'\nimport {\n type XrplDefinitionsBase,\n DEFAULT_DEFINITIONS,\n type FieldInstance,\n} from './enums'\nimport { STObject } from './types/st-object'\nimport { JsonObject } from './types/serialized-type'\n\n/**\n * Construct a BinaryParser\n *\n * @param bytes hex-string or Uint8Array to construct BinaryParser from\n * @param definitions rippled definitions used to parse the values of transaction types and such.\n * Can be customized for sidechains and amendments.\n * @returns BinaryParser\n */\nconst makeParser = (\n bytes: string | Uint8Array,\n definitions?: XrplDefinitionsBase,\n): BinaryParser =>\n new BinaryParser(\n bytes instanceof Uint8Array ? bytesToHex(bytes) : bytes,\n definitions,\n )\n\n/**\n * Parse BinaryParser into JSON\n *\n * @param parser BinaryParser object\n * @param definitions rippled definitions used to parse the values of transaction types and such.\n * Can be customized for sidechains and amendments.\n * @returns JSON for the bytes in the BinaryParser\n */\nconst readJSON = (\n parser: BinaryParser,\n definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,\n): JsonObject =>\n (parser.readType(coreTypes.STObject) as STObject).toJSON(definitions)\n\n/**\n * Parse a hex-string into its JSON interpretation\n *\n * @param bytes hex-string to parse into JSON\n * @param definitions rippled definitions used to parse the values of transaction types and such.\n * Can be customized for sidechains and amendments.\n * @returns JSON\n */\nconst binaryToJSON = (\n bytes: string,\n definitions?: XrplDefinitionsBase,\n): JsonObject => readJSON(makeParser(bytes, definitions), definitions)\n\n/**\n * Interface for passing parameters to SerializeObject\n *\n * @field set signingFieldOnly to true if you want to serialize only signing fields\n */\ninterface OptionObject {\n prefix?: Uint8Array\n suffix?: Uint8Array\n signingFieldsOnly?: boolean\n definitions?: XrplDefinitionsBase\n}\n\n/**\n * Function to serialize JSON object representing a transaction\n *\n * @param object JSON object to serialize\n * @param opts options for serializing, including optional prefix, suffix, signingFieldOnly, and definitions\n * @returns A Uint8Array containing the serialized object\n */\nfunction serializeObject(\n object: JsonObject,\n opts: OptionObject = {},\n): Uint8Array {\n const { prefix, suffix, signingFieldsOnly = false, definitions } = opts\n const bytesList = new BytesList()\n\n if (prefix) {\n bytesList.put(prefix)\n }\n\n const filter = signingFieldsOnly\n ? (f: FieldInstance): boolean => f.isSigningField\n : undefined\n ;(coreTypes.STObject as typeof STObject)\n .from(object, filter, definitions)\n .toBytesSink(bytesList)\n\n if (suffix) {\n bytesList.put(suffix)\n }\n\n return bytesList.toBytes()\n}\n\n/**\n * Serialize an object for signing\n *\n * @param transaction Transaction to serialize\n * @param prefix Prefix bytes to put before the serialized object\n * @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns A Uint8Array with the serialized object\n */\nfunction signingData(\n transaction: JsonObject,\n prefix: Uint8Array = HashPrefix.transactionSig,\n opts: { definitions?: XrplDefinitionsBase } = {},\n): Uint8Array {\n return serializeObject(transaction, {\n prefix,\n signingFieldsOnly: true,\n definitions: opts.definitions,\n })\n}\n\n/**\n * Interface describing fields required for a Claim\n */\ninterface ClaimObject extends JsonObject {\n channel: string\n amount: string | number\n}\n\n/**\n * Serialize a signingClaim\n *\n * @param claim A claim object to serialize\n * @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns the serialized object with appropriate prefix\n */\nfunction signingClaimData(claim: ClaimObject): Uint8Array {\n const num = BigInt(String(claim.amount))\n const prefix = HashPrefix.paymentChannelClaim\n const channel = coreTypes.Hash256.from(claim.channel).toBytes()\n const amount = coreTypes.UInt64.from(num).toBytes()\n\n const bytesList = new BytesList()\n\n bytesList.put(prefix)\n bytesList.put(channel)\n bytesList.put(amount)\n return bytesList.toBytes()\n}\n\n/**\n * Serialize a transaction object for multiSigning\n *\n * @param transaction transaction to serialize\n * @param signingAccount Account to sign the transaction with\n * @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.\n * @returns serialized transaction with appropriate prefix and suffix\n */\nfunction multiSigningData(\n transaction: JsonObject,\n signingAccount: string | AccountID,\n opts: { definitions: XrplDefinitionsBase } = {\n definitions: DEFAULT_DEFINITIONS,\n },\n): Uint8Array {\n const prefix = HashPrefix.transactionMultiSig\n const suffix = coreTypes.AccountID.from(signingAccount).toBytes()\n return serializeObject(transaction, {\n prefix,\n suffix,\n signingFieldsOnly: true,\n definitions: opts.definitions,\n })\n}\n\n/**\n * Interface describing fields required for a Batch signer\n * @property flags - Flags indicating Batch transaction properties\n * @property txIDs - Array of transaction IDs included in the Batch\n */\ninterface BatchObject extends JsonObject {\n flags: number\n txIDs: string[]\n}\n\n/**\n * Serialize a signingClaim\n *\n * @param batch A Batch object to serialize.\n * @returns the serialized object with appropriate prefix\n */\nfunction signingBatchData(batch: BatchObject): Uint8Array {\n if (batch.flags == null) {\n throw Error(\"No field `flags'\")\n }\n if (batch.txIDs == null) {\n throw Error('No field `txIDs`')\n }\n const prefix = HashPrefix.batch\n const flags = coreTypes.UInt32.from(batch.flags).toBytes()\n const txIDsLength = coreTypes.UInt32.from(batch.txIDs.length).toBytes()\n\n const bytesList = new BytesList()\n\n bytesList.put(prefix)\n bytesList.put(flags)\n bytesList.put(txIDsLength)\n batch.txIDs.forEach((txID: string) => {\n bytesList.put(coreTypes.Hash256.from(txID).toBytes())\n })\n\n return bytesList.toBytes()\n}\n\nexport {\n BinaryParser,\n BinarySerializer,\n BytesList,\n ClaimObject,\n BatchObject,\n makeParser,\n serializeObject,\n readJSON,\n multiSigningData,\n signingData,\n signingClaimData,\n binaryToJSON,\n sha512Half,\n transactionID,\n signingBatchData,\n}\n","import {\n ResponseFormatError,\n RippledError,\n TimeoutError,\n XrplError,\n} from '../errors'\nimport type { APIVersion } from '../models'\nimport { Response, RequestResponseMap } from '../models/methods'\nimport { BaseRequest, ErrorResponse } from '../models/methods/baseMethod'\n\ninterface PromiseEntry<T> {\n resolve: (value: T | PromiseLike<T>) => void\n reject: (value: Error) => void\n timer: ReturnType<typeof setTimeout>\n}\n\n/**\n * Manage all the requests made to the websocket, and their async responses\n * that come in from the WebSocket. Responses come in over the WS connection\n * after-the-fact, so this manager will tie that response to resolve the\n * original request.\n */\nexport default class RequestManager {\n private nextId = 0\n private readonly promisesAwaitingResponse = new Map<\n string | number,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Necessary and typed wrapper in addPromise method\n PromiseEntry<any>\n >()\n\n /**\n * Adds a promise to the collection of promises awaiting response. Handles typing with generics.\n *\n * @template T The generic type parameter representing the resolved value type.\n * @param newId - The identifier for the new promise.\n * @param timer - The timer associated with the promise.\n * @returns A promise that resolves to the specified generic type.\n */\n public async addPromise<\n R extends BaseRequest,\n T = RequestResponseMap<R, APIVersion>,\n >(newId: string | number, timer: ReturnType<typeof setTimeout>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.promisesAwaitingResponse.set(newId, {\n resolve,\n reject,\n timer,\n })\n })\n }\n\n /**\n * Successfully resolves a request.\n *\n * @param id - ID of the request.\n * @param response - Response to return.\n * @throws Error if no existing promise with the given ID.\n */\n public resolve(\n id: string | number,\n response: Partial<Response<APIVersion>>,\n ): void {\n const promise = this.promisesAwaitingResponse.get(id)\n if (promise == null) {\n throw new XrplError(`No existing promise with id ${id}`, {\n type: 'resolve',\n response,\n })\n }\n clearTimeout(promise.timer)\n promise.resolve(response)\n this.deletePromise(id)\n }\n\n /**\n * Rejects a request.\n *\n * @param id - ID of the request.\n * @param error - Error to throw with the reject.\n * @throws Error if no existing promise with the given ID.\n */\n public reject(id: string | number, error: Error): void {\n const promise = this.promisesAwaitingResponse.get(id)\n if (promise == null) {\n throw new XrplError(`No existing promise with id ${id}`, {\n type: 'reject',\n error,\n })\n }\n clearTimeout(promise.timer)\n // TODO: figure out how to have a better stack trace for an error\n promise.reject(error)\n this.deletePromise(id)\n }\n\n /**\n * Reject all pending requests.\n *\n * @param error - Error to throw with the reject.\n */\n public rejectAll(error: Error): void {\n this.promisesAwaitingResponse.forEach((_promise, id, _map) => {\n this.reject(id, error)\n this.deletePromise(id)\n })\n }\n\n /**\n * Creates a new WebSocket request. This sets up a timeout timer to catch\n * hung responses, and a promise that will resolve with the response once\n * the response is seen & handled.\n *\n * @param request - Request to create.\n * @param timeout - Timeout length to catch hung responses.\n * @returns Request ID, new request form, and the promise for resolving the request.\n * @throws XrplError if request with the same ID is already pending.\n */\n public createRequest<\n R extends BaseRequest,\n T = RequestResponseMap<R, APIVersion>,\n >(request: R, timeout: number): [string | number, string, Promise<T>] {\n let newId: string | number\n if (request.id == null) {\n newId = this.nextId\n this.nextId += 1\n } else {\n newId = request.id\n }\n const newRequest = JSON.stringify({ ...request, id: newId })\n // Typing required for Jest running in browser\n const timer: ReturnType<typeof setTimeout> = setTimeout(() => {\n this.reject(\n newId,\n new TimeoutError(\n `Timeout for request: ${JSON.stringify(request)} with id ${newId}`,\n request,\n ),\n )\n }, timeout)\n /*\n * Node.js won't exit if a timer is still running, so we tell Node to ignore.\n * (Node will still wait for the request to complete).\n */\n // The following type assertions are required to get this code to pass in browser environments\n // where setTimeout has a different type\n // eslint-disable-next-line max-len -- Necessary to disable both rules.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access -- Reason above.\n if ((timer as unknown as any).unref) {\n // eslint-disable-next-line max-len -- Necessary to disable both rules.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call -- Reason above.\n ;(timer as unknown as any).unref()\n }\n if (this.promisesAwaitingResponse.has(newId)) {\n clearTimeout(timer)\n throw new XrplError(\n `Response with id '${newId}' is already pending`,\n request,\n )\n }\n const newPromise = new Promise<T>((resolve, reject) => {\n this.promisesAwaitingResponse.set(newId, {\n resolve,\n reject,\n timer,\n })\n })\n\n return [newId, newRequest, newPromise]\n }\n\n /**\n * Handle a \"response\". Responses match to the earlier request handlers,\n * and resolve/reject based on the data received.\n *\n * @param response - The response to handle.\n * @throws ResponseFormatError if the response format is invalid, RippledError if rippled returns an error.\n */\n // eslint-disable-next-line complexity -- handling a response is complex\n public handleResponse(\n response: Partial<Response<APIVersion> | ErrorResponse>,\n ): void {\n if (\n response.id == null ||\n !(typeof response.id === 'string' || typeof response.id === 'number')\n ) {\n throw new ResponseFormatError('valid id not found in response', response)\n }\n if (!this.promisesAwaitingResponse.has(response.id)) {\n return\n }\n if (response.status == null) {\n const error = new ResponseFormatError('Response has no status')\n this.reject(response.id, error)\n }\n if (response.status === 'error') {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- We know this must be true\n const errorResponse = response as Partial<ErrorResponse>\n const error = new RippledError(\n errorResponse.error_message ??\n errorResponse.error_exception ??\n errorResponse.error,\n errorResponse,\n )\n this.reject(response.id, error)\n return\n }\n if (response.status !== 'success') {\n const error = new ResponseFormatError(\n `unrecognized response.status: ${response.status ?? ''}`,\n response,\n )\n this.reject(response.id, error)\n return\n }\n // status no longer needed because error is thrown if status is not \"success\"\n delete response.status\n this.resolve(response.id, response)\n }\n\n /**\n * Delete a promise after it has been returned.\n *\n * @param id - ID of the request.\n */\n private deletePromise(id: string | number): void {\n this.promisesAwaitingResponse.delete(id)\n }\n}\n","import { ed25519 as nobleEd25519 } from '@noble/curves/ed25519'\nimport { bytesToHex } from '@xrplf/isomorphic/utils'\n\nimport type { HexString, SigningScheme } from '../../types'\nimport assert from '../../utils/assert'\nimport Sha512 from '../../utils/Sha512'\n\nconst ED_PREFIX = 'ED'\n\nconst ed25519: SigningScheme = {\n deriveKeypair(entropy: Uint8Array): {\n privateKey: string\n publicKey: string\n } {\n const rawPrivateKey = Sha512.half(entropy)\n const privateKey = ED_PREFIX + bytesToHex(rawPrivateKey)\n const publicKey =\n ED_PREFIX + bytesToHex(nobleEd25519.getPublicKey(rawPrivateKey))\n return { privateKey, publicKey }\n },\n\n sign(message: Uint8Array, privateKey: HexString): string {\n assert.ok(message instanceof Uint8Array, 'message must be array of octets')\n assert.ok(\n privateKey.length === 66,\n 'private key must be 33 bytes including prefix',\n )\n return bytesToHex(nobleEd25519.sign(message, privateKey.slice(2)))\n },\n\n verify(\n message: Uint8Array,\n signature: HexString,\n publicKey: string,\n ): boolean {\n // Unlikely to be triggered as these are internal and guarded by getAlgorithmFromKey\n assert.ok(\n publicKey.length === 66,\n 'public key must be 33 bytes including prefix',\n )\n return nobleEd25519.verify(\n signature,\n message,\n // Remove the 0xED prefix\n publicKey.slice(2),\n // By default, set zip215 to false for compatibility reasons.\n // ZIP 215 is a stricter Ed25519 signature verification scheme.\n // However, setting it to false adheres to the more commonly used\n // RFC8032 / NIST186-5 standards, making it compatible with systems\n // like the XRP Ledger.\n { zip215: false },\n )\n },\n}\n\nexport default ed25519\n","/* eslint-disable no-bitwise -- flags require bitwise operations */\nimport { ValidationError } from '../../errors'\nimport {\n AccountRootFlagsInterface,\n AccountRootFlags,\n} from '../ledger/AccountRoot'\nimport { AccountSetTfFlags } from '../transactions/accountSet'\nimport { AMMClawbackFlags } from '../transactions/AMMClawback'\nimport { AMMDepositFlags } from '../transactions/AMMDeposit'\nimport { AMMWithdrawFlags } from '../transactions/AMMWithdraw'\nimport { BatchFlags } from '../transactions/batch'\nimport { GlobalFlags } from '../transactions/common'\nimport { MPTokenAuthorizeFlags } from '../transactions/MPTokenAuthorize'\nimport { MPTokenIssuanceCreateFlags } from '../transactions/MPTokenIssuanceCreate'\nimport { MPTokenIssuanceSetFlags } from '../transactions/MPTokenIssuanceSet'\nimport { NFTokenCreateOfferFlags } from '../transactions/NFTokenCreateOffer'\nimport { NFTokenMintFlags } from '../transactions/NFTokenMint'\nimport { OfferCreateFlags } from '../transactions/offerCreate'\nimport { PaymentFlags } from '../transactions/payment'\nimport { PaymentChannelClaimFlags } from '../transactions/paymentChannelClaim'\nimport type { Transaction } from '../transactions/transaction'\nimport { TrustSetFlags } from '../transactions/trustSet'\nimport { VaultCreateFlags } from '../transactions/vaultCreate'\nimport { XChainModifyBridgeFlags } from '../transactions/XChainModifyBridge'\n\nimport { isFlagEnabled } from '.'\n\n/**\n * Convert an AccountRoot Flags number into an interface for easy interpretation.\n *\n * @param flags - A number which is the bitwise and of all enabled AccountRootFlagsInterface.\n * @returns An interface with all flags as booleans.\n */\nexport function parseAccountRootFlags(\n flags: number,\n): AccountRootFlagsInterface {\n const flagsInterface: AccountRootFlagsInterface = {}\n\n // If we use keys all will be strings and enums are reversed during transpilation\n Object.values(AccountRootFlags).forEach((flag) => {\n if (\n typeof flag === 'string' &&\n isFlagEnabled(flags, AccountRootFlags[flag])\n ) {\n flagsInterface[flag] = true\n }\n })\n\n return flagsInterface\n}\n\nconst txToFlag = {\n AccountSet: AccountSetTfFlags,\n AMMClawback: AMMClawbackFlags,\n AMMDeposit: AMMDepositFlags,\n AMMWithdraw: AMMWithdrawFlags,\n Batch: BatchFlags,\n MPTokenAuthorize: MPTokenAuthorizeFlags,\n MPTokenIssuanceCreate: MPTokenIssuanceCreateFlags,\n MPTokenIssuanceSet: MPTokenIssuanceSetFlags,\n NFTokenCreateOffer: NFTokenCreateOfferFlags,\n NFTokenMint: NFTokenMintFlags,\n OfferCreate: OfferCreateFlags,\n PaymentChannelClaim: PaymentChannelClaimFlags,\n Payment: PaymentFlags,\n TrustSet: TrustSetFlags,\n VaultCreate: VaultCreateFlags,\n XChainModifyBridge: XChainModifyBridgeFlags,\n}\n\nfunction isTxToFlagKey(\n transactionType: string,\n): transactionType is keyof typeof txToFlag {\n return transactionType in txToFlag\n}\n\n/**\n * Sets a transaction's flags to its numeric representation.\n *\n * @deprecated\n * This utility function is deprecated.\n * Use convertTxFlagsToNumber() instead and use the returned value to modify the Transaction.Flags from the caller.\n *\n * @param tx - A transaction to set its flags to its numeric representation.\n */\nexport function setTransactionFlagsToNumber(tx: Transaction): void {\n // eslint-disable-next-line no-console -- intended deprecation warning\n console.warn(\n 'This function is deprecated. Use convertTxFlagsToNumber() instead and use the returned value to modify the Transaction.Flags from the caller.',\n )\n\n if (tx.Flags) {\n // eslint-disable-next-line no-param-reassign -- intended param reassign in setter, retain old functionality for compatibility\n tx.Flags = convertTxFlagsToNumber(tx)\n }\n}\n\n/**\n * Returns a Transaction's Flags as its numeric representation.\n *\n * @param tx - A Transaction to parse Flags for\n * @returns A numerical representation of a Transaction's Flags\n */\nexport function convertTxFlagsToNumber(tx: Transaction): number {\n const txFlags = tx.Flags\n if (txFlags == null) {\n return 0\n }\n if (typeof txFlags === 'number') {\n return txFlags\n }\n\n if (isTxToFlagKey(tx.TransactionType)) {\n const flagEnum = txToFlag[tx.TransactionType]\n return Object.keys(txFlags).reduce((resultFlags, flag) => {\n if (flagEnum[flag] == null && GlobalFlags[flag] == null) {\n throw new ValidationError(`Invalid flag ${flag}.`)\n }\n\n return txFlags[flag]\n ? resultFlags | (flagEnum[flag] || GlobalFlags[flag])\n : resultFlags\n }, 0)\n }\n\n return Object.keys(txFlags).reduce((resultFlags, flag) => {\n if (GlobalFlags[flag] == null) {\n throw new ValidationError(\n `Invalid flag ${flag}. Valid flags are ${JSON.stringify(GlobalFlags)}`,\n )\n }\n\n return txFlags[flag] ? resultFlags | GlobalFlags[flag] : resultFlags\n }, 0)\n}\n\n/**\n * Convert a Transaction flags property into a map for easy interpretation.\n *\n * @param tx - A transaction to parse flags for.\n * @returns A map with all flags as booleans.\n */\nexport function parseTransactionFlags(tx: Transaction): object {\n const flags = convertTxFlagsToNumber(tx)\n if (flags === 0) {\n return {}\n }\n\n const booleanFlagMap = {}\n\n if (isTxToFlagKey(tx.TransactionType)) {\n const transactionTypeFlags = txToFlag[tx.TransactionType]\n Object.values(transactionTypeFlags).forEach((flag) => {\n if (\n typeof flag === 'string' &&\n isFlagEnabled(flags, transactionTypeFlags[flag])\n ) {\n booleanFlagMap[flag] = true\n }\n })\n }\n\n Object.values(GlobalFlags).forEach((flag) => {\n if (typeof flag === 'string' && isFlagEnabled(flags, GlobalFlags[flag])) {\n booleanFlagMap[flag] = true\n }\n })\n\n return booleanFlagMap\n}\n","import {\n BaseTransaction,\n isNumber,\n validateBaseTransaction,\n validateRequiredField,\n} from './common'\n\n/**\n * Delete an Oracle ledger entry.\n *\n * @category Transaction Models\n */\nexport interface OracleDelete extends BaseTransaction {\n TransactionType: 'OracleDelete'\n\n /**\n * A unique identifier of the price oracle for the Account.\n */\n OracleDocumentID: number\n}\n\n/**\n * Verify the form and type of a OracleDelete at runtime.\n *\n * @param tx - A OracleDelete Transaction.\n * @throws When the OracleDelete is malformed.\n */\nexport function validateOracleDelete(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n validateRequiredField(tx, 'OracleDocumentID', isNumber)\n}\n","/**\n * LedgerEntry type definitions are exported in their own namespace to prevent\n * collisions of the DepositPreauth SLE and Transaction. LedgerEntries are used\n * by the client less often, and in most scenarios, like when parsing a\n * response, the client won't need to import the type. If it is required to use\n * a Ledger Entry, import `LedgerEntry`, and access individual ledger entry\n * types on the `LedgerEntry` namespace.\n */\nexport * as LedgerEntry from './ledger'\nexport {\n parseAccountRootFlags,\n setTransactionFlagsToNumber,\n convertTxFlagsToNumber,\n parseTransactionFlags,\n} from './utils/flags'\nexport * from './methods'\nexport * from './transactions'\nexport * from './common'\n","\"use strict\";\n/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateMnemonic = generateMnemonic;\nexports.mnemonicToEntropy = mnemonicToEntropy;\nexports.entropyToMnemonic = entropyToMnemonic;\nexports.validateMnemonic = validateMnemonic;\nexports.mnemonicToSeed = mnemonicToSeed;\nexports.mnemonicToSeedSync = mnemonicToSeedSync;\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nconst pbkdf2_1 = require(\"@noble/hashes/pbkdf2\");\nconst sha2_1 = require(\"@noble/hashes/sha2\");\nconst utils_1 = require(\"@noble/hashes/utils\");\nconst base_1 = require(\"@scure/base\");\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n (0, utils_1.abytes)(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nfunction generateMnemonic(wordlist, strength = 128) {\n (0, utils_1.anumber)(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic((0, utils_1.randomBytes)(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([((0, sha2_1.sha256)(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nfunction mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nfunction entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nfunction validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nfunction mnemonicToSeed(mnemonic, passphrase = '') {\n return (0, pbkdf2_1.pbkdf2Async)(sha2_1.sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nfunction mnemonicToSeedSync(mnemonic, passphrase = '') {\n return (0, pbkdf2_1.pbkdf2)(sha2_1.sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","export { BaseTransaction, isMPTAmount } from './common'\nexport {\n validate,\n PseudoTransaction,\n SubmittableTransaction,\n TransactionAndMetadata,\n Transaction,\n} from './transaction'\nexport * from './metadata'\nexport {\n AccountSetAsfFlags,\n AccountSetTfFlags,\n AccountSetFlagsInterface,\n AccountSet,\n} from './accountSet'\nexport { AccountDelete } from './accountDelete'\nexport { AMMBid } from './AMMBid'\nexport {\n AMMClawbackFlags,\n AMMClawbackFlagsInterface,\n AMMClawback,\n} from './AMMClawback'\nexport { AMMCreate } from './AMMCreate'\nexport { AMMDelete } from './AMMDelete'\nexport {\n AMMDepositFlags,\n AMMDepositFlagsInterface,\n AMMDeposit,\n} from './AMMDeposit'\nexport { AMMVote } from './AMMVote'\nexport {\n AMMWithdrawFlags,\n AMMWithdrawFlagsInterface,\n AMMWithdraw,\n} from './AMMWithdraw'\nexport { Batch } from './batch'\nexport { CheckCancel } from './checkCancel'\nexport { CheckCash } from './checkCash'\nexport { CheckCreate } from './checkCreate'\nexport { Clawback } from './clawback'\nexport { CredentialAccept } from './CredentialAccept'\nexport { CredentialCreate } from './CredentialCreate'\nexport { CredentialDelete } from './CredentialDelete'\nexport { DIDDelete } from './DIDDelete'\nexport { DIDSet } from './DIDSet'\nexport { DelegateSet, Permission } from './delegateSet'\nexport { DepositPreauth } from './depositPreauth'\nexport { EscrowCancel } from './escrowCancel'\nexport { EscrowCreate } from './escrowCreate'\nexport { EscrowFinish } from './escrowFinish'\nexport { EnableAmendment, EnableAmendmentFlags } from './enableAmendment'\nexport {\n MPTokenAuthorize,\n MPTokenAuthorizeFlags,\n MPTokenAuthorizeFlagsInterface,\n} from './MPTokenAuthorize'\nexport {\n MPTokenIssuanceCreate,\n MPTokenIssuanceCreateFlags,\n MPTokenIssuanceCreateFlagsInterface,\n} from './MPTokenIssuanceCreate'\nexport { MPTokenIssuanceDestroy } from './MPTokenIssuanceDestroy'\nexport {\n MPTokenIssuanceSet,\n MPTokenIssuanceSetFlags,\n MPTokenIssuanceSetFlagsInterface,\n} from './MPTokenIssuanceSet'\nexport { NFTokenAcceptOffer } from './NFTokenAcceptOffer'\nexport { NFTokenBurn } from './NFTokenBurn'\nexport { NFTokenCancelOffer } from './NFTokenCancelOffer'\nexport {\n NFTokenCreateOffer,\n NFTokenCreateOfferFlags,\n NFTokenCreateOfferFlagsInterface,\n} from './NFTokenCreateOffer'\nexport {\n NFTokenMint,\n NFTokenMintFlags,\n NFTokenMintFlagsInterface,\n} from './NFTokenMint'\nexport { NFTokenModify, validateNFTokenModify } from './NFTokenModify'\nexport { OfferCancel } from './offerCancel'\nexport {\n OfferCreateFlags,\n OfferCreateFlagsInterface,\n OfferCreate,\n} from './offerCreate'\nexport { OracleDelete } from './oracleDelete'\nexport { OracleSet } from './oracleSet'\nexport { PaymentFlags, PaymentFlagsInterface, Payment } from './payment'\nexport {\n PaymentChannelClaimFlags,\n PaymentChannelClaimFlagsInterface,\n PaymentChannelClaim,\n} from './paymentChannelClaim'\nexport { PaymentChannelCreate } from './paymentChannelCreate'\nexport { PaymentChannelFund } from './paymentChannelFund'\nexport { PermissionedDomainSet } from './permissionedDomainSet'\nexport { PermissionedDomainDelete } from './permissionedDomainDelete'\nexport { SetFee, SetFeePreAmendment, SetFeePostAmendment } from './setFee'\nexport { SetRegularKey } from './setRegularKey'\nexport { SignerListSet } from './signerListSet'\nexport { TicketCreate } from './ticketCreate'\nexport { TrustSetFlagsInterface, TrustSetFlags, TrustSet } from './trustSet'\nexport { UNLModify } from './UNLModify'\nexport { VaultClawback } from './vaultClawback'\nexport {\n VaultCreate,\n VaultCreateFlags,\n VaultCreateFlagsInterface,\n VaultWithdrawalPolicy,\n} from './vaultCreate'\nexport { VaultDelete } from './vaultDelete'\nexport { VaultDeposit } from './vaultDeposit'\nexport { VaultSet } from './vaultSet'\nexport { VaultWithdraw } from './vaultWithdraw'\nexport { XChainAddAccountCreateAttestation } from './XChainAddAccountCreateAttestation'\nexport { XChainAddClaimAttestation } from './XChainAddClaimAttestation'\nexport { XChainClaim } from './XChainClaim'\nexport { XChainCommit } from './XChainCommit'\nexport { XChainCreateBridge } from './XChainCreateBridge'\nexport { XChainCreateClaimID } from './XChainCreateClaimID'\nexport { XChainAccountCreateCommit } from './XChainAccountCreateCommit'\nexport {\n XChainModifyBridge,\n XChainModifyBridgeFlags,\n XChainModifyBridgeFlagsInterface,\n} from './XChainModifyBridge'\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * Manage all the requests made to the websocket, and their async responses\n * that come in from the WebSocket. Because they come in over the WS connection\n * after-the-fact.\n */\nexport default class ConnectionManager {\n private promisesAwaitingConnection: Array<{\n resolve: (value?: void | PromiseLike<void>) => void\n reject: (value?: Error) => void\n }> = []\n\n /**\n * Resolves all awaiting connections.\n */\n public resolveAllAwaiting(): void {\n this.promisesAwaitingConnection.map(({ resolve }) => resolve())\n this.promisesAwaitingConnection = []\n }\n\n /**\n * Rejects all awaiting connections.\n *\n * @param error - Error to throw in the rejection.\n */\n public rejectAllAwaiting(error: Error): void {\n this.promisesAwaitingConnection.map(({ reject }) => reject(error))\n this.promisesAwaitingConnection = []\n }\n\n /**\n * Await a new connection.\n *\n * @returns A promise for resolving the connection.\n */\n public async awaitConnection(): Promise<void> {\n return new Promise((resolve, reject) => {\n this.promisesAwaitingConnection.push({ resolve, reject })\n })\n }\n}\n","import { ValidationError } from '../../errors'\nimport { isHex, INTEGER_SANITY_CHECK, isFlagEnabled } from '../utils'\n\nimport {\n BaseTransaction,\n GlobalFlagsInterface,\n validateBaseTransaction,\n validateOptionalField,\n isString,\n isNumber,\n} from './common'\nimport type { TransactionMetadataBase } from './metadata'\n\n// 2^63 - 1\nconst MAX_AMT = '9223372036854775807'\nconst MAX_TRANSFER_FEE = 50000\n\n/**\n * Transaction Flags for an MPTokenIssuanceCreate Transaction.\n *\n * @category Transaction Flags\n */\nexport enum MPTokenIssuanceCreateFlags {\n /**\n * If set, indicates that the MPT can be locked both individually and globally.\n * If not set, the MPT cannot be locked in any way.\n */\n tfMPTCanLock = 0x00000002,\n /**\n * If set, indicates that individual holders must be authorized.\n * This enables issuers to limit who can hold their assets.\n */\n tfMPTRequireAuth = 0x00000004,\n /**\n * If set, indicates that individual holders can place their balances into an escrow.\n */\n tfMPTCanEscrow = 0x00000008,\n /**\n * If set, indicates that individual holders can trade their balances\n * using the XRP Ledger DEX or AMM.\n */\n tfMPTCanTrade = 0x00000010,\n /**\n * If set, indicates that tokens may be transferred to other accounts\n * that are not the issuer.\n */\n tfMPTCanTransfer = 0x00000020,\n /**\n * If set, indicates that the issuer may use the Clawback transaction\n * to clawback value from individual holders.\n */\n tfMPTCanClawback = 0x00000040,\n}\n\n/**\n * Map of flags to boolean values representing {@link MPTokenIssuanceCreate} transaction\n * flags.\n *\n * @category Transaction Flags\n */\nexport interface MPTokenIssuanceCreateFlagsInterface\n extends GlobalFlagsInterface {\n tfMPTCanLock?: boolean\n tfMPTRequireAuth?: boolean\n tfMPTCanEscrow?: boolean\n tfMPTCanTrade?: boolean\n tfMPTCanTransfer?: boolean\n tfMPTCanClawback?: boolean\n}\n\n/**\n * The MPTokenIssuanceCreate transaction creates a MPTokenIssuance object\n * and adds it to the relevant directory node of the creator account.\n * This transaction is the only opportunity an issuer has to specify any token fields\n * that are defined as immutable (e.g., MPT Flags). If the transaction is successful,\n * the newly created token will be owned by the account (the creator account) which\n * executed the transaction.\n */\nexport interface MPTokenIssuanceCreate extends BaseTransaction {\n TransactionType: 'MPTokenIssuanceCreate'\n /**\n * An asset scale is the difference, in orders of magnitude, between a standard unit and\n * a corresponding fractional unit. More formally, the asset scale is a non-negative integer\n * (0, 1, 2, …) such that one standard unit equals 10^(-scale) of a corresponding\n * fractional unit. If the fractional unit equals the standard unit, then the asset scale is 0.\n * Note that this value is optional, and will default to 0 if not supplied.\n */\n AssetScale?: number\n /**\n * Specifies the maximum asset amount of this token that should ever be issued.\n * It is a non-negative integer string that can store a range of up to 63 bits. If not set, the max\n * amount will default to the largest unsigned 63-bit integer (0x7FFFFFFFFFFFFFFF or 9223372036854775807)\n *\n * Example:\n * ```\n * MaximumAmount: '9223372036854775807'\n * ```\n */\n MaximumAmount?: string\n /**\n * Specifies the fee to charged by the issuer for secondary sales of the Token,\n * if such sales are allowed. Valid values for this field are between 0 and 50,000 inclusive,\n * allowing transfer rates of between 0.000% and 50.000% in increments of 0.001.\n * The field must NOT be present if the `tfMPTCanTransfer` flag is not set.\n */\n TransferFee?: number\n /**\n * Arbitrary metadata about this issuance, in hex format.\n */\n MPTokenMetadata?: string | null\n Flags?: number | MPTokenIssuanceCreateFlagsInterface\n}\n\nexport interface MPTokenIssuanceCreateMetadata extends TransactionMetadataBase {\n mpt_issuance_id?: string\n}\n\n/* eslint-disable max-lines-per-function -- Not needed to reduce function */\n/**\n * Verify the form and type of an MPTokenIssuanceCreate at runtime.\n *\n * @param tx - An MPTokenIssuanceCreate Transaction.\n * @throws When the MPTokenIssuanceCreate is Malformed.\n */\nexport function validateMPTokenIssuanceCreate(\n tx: Record<string, unknown>,\n): void {\n validateBaseTransaction(tx)\n validateOptionalField(tx, 'MaximumAmount', isString)\n validateOptionalField(tx, 'MPTokenMetadata', isString)\n validateOptionalField(tx, 'TransferFee', isNumber)\n validateOptionalField(tx, 'AssetScale', isNumber)\n\n if (typeof tx.MPTokenMetadata === 'string' && tx.MPTokenMetadata === '') {\n throw new ValidationError(\n 'MPTokenIssuanceCreate: MPTokenMetadata must not be empty string',\n )\n }\n\n if (typeof tx.MPTokenMetadata === 'string' && !isHex(tx.MPTokenMetadata)) {\n throw new ValidationError(\n 'MPTokenIssuanceCreate: MPTokenMetadata must be in hex format',\n )\n }\n\n if (typeof tx.MaximumAmount === 'string') {\n if (!INTEGER_SANITY_CHECK.exec(tx.MaximumAmount)) {\n throw new ValidationError('MPTokenIssuanceCreate: Invalid MaximumAmount')\n } else if (\n BigInt(tx.MaximumAmount) > BigInt(MAX_AMT) ||\n BigInt(tx.MaximumAmount) < BigInt(`0`)\n ) {\n throw new ValidationError(\n 'MPTokenIssuanceCreate: MaximumAmount out of range',\n )\n }\n }\n\n if (typeof tx.TransferFee === 'number') {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Not necessary\n const flags = (tx.Flags ?? 0) as\n | number\n | MPTokenIssuanceCreateFlagsInterface\n const isTfMPTCanTransfer =\n typeof flags === 'number'\n ? isFlagEnabled(flags, MPTokenIssuanceCreateFlags.tfMPTCanTransfer)\n : flags.tfMPTCanTransfer ?? false\n\n if (tx.TransferFee < 0 || tx.TransferFee > MAX_TRANSFER_FEE) {\n throw new ValidationError(\n `MPTokenIssuanceCreate: TransferFee must be between 0 and ${MAX_TRANSFER_FEE}`,\n )\n }\n\n if (tx.TransferFee && !isTfMPTCanTransfer) {\n throw new ValidationError(\n 'MPTokenIssuanceCreate: TransferFee cannot be provided without enabling tfMPTCanTransfer flag',\n )\n }\n }\n}\n/* eslint-enable max-lines-per-function */\n","import { ValidationError } from '../../errors'\nimport { Amount } from '../common'\n\nimport { BaseTransaction, isAmount, validateBaseTransaction } from './common'\n\nexport const AMM_MAX_TRADING_FEE = 1000\n\n/**\n * Create a new Automated Market Maker (AMM) instance for trading a pair of assets (fungible tokens or XRP).\n *\n * Creates both an AMM object and a special AccountRoot object to represent the AMM.\n * Also transfers ownership of the starting balance of both assets from the sender to the created AccountRoot\n * and issues an initial balance of liquidity provider tokens (LP Tokens) from the AMM account to the sender.\n *\n * CAUTION: When you create the AMM, you should fund it with (approximately) equal-value amounts of each asset.\n * Otherwise, other users can profit at your expense by trading with this AMM (performing arbitrage).\n * The currency risk that liquidity providers take on increases with the volatility (potential for imbalance) of the asset pair.\n * The higher the trading fee, the more it offsets this risk,\n * so it's best to set the trading fee based on the volatility of the asset pair.\n */\nexport interface AMMCreate extends BaseTransaction {\n TransactionType: 'AMMCreate'\n\n /**\n * The first of the two assets to fund this AMM with. This must be a positive amount.\n */\n Amount: Amount\n\n /**\n * The second of the two assets to fund this AMM with. This must be a positive amount.\n */\n Amount2: Amount\n\n /**\n * The fee to charge for trades against this AMM instance, in units of 1/100,000; a value of 1 is equivalent to 0.001%.\n * The maximum value is 1000, indicating a 1% fee.\n * The minimum value is 0.\n */\n TradingFee: number\n}\n\n/**\n * Verify the form and type of an AMMCreate at runtime.\n *\n * @param tx - An AMMCreate Transaction.\n * @throws When the AMMCreate is Malformed.\n */\nexport function validateAMMCreate(tx: Record<string, unknown>): void {\n validateBaseTransaction(tx)\n\n if (tx.Amount == null) {\n throw new ValidationError('AMMCreate: missing field Amount')\n }\n\n if (!isAmount(tx.Amount)) {\n throw new ValidationError('AMMCreate: Amount must be an Amount')\n }\n\n if (tx.Amount2 == null) {\n throw new ValidationError('AMMCreate: missing field Amount2')\n }\n\n if (!isAmount(tx.Amount2)) {\n throw new ValidationError('AMMCreate: Amount2 must be an Amount')\n }\n\n if (tx.TradingFee == null) {\n throw new ValidationError('AMMCreate: missing field TradingFee')\n }\n\n if (typeof tx.TradingFee !== 'number') {\n throw new ValidationError('AMMCreate: TradingFee must be a number')\n }\n\n if (tx.TradingFee < 0 || tx.TradingFee > AMM_MAX_TRADING_FEE) {\n throw new ValidationError(\n `AMMCreate: TradingFee must be between 0 and ${AMM_MAX_TRADING_FEE}`,\n )\n }\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n// Cast array to view\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const byteSwapIfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): void {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * Convert byte array to hex string.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Convert JS string to byte array.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash function */\nexport type CHash = ReturnType<typeof wrapConstructor>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof wrapConstructorWithOpts>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof wrapXOFConstructorWithOpts>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function wrapConstructor<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(5642);\n"],"names":["tx","validateBaseTransaction","undefined","Channel","ValidationError","Amount","Expiration","Hash128","Hash","constructor","bytes","byteLength","ZERO_128","super","toHex","hex","bytesToHex","this","toBytes","exec","width","Uint8Array","HEX_REGEX","isFlagEnabled","Flags","checkFlag","BigInt","INTEGER_SANITY_CHECK","obj","fields","Object","keys","every","key","includes","flag","flagName","str","test","NodeType","DeliverMin","isAmount","CheckID","XrplError","Error","message","data","name","captureStackTrace","toString","result","JSON","stringify","inspect","RippledError","UnexpectedError","ConnectionError","NotConnectedError","DisconnectedError","RippledNotInitializedError","TimeoutError","ResponseFormatError","XRPLFaucetError","NotFoundError","channel","xrpAmount","privateKey","signingData","encodeForSigningClaim","amount","xrpToDrops","sign","validateRequiredField","isString","validateCredentialType","signature","publicKey","verify","UInt8","UInt","defaultUInt8","fromParser","parser","read","from","val","checkUintRange","buf","writeUInt8","valueOf","parseInt","isXChainBridge","isAccount","HEX_ZERO","InnerNode","Node","depth","leaves","type","INNER","empty","hash","iter","child","prefix","INNER_NODE","addItem","tag","node","existingNode","getNode","newInnerNode","setNode","slot","MPTokenIssuanceSetFlags","validateOptionalField","flags","isTfMPTLock","tfMPTLock","isTfMPTUnlock","tfMPTUnlock","filter","length","validateSingleAuthorizationFieldProvided","Authorize","Account","Unauthorize","AuthorizeCredentials","validateCredentialsList","TransactionType","MAX_AUTHORIZED_CREDENTIALS","UnauthorizeCredentials","toUpperCase","hexToBytes","len","array","i","j","hexByte","slice","byte","Number","isNaN","hexToString","encoding","TextDecoder","decode","stringToHex","string","TextEncoder","encode","randomBytes","addressToBigNumber","address","decodeAccountID","NUM_BITS_IN_HEX","left","right","comparedTo","txOrBlob","SHA512_Kh","SHA512_Kl","split","map","n","SHA512_W_H","Uint32Array","SHA512_W_L","SHA512","HashMD","Ah","Al","Bh","Bl","Ch","Cl","Dh","Dl","Eh","El","Fh","Fl","Gh","Gl","Hh","Hl","get","set","process","view","offset","getUint32","W15h","W15l","s0h","rotrSH","shrSH","s0l","rotrSL","shrSL","W2h","W2l","s1h","rotrBH","s1l","rotrBL","SUMl","add4L","SUMh","add4H","sigma1h","sigma1l","CHIh","CHIl","T1ll","add5L","T1h","add5H","T1l","sigma0h","sigma0l","MAJh","MAJl","h","l","add","All","add3L","add3H","roundClean","fill","destroy","buffer","SHA512_224","outputLen","SHA512_256","SHA384","sha512","wrapConstructor","sha512_224","sha512_256","sha384","BigNumber","isNumeric","mathceil","Math","ceil","mathfloor","floor","bignumberError","tooManyDigits","BASE","LOG_BASE","MAX_SAFE_INTEGER","POWS_TEN","SQRT_BASE","MAX","bitFloor","coeffToString","a","s","z","r","charCodeAt","compare","x","y","b","xc","c","yc","k","e","intCheck","min","max","String","isOdd","toExponential","charAt","toFixedPoint","zs","clone","configObject","div","convertBase","parseNumeric","pow2_53","random53bitInt","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","P","prototype","ONE","DECIMAL_PLACES","ROUNDING_MODE","TO_EXP_NEG","TO_EXP_POS","MIN_EXP","MAX_EXP","CRYPTO","MODULO_MODE","POW_PRECISION","FORMAT","groupSize","secondaryGroupSize","groupSeparator","decimalSeparator","fractionGroupSize","fractionGroupSeparator","suffix","ALPHABET","alphabetHasNormalDecimalDigits","v","alphabet","caseChanged","isNum","_isBigNumber","indexOf","replace","search","substring","round","DEBUG","toLowerCase","push","format","rm","id","c0","ne","maxOrMin","args","normalise","pop","sd","d","ni","rd","pows10","out","ROUND_UP","ROUND_DOWN","ROUND_CEIL","ROUND_FLOOR","ROUND_HALF_UP","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_CEIL","ROUND_HALF_FLOOR","EUCLID","config","p","hasOwnProperty","crypto","getRandomValues","EXPONENTIAL_AT","RANGE","isBigNumber","call","maximum","arguments","minimum","random","dp","rand","copy","splice","sum","plus","decimal","toBaseOut","baseIn","baseOut","arrL","arr","reverse","callerIsToString","pow","concat","multiply","base","m","temp","xlo","xhi","carry","klo","khi","aL","bL","cmp","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","NaN","p1","p2","absoluteValue","abs","decimalPlaces","dividedBy","dividedToIntegerBy","idiv","exponentiatedBy","half","isModExp","nIsBig","nIsNeg","nIsOdd","isInteger","mod","times","integerValue","isEqualTo","eq","isFinite","isGreaterThan","gt","isGreaterThanOrEqualTo","gte","isLessThan","lt","isLessThanOrEqualTo","lte","isNegative","isPositive","isZero","minus","t","xLTy","xe","ye","modulo","multipliedBy","xcL","ycL","ylo","yhi","zc","sqrtBase","negated","precision","shiftedBy","squareRoot","sqrt","rep","toFixed","toFormat","g1","g2","intPart","fractionPart","isNeg","intDigits","substr","RegExp","toFraction","md","d0","d1","d2","exp","n0","n1","toNumber","toPrecision","toJSON","power","res","_0n","field","opts","FIELD_FIELDS","reduce","ORDER","MASK","BYTES","BITS","validateObject","f","lhs","rhs","mul","invert","inv","legendre","FpLegendre","eql","ZERO","bitLen","isLE","redef","nBitLength","nByteLength","nLength","sqrtP","freeze","bitMask","_1n","create","num","isValid","is0","neg","sqr","sub","FpPow","sqrN","addN","subN","mulN","FpSqrt","invertBatch","lst","FpInvertBatch","cmov","numberToBytesLE","numberToBytesBE","fromBytes","bytesToNumberLE","bytesToNumberBE","Fp","elm","root","groupOrder","hashLen","ensureBytes","minLen","fieldOrder","fieldLen","getFieldBytesLength","getMinHashLength","reduced","_2n","_3n","_4n","_5n","_8n","number","u","tonelliShanks","legendreC","Q","S","Z","p1div4","Q1div2","g","t2","ge","c1","n2","nv","isNegativeLE","nums","tmp","Array","lastMultiplied","acc","inverted","reduceRight","order","legendreConst","_nBitLength","bitLength","isPartialPayment","metadata","meta","PaymentFlags","tfPartialPayment","delivered","delivered_amount","DeliverMax","amt1","amt2","isMPTAmount","aValue","value","bValue","mpt_issuance_id","currency","issuer","amountsEqual","command","response","tx_json","txHasPartialPayment","txEntryHasPartialPayment","transactions","some","transaction","accountTxHasPartialPayment","hasPartialPayment","warnings","warning","stream","log","isArray","AcceptedCredentials","Point","ProjectivePoint","base58check","createBase58check","sha256","bytesToNumber","abytes","MASTER_SECRET","utf8ToBytes","BITCOIN_VERSIONS","private","public","HARDENED_OFFSET","toU32","isSafeInteger","createView","setUint32","HDKey","fingerprint","pubHash","identifier","pubKeyHash","privKeyBytes","pubKey","privateExtendedKey","priv","serialize","versions","concatBytes","publicExtendedKey","fromMasterSeed","seed","I","hmac","chainCode","fromExtendedKey","base58key","keyBuffer","keyView","version","opt","parentFingerprint","index","isPriv","fromJSON","json","xpriv","utils","isValidPrivateKey","privKey","padStart","numberToBytes","getPublicKey","fromHex","toRawBytes","ripemd160","derive","path","parts","m1","idx","deriveChild","childTweak","added","CURVE","fromPrivateKey","equals","err","toCompactRawBytes","sig","Signature","fromCompact","error","wipePrivateData","xpub","BinaryParser","hexBytes","definitions","DEFAULT_DEFINITIONS","peek","skip","readUIntN","readUInt8","readUInt16","readUInt32","size","end","customEnd","readVariableLength","readVariableLengthLength","b1","readFieldOrdinal","nth","readField","fromString","readType","typeForField","associatedType","readFieldValue","sizeHint","isVariableLengthEncoded","readFieldAndValue","WSWrapper","EventEmitter","url","_protocols","_websocketOptions","ws","WebSocket","onclose","closeEvent","reason","emit","code","onopen","onerror","onmessage","readyState","close","send","CONNECTING","OPEN","CLOSING","CLOSED","AMMWithdrawFlags","Asset","isIssuedCurrency","Asset2","Amount2","EPrice","LPTokenIn","isIssuedCurrencyAmount","SHA1_IV","SHA1_W","SHA1","A","B","C","D","E","rotl","F","K","Chi","Maj","T","clean","sha1","createHasher","p32","_","sin","MD5_IV","MD5_W","MD5","md5","Rho160","Id160","Pi160","idxLR","idxL","idxR","shifts160","shiftsL160","shiftsR160","Kl160","Kr160","ripemd_f","group","BUF_160","RIPEMD160","h0","h1","h2","h3","h4","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","tr","destroyed","COEFF","xNum","xDen","yNum","yDen","mapToCurve","def","hashToCurve","msg","options","hash_to_field","DST","u0","fromAffine","u1","clearCofactor","assertValidity","encodeToCurve","encodeDST","scalars","os2ip","i2osp","anum","strxor","item","expand_message_xmd","lenInBytes","H","b_in_bytes","blockLen","r_in_bytes","ell","DST_prime","Z_pad","l_i_b_str","b_0","expand_message_xof","dkLen","update","digest","count","expand","_DST","log2p","L","len_in_bytes","prb","elm_offset","tv","subarray","XrplDefinitionsBase","Bytes","Type","LedgerEntryType","ledgerEntryType","transactionType","TransactionResult","transactionResult","Field","TRANSACTION_TYPES","transactionNames","defineProperty","exports","wordlist","SerializedType","hint","toBytesSink","list","put","BytesList","_definitions","_fieldName","Comparable","other","compareTo","RIPPLED_API_V1","RIPPLED_API_V2","DEFAULT_API_VERSION","globalThis","UInt16","defaultUInt16","writeUInt16BE","readUInt16BE","hashLedger","hashLedgerHeader","hashSignedTx","hashTxTree","hashStateTree","HEX","addressToHex","ledgerSpaceHex","txBlobHex","TRANSACTION_SIGN","sequence","hexPrefix","offer","hexSequence","address1","address2","address1Hex","address2Hex","swap","lowAddressHex","highAddressHex","currencyToHex","BYTE_LENGTH","dstAddress","isNumber","priceData","isRecord","priceDataInner","PriceData","BaseAsset","QuoteAsset","AssetPrice","Scale","isHex","isPathStep","pathStep","account","isPath","CredentialIDs","InvoiceID","Paths","paths","isPaths","SendMax","checkPartialPayment","fromBig","U32_MASK64","_32n","le","toBig","_l","rotr32H","_h","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","low","u64","txNeedsNetworkID","client","networkID","buildVersion","source","target","sourceDecomp","targetDecomp","sourceMajor","sourceMinor","targetMajor","targetMinor","sourcePatch","targetPatch","sourcePatchVersion","targetPatchVersion","startsWith","isNotLaterRippledVersion","validateAccountAddress","accountField","tagField","classicAccount","getClassicAccountAndTag","expectedTag","isValidXAddress","classic","xAddressToClassicAddress","classicAddress","convertToClassicAddress","fieldName","getNextValidSequenceNumber","request","ledger_index","account_data","Sequence","calculateFeePerTransactionType","signersCount","netFeeXRP","netFeeDrops","baseFee","isSpecialTxCost","FinishFunction","Fulfillment","fulfillmentBytesSize","ComputationAllowance","gasPrice","state","validated_ledger","gas_price","Promise","reject","fetchGasPrice","extraFee","rawTxFees","RawTransactions","rawTxn","resolvedAcc","fee","RawTransaction","resolve","reserve_inc","fetchOwnerReserveFee","maxFeeDrops","maxFeeXRP","Fee","ledgerSequence","getLedgerIndex","LastLedgerSequence","deletion_blockers_only","account_objects","accountSequences","txn","TicketSequence","nextSequence","SigningPubKey","TxnSignature","Signers","NetworkID","views","buf1","buf2","dv1","Int8Array","dv2","isBytes","ArrayBuffer","isView","lengths","isArrayOf","afn","input","astr","label","anumber","aArr","astrArr","anumArr","chain","wrap","letters","lettersA","indexes","Map","digits","letter","join","separator","to","padding","bits","chr","normalize","fn","convertRadix","pos","dlen","done","digit","fromCarry","digitBase","rounded","gcd","radix2carry","powers","convertRadix2","mask","radix","radix2","revPadding","unsafeWrapper","apply","checksum","payload","oldChecksum","newChecksum","base16","base32","base32nopad","base32hex","base32hexnopad","base32crockford","hasBase64Builtin","toBase64","fromBase64","decodeBase64Builtin","isUrl","re","lastChunkHandling","base64","base64nopad","base64url","base64urlnopad","genBase58","abc","base58","base58flickr","base58xrp","XMR_BLOCK_LEN","base58xmr","block","BECH_ALPHABET","POLYMOD_GENERATORS","bech32Polymod","pre","chk","bechChecksum","words","encodingConst","genBech32","ENCODING_CONST","_words","fromWords","toWords","fromWordsUnsafe","limit","plen","TypeError","actualLength","lowered","slen","sepIndex","lastIndexOf","endsWith","encodeFromBytes","decodeToBytes","decodeUnsafe","bech32","bech32m","utf8","hasHexBuiltin","hexBuiltin","CODERS","coderTypeError","bytesToString","stringToBytes","RegularKey","SettleDelay","PublicKey","CancelAfter","setBigUint64","byteOffset","_u32_max","wh","wl","padOffset","finished","aexists","take","dataView","digestInto","aoutput","oview","outLen","_cloneInto","SignerListFlags","Prefix","KEY_TYPES","NONE","SECP256K1_PRIVATE","ED25519","SECP256K1_PUB_X","SECP256K1_PUB_X_ODD_Y","SECP256K1_PUB_XY","prefixRepr","getAlgorithmFromKey","getKeyInfo","usedPrefix","algorithm","validFormats","colWidth","entries","padEnd","getValidFormatsTable","keyError","isXRPLNumber","Data","dataHex","dataByteLength","VAULT_DATA_MAX_BYTE_LENGTH","Issue","ZERO_ISSUED_CURRENCY","arg","sort","isXRP","isIOU","isMPT","isIssueObject","Currency","AccountID","mptIssuanceIdBytes","Hash192","mptBytes","currencyAndIssuer","inp","PaymentChannelClaimFlags","Balance","TradingFee","AMM_MAX_TRADING_FEE","SHA256_K","SHA256_IV","SHA256_W","SHA256","G","W15","W2","s0","rotr","s1","T1","T2","SHA224","sha224","RIPPLE_EPOCH_DIFF","rippleTimeToUnixTime","rpepoch","unixTimeToRippleTime","timestamp","rippleTimeToISOTime","rippleTime","Date","toISOString","isoTimeToRippleTime","iso8601","getTime","computeHash","itemizer","itemsJson","ShaMap","forEach","transactionItemizer","Hash256","hashPrefix","HashPrefix","sink","serializer","BinarySerializer","writeLengthEncoded","STObject","metaData","entryItemizer","serializeObject","accountStateEntry","transactionTreeHash","param","accountStateHash","ledgerHash","header","Sha512Half","ledgerHeader","parent_close_time","close_flags","UInt32","UInt64","total_coins","parent_hash","transaction_hash","account_hash","close_time","close_time_resolution","finish","decodeLedgerData","binary","secp256k1","deriveKeypair","entropy","derived","derivePrivateKey","ok","normedPrivateKey","lowS","extraEntropy","toDERHex","decoded","fromDER","secretNumbers","_account","familySeed","keypair","_secret","parseSecretString","entropyToSecret","randomSecret","validateLengths","getSecret","getSecretString","getAddress","getFamilySeed","getKeypair","secretToEntropy","generateSeed","deriveAddress","chash","wrapped","DROPS_PER_XRP","SANITY_CHECK","dropsToConvert","drops","xrpToConvert","xrp","components","isMemo","memo","Memo","validData","MemoData","validFormat","MemoFormat","validType","MemoType","onlyHasFields","isSigner","signer","Signer","isAuthorizeCredential","Credential","CredentialType","Issuer","isValidClassicAddress","checkValidity","errorOpts","paramNameStr","paramName","txType","GlobalFlags","containsDuplicates","objectList","Set","seen","has","trim","LockingChainDoor","LockingChainIssue","IssuingChainDoor","IssuingChainIssue","common","memos","Memos","signers","delegate","Delegate","parseFloat","MAX_CREDENTIAL_BYTE_LENGTH","credentials","isStringID","maxCredentials","credential","arr1","arr2","flatMap","HEX_WALLET_LOCATOR_REGEX","SignerQuorum","SignerEntries","entry","SignerEntry","signerEntry","WalletLocator","XChainBridge","ZERO_XCHAIN_BRIDGE","isXChainBridgeObject","TYPE_ORDER","object","ordinal","ordinalWidth","types","SyntaxError","normalizeNode","affectedNode","diffType","LedgerIndex","NewFields","FinalFields","PreviousFields","getValue","balance","computeBalanceChange","flipTrustlinePerspective","balanceChange","negatedBalance","balanceChanges","grouped","groupBy","items","balances","groupByAccount","AffectedNodes","normalizeNodes","xrpQuantity","dropsToXrp","getXRPQuantity","trustlineQuantity","LowLimit","HighLimit","getTrustlineQuantity","flat","TicketCount","MPTokenAuthorizeFlags","assertHelper","cond","getOrderbookOptionsSet","ledger_hash","taker","currency1","currency2","taker_pays","taker_gets","requestAll","offers","offerResults","offerResult","directOffers","reverseOffers","orders","buy","sell","OfferFlags","lsfSell","offerA","offerB","qualityA","quality","qualityB","sortOffers","FinishAfter","Condition","ONE_BILLION","percentToDecimal","percent","decimalToTransferRate","rate","billionths","decimalToQuality","title","hexToNumber","numberToHexUnpadded","expectedLength","diff","inRange","qByteLen","hmacFn","u8n","reset","reseed","u8fr","gen","pred","validators","optValidators","checkField","isOptional","checkVal","validatorFns","WeakMap","computed","hexes","asciis","_0","_9","asciiToBase16","ch","hl","ai","hi","char","arrays","pad","isPosBig","bigint","function","boolean","stringOrUint8Array","notImplemented","OfferSequence","dirNode","generatorMap","rippleState","ownerDir","bookDir","contract","skipList","escrow","amendment","feeSettings","ticket","signerList","paychan","check","depositPreauth","Vector256","bytesList","hashes","field_info","typeOrdinal","info","fieldHeader","isVLEncoded","isSerialized","isSigningField","TYPE_WIDTH","buildField","AMMClawbackFlags","asset","Holder","AccountSetAsfFlags","AccountSetTfFlags","ClearFlag","values","Domain","EmailHash","MessageKey","SetFlag","TransferRate","TickSize","nibblet","byteIx","HMAC","_key","ahash","iHash","oHash","getPrototypeOf","multisign","decodedTransactions","getDecodedTransaction","validate","exampleTransaction","validateTransactionEquivalence","sortedSigners","signer1","signer2","compareSigners","getTransactionWithAllSigners","verifySignature","decodedTx","encodeForSigning","Hop","hopParser","Path","hop","pathParser","PathSet","isHopObject","constTimeNegate","hasPrecomputes","getW","unsafeLadder","double","precomputeWindow","W","windows","windowSize","calcWOpts","points","window","wNAF","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFUnsafe","curr","negate","getPrecomputes","transform","comp","pointPrecomputes","wNAFCached","wNAFCachedUnsafe","prev","setWindowSize","validateW","pointWindowSizes","delete","fieldN","validateMSMPoints","validateMSMScalars","zero","buckets","scalar","resI","sumI","tableSize","chunks","tables","curve","validateField","Gx","Gy","condition","INTENTIONAL_DISCONNECT_CODE","Connection","reconnectTimeoutID","heartbeatIntervalID","retryConnectionBackoff","SECONDS_PER_MINUTE","requestManager","connectionManager","trace","timeout","TIMEOUT","connectionTimeout","CONNECTION_TIMEOUT","console","shouldBeConnected","isConnected","connect","awaitConnection","connectionTimeoutID","setTimeout","onConnectionFailed","agent","headers","authorization","Authorization","btoa","websocketOptions","createWebSocket","on","clearTimeout","once","onceOpen","disconnect","clearHeartbeatInterval","reconnect","responsePromise","createRequest","websocketSendAsync","catch","getUrl","onMessage","parse","error_message","handleResponse","removeAllListeners","rejectAll","internalErrorCode","intentionalDisconnect","startHeartbeatInterval","resolveAllAwaiting","rejectAllAwaiting","retryTimeout","duration","attempts","clearInterval","setInterval","heartbeat","errorOrCode","ledgerHashes","decodedMeta","ensureDecodedMeta","find","isCreatedNode","CreatedNode","XChainClaimID","defaultUInt32","writeUInt32BE","readUInt32BE","FaucetNetwork","faucetNetworkPaths","Testnet","Devnet","WasmDevnet","faucetNetworkIDs","hostname","password","salt","DK","PRF","PRFSalt","pbkdf2Init","prfW","ti","Ti","setInt32","ui","pbkdf2Output","async","asyncTick","asyncLoop","_password","_salt","_opts","checkOpts","kdfInputToBytes","DataView","word","shift","byteSwap","iters","tick","cb","ts","now","nextTick","defaults","assign","hashCons","hashC","bytesLength","byteSwapIfBE","rfc1751WordList","BINARY","keyToBinary","extract","start","subKey","getSubKey","sublist","cc","swap128","reversedBytes","swap64","keyToRFC1751Mnemonic","hex_key","english","skbin","parity","rfc1751MnemonicToKey","SHA224_IV","K512","SHA512_IV","SHA384_IV","T224_IV","T256_IV","BidMin","BidMax","AuthAccounts","senderAddress","authAccounts","authAccount","AuthAccount","validateAuthAccounts","curveDef","validateBasic","ut","bits2int","bits2int_modN","validateOpts","CURVE_ORDER","compressedLen","uncompressedLen","modN","invN","normPrivateKeyToScalar","weierstrassEquation","isWithinCurveOrder","weierstrassPoints","_c","point","isCompressed","toAffine","cat","abool","hasEvenY","head","tail","y2","sqrtError","numToNByteStr","isBiggerThanHalfOrder","slcNum","recovery","DER","toSig","aInRange","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","R","ir","u2","multiplyAndAddUnsafe","hasHighS","normalizeS","toDERRawBytes","hexFromSig","toCompactHex","randomPrivateKey","mapHashToField","precompute","_setWindowSize","isProbPub","delta","ORDER_MASK","int2octets","defaultSigOpts","prehash","defaultVerOpts","getSharedSecret","privateA","publicB","k2sig","ent","validateSigVerOpts","h1int","seedArgs","kBytes","ik","normS","prepSig","createHmacDrbg","drbg","sg","isObj","_sig","derError","Err","is","sqrtRatio","SWUFpSqrtRatio","tv1","tv2","tv3","tv4","tv5","tv6","e1","b2n","h2b","DERErr","_tlv","dataLen","lenLen","first","lengthBytes","_int","int","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","seq","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","Fn","_isCompressed","x2","x3","N","assertPrjPoint","toAffineMemo","memoized","iz","px","py","pz","ax","ay","zz","assertValidMemo","normalizeZ","toInv","msm","pippenger","wnaf","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t3","t4","t5","multiplyUnsafe","sc","k1neg","k1","k2neg","k2","k1p","k2p","fake","f1p","f2p","cofactor","_bits","o","_2n_pow_c1_1","_2n_pow_c1","c2","c3","c4","c5","c6","c7","isQR","tvv5","y1","isSigned","signedTransaction","failHard","tx_blob","fail_hard","waitForFinalTransactionOutcome","txHash","lastLedger","submissionResult","sleep","latestLedger","txResponse","validated","autofill","wallet","XChainModifyBridgeFlags","NON_DELEGATABLE_TRANSACTIONS","permissions","Permissions","permissionValueSet","permission","Permission","permissionValue","PermissionValue","XrplDefinitions","enums","additionalTypes","coreTypes","Sha512","first256","addU32","first256BigInt","clamp","Client","server","apiVersion","feeCushion","connection","errorCode","errorMessage","finalCode","ledger","handleStreamPartialPayment","validation","manifest","status","consensus","req","ensureClassicAddress","api_version","handlePartialPayment","requestNextPage","resp","marker","nextPageRequest","eventName","listener","collect","collectKey","getCollectKeyFromCommand","countTo","Infinity","results","countRemaining","repeatProps","singleResponse","singleResult","collectedData","Boolean","getServerInfo","network_id","build_version","then","setValidAddresses","convertTxFlagsToNumber","promises","setNextValidSequenceNumber","getTransactionFee","setLatestValidatedLedgerSequence","checkAccountDeleteBlockers","autofillBatchTxn","handleDeliverMax","all","simulate","submit","signedTx","getSignedTx","submitRequest","submitAndWait","getLastLedgerSequence","engine_result","engine_result_message","prepareTransaction","getXrpBalance","xrpRequest","getBalances","xrpPromise","peer","linesRequest","linesPromise","xrpBalance","linesResponses","accountLinesBalance","formatBalances","lines","getOrderbook","validateOrderbookOptions","createBookOffersRequest","directOfferResults","requestAllOffers","reverseOfferResults","reverseRequest","extractOffers","combineOrders","separateBuySellOrders","sortAndLimitOffers","fundWallet","existingWallet","walletToFund","Wallet","generate","postBody","destination","usageContext","userAgent","startingBalance","requestFunding","DEFAULT_ALGORITHM","ed25519","masterAddress","fromSeed","deriveWallet","fromEntropy","fromMnemonic","mnemonic","mnemonicEncoding","fromRFC1751Mnemonic","validateMnemonic","mnemonicToSeedSync","derivationPath","validateKey","encodeAlgorithm","encodedSeed","encodeSeed","multisignAddress","omitBy","removeTrailingZeros","hasFlag","tfInnerBatchTxn","txToSignAndEncode","computeSignature","serialized","verifyTransaction","getXAddress","isTestnet","classicAddressToXAddress","signAs","encodeForMultisigning","fromSecret","unscrambleTaxon","taxon","tokenSeq","nftokenID","scrambledTaxon","NFTokenID","TransferFee","encodeAccountID","Taxon","NEGATIVE_UNL_ID","factor","numAttempts","ms","decodeSeed","getSigningScheme","deriveAddressFromBytes","publicKeyBytes","computePublicKeyHash","scheme","messageToVerify","messageHex","getAlgorithmFromPrivateKey","getAlgorithmFromPublicKey","deriveNodeAddress","generatorBytes","decodeNodePublic","accountPublicFromPublicGenerator","BASE10_REGEX","useBase10","defaultUInt64","intBuf","strBuf","hexString","msb","lsb","instance","checkFinished","byteSwap32","swap8IfBE","swap32IfBE","createOptHasher","createXOFer","wrapConstructorWithOpts","wrapXOFConstructorWithOpts","ED25519_SEED","codecOptions","codecWithXrpAlphabet","_sha256","_codec","_encodeVersioned","base58string","versionTypes","withoutSum","decodeChecked","versionLengthGuess","payloadLength","versionBytes","arrayEqual","encodeChecked","_encodeRaw","concatArgs","intArray","_decodeRaw","_verifyCheckSum","checkByteLength","accountId","codec","encodeAddress","decodeAddress","_error","aligned16","aligned32","setBigInt64","getUint16","getInt32","getBigInt64","aUInt","bUInt","compare32","Uint16Array","compare16","compare8","VaultWithdrawalPolicy","VaultCreateFlags","isCurrency","MPTokenMetadata","metaHex","metaByteLength","DomainID","tfVaultPrivate","signingClaimData","multiSigningData","signingBatchData","binaryToJSON","transactionSig","definitionsOpt","encodeForSigningBatch","encodeQuality","decodeQuality","default","walletFromSecretNumbers","LeafNode","ACCOUNT_STATE","leafPrefix","LEAF_NODE","TRANSACTION_NO_METADATA","txIDPrefix","TRANSACTION_ID","TRANSACTION_METADATA","txNodePrefix","TRANSACTION_NODE","decodeAccountPublic","decodeXAddress","encodeAccountPublic","encodeNodePublic","encodeXAddress","deriveXAddress","getBalanceChanges","getNFTokenID","getXChainClaimID","parseNFTokenID","percentToTransferRate","transferRateToDecimal","percentToQuality","qualityToDecimal","signPaymentChannelClaim","convertHexToString","convertStringToHex","verifyPaymentChannelClaim","isValidSecret","secret","_err","encodeForMultiSigning","isValidAddress","hasNextPage","hashTx","hashAccountRoot","hashSignerListId","hashOfferId","hashTrustline","hashEscrow","hashPaymentChannel","Blob","Hash160","defaultAccountID","fromBase58","toBase58","adjustScalarBytes","domain","uvRatio","cHash","modP","ctx","phflag","aCoordinate","assertPoint","ex","ey","ez","X","Y","et","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","T3","isSmallOrder","zip215","normed","lastByte","isXOdd","isLastByteOdd","getExtendedPublicKey","modN_LE","hashed","pointBytes","hashDomainToScalar","context","msgs","verifyOpts","VERIFY_DEFAULT","SB","ExtendedPoint","NFTokenCreateOfferFlags","Owner","Destination","tfSellNFToken","validateNFTokenSellOfferCases","parseAmountValue","validateNFTokenBuyOfferCases","txCurrency","validateAMMBid","validateAMMClawback","validateAMMCreate","validateAMMDelete","validateAMMDeposit","validateAMMVote","validateAMMWithdraw","validateAccountDelete","validateAccountSet","validateBatch","innerTx","validateCheckCancel","validateCheckCash","validateCheckCreate","validateClawback","validateCredentialAccept","validateCredentialCreate","validateCredentialDelete","validateDIDDelete","validateDIDSet","validateDelegateSet","validateDepositPreauth","validateEscrowCancel","validateEscrowCreate","validateEscrowFinish","validateMPTokenAuthorize","validateMPTokenIssuanceCreate","validateMPTokenIssuanceDestroy","validateMPTokenIssuanceSet","validateNFTokenAcceptOffer","validateNFTokenBurn","validateNFTokenCancelOffer","validateNFTokenCreateOffer","validateNFTokenMint","validateNFTokenModify","validateOfferCancel","validateOfferCreate","validateOracleDelete","validateOracleSet","validatePayment","validatePaymentChannelClaim","validatePaymentChannelCreate","validatePaymentChannelFund","validatePermissionedDomainSet","validatePermissionedDomainDelete","validateSetRegularKey","validateSignerListSet","validateTicketCreate","validateTrustSet","validateVaultClawback","validateVaultCreate","validateVaultDelete","validateVaultDeposit","validateVaultSet","validateVaultWithdraw","validateXChainAccountCreateCommit","validateXChainAddAccountCreateAttestation","validateXChainAddClaimAttestation","validateXChainClaim","validateXChainCommit","validateXChainCreateBridge","validateXChainCreateClaimID","validateXChainModifyBridge","isClawbackAmount","updatedOpts","XRP_HEX_REGEX","ISO_REGEX","STANDARD_FORMAT_HEX_REGEX","bytesFromRepresentation","isStringRepresentation","isValidRepresentation","iso","isoBytes","isoToBytes","byteBuf","XRP","_iso","isIsoCode","isoCodeFromHex","ECDSA","NFTokenBrokerFee","NFTokenSellOffer","NFTokenBuyOffer","validateNFTokenBrokerFee","TrustSetFlags","LimitAmount","QualityIn","QualityOut","AMMDepositFlags","LPTokenOut","intToHex","integer","addLengthPrefix","txBlob","txObject","LEDGER","integerString","shamap","txJSON","ledgerEntry","computeTransactionHash","computeTreeHashes","transactionHash","transactionHashInHeader","computedHashOfTransactions","computeStateHash","accountState","stateHash","subhashes","PREFIX_BYTES","main","theTag","xAddress","decodedPrefix","equal","isUint8ArrayForTestAddress","tagFromUint8Array","trustlines","trustline","cushion","serverInfo","base_fee_xrp","baseFeeXrp","load_factor","defHash","weierstrass","getHash","affectedNodes","isModifiedNode","ModifiedNode","NFTokens","previousTokenIDSet","token","NFToken","BatchFlags","rawTxObj","rawTx","BatchSigners","signerObj","signerRecord","BatchSigner","Subject","ZERO_192","STArray","STNumber","associateTypes","FEE_SETTINGS_ID","faucetHost","getFaucetHost","pathname","faucetPath","getFaucetPath","fetch","method","body","updatedBalance","originalBalance","interval","newBalance","INTERVAL_SECONDS","getUpdatedBalance","processSuccessfulResponse","contentType","statusCode","processError","ZERO_160","uint32","transactionID","innerNode","transactionMultiSig","proposal","paymentChannelClaim","batch","finish256","sha512Half","EnableAmendmentFlags","URI","NFTokenOffers","validateURI","montgomeryBits","powPminus2","Gu","montgomeryBytes","cswap","x_2","x_3","dummy","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","decodeScalar","GuBytes","scalarMultBase","AMENDMENTS_ID","bytesArray","getLength","bytesArg","write","writeType","writeBytesList","encodeVariableLength","lenBytes","writeFieldAndValue","isUnlModifyWorkaround","associatedValue","randomEntropy","calculateChecksum","position","checkChecksum","normalizedChecksum","normalizedValue","_a","chunk","buffChunk","no","repeat","normalizedSecret","LEDGER_ENTRY_WIDTH","TRANSACTION_TYPE_WIDTH","TRANSACTION_RESULT_WIDTH","DELEGATABLE_PERMISSIONS_WIDTH","exponent","qualityString","ARRAY_END_MARKER","ARRAY_END_MARKER_NAME","OBJECT_END_MARKER","arrayParser","outer","ZERO_256","DIDDocument","ShaMapNode","ShaMapLeaf","isLeaf","isInner","ShaMapInner","slotBits","branches","setBranch","branch","leaf","nibble","existing","newInner","AccountRootFlags","edwardsPriv","ed25519Defaults","ED25519_P","ED25519_SQRT_M1","ed25519_pow_2_252_3","_10n","_20n","_40n","_80n","b2","b4","pow2","b5","b10","b20","b40","b80","b160","b240","b250","pow_p_5_8","v3","vx2","root1","root2","useRoot1","useRoot2","noRoot","ED25519_TORSION_SUBGROUP","ed25519_domain","edwardsToMontgomeryPub","edwardsPub","twistedEdwards","ed25519ctx","ed25519ph","x25519","montgomery","edwardsToMontgomery","ELL2_C1","ELL2_C2","ELL2_C3","ELL2_C1_EDWARDS","FpSqrtEven","htf","xMn","xMd","yMn","yMd","ELL2_C4","ELL2_J","xd","x1n","gxd","gx1","y11","y12","x2n","y21","y22","gx2","e2","e3","xn","e4","map_to_curve_elligator2_curve25519","yn","yd","map_to_curve_elligator2_edwards25519","assertRstPoint","RistPoint","SQRT_M1","SQRT_AD_MINUS_ONE","INVSQRT_A_MINUS_D","ONE_MINUS_D_SQ","D_MINUS_ONE_SQ","invertSqrt","MAX_255B","bytes255ToNumberLE","calcElligatorRistrettoMap","r0","Ns","Ns_D_is_sq","s_","Nt","s2","W0","W1","W3","ep","ap","R1","R2","emsg","equalBytes","u1_2","u2_2","Dx","Dy","u2sq","invsqrt","D1","D2","zInv","_x","_y","one","two","RistrettoPoint","hashToRistretto255","uniform_bytes","hash_to_ristretto255","Rho","Id","shifts","shiftsL","shiftsR","Kl","Kr","R_BUF","NFTokenMintFlags","NFTokenTaxon","MIN_MANTISSA","MAX_MANTISSA","DEFAULT_VALUE_EXPONENT","used","defaultBytes","fromValue","mantissa","match","fracPart","expPart","mantissaStr","extractNumberPartsFromString","normalizedMantissa","normalizedExponent","writeInt64BE","writeInt32BE","readInt64BE","readInt32BE","rawValue","OFFSET","integerPart","BytesLookup","FieldLookup","TYPES","LEDGER_ENTRY_TYPES","TRANSACTION_RESULTS","FIELDS","_value","dataTypes","granularPermissions","TrustlineAuthorize","TrustlineFreeze","TrustlineUnfreeze","AccountDomainSet","AccountEmailHashSet","AccountMessageKeySet","AccountTransferRateSet","AccountTickSizeSet","PaymentMint","PaymentBurn","MPTokenIssuanceLock","MPTokenIssuanceUnlock","incrementedTransactionTypes","fromEntries","combinedPermissions","delegatablePermissions","getAssociatedTypes","RippleStateFlags","OBJECT_END_MARKER_BYTE","ST_OBJECT","SOURCE_TAG","DEST_TAG","isUnlModify","xAddressDecoded","handled","tagName","handleXAddress","obj1","obj2","checkForDuplicateTags","sorted","objectParser","accumulator","deriveScalar","discrim","hasher","validator","privateGen","accountIndex","publicGenBytes","rootPubPoint","secp256k1P","secp256k1N","divNearest","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","Fpk1","createCurve","a1","a2","POW_2_128","TAGGED_HASH_PREFIXES","taggedHash","messages","tagP","tagH","pointToBytes","numTo32b","schnorrGetExtPubKey","d_","lift_x","xx","challenge","schnorrVerify","pub","schnorr","auxRand","k_","rx","isoMap","isogenyMap","mapSWU","mapToCurveSimpleSWU","iteratee","arrayReference","predicate","kb","OfferCreateFlags","TakerGets","TakerPays","MAX_DROPS","MIN_XRP","mptMask","MIN_IOU_EXPONENT","MAX_IOU_EXPONENT","defaultAmount","assertXrpIsValid","isAmountObjectIOU","assertIouIsValid","integerNumberString","exponentByte","isAmountObjectMPT","assertMptIsValid","leadingByte","mptIssuanceID","numBytes","isNative","mptID","verifyNoDecimal","makeParser","readJSON","signingFieldsOnly","claim","signingAccount","txIDs","txIDsLength","txID","nextId","promisesAwaitingResponse","addPromise","newId","timer","promise","deletePromise","_promise","_map","newRequest","unref","newPromise","errorResponse","error_exception","rawPrivateKey","flagsInterface","txToFlag","AccountSet","AMMClawback","AMMDeposit","AMMWithdraw","Batch","MPTokenAuthorize","MPTokenIssuanceCreate","MPTokenIssuanceCreateFlags","MPTokenIssuanceSet","NFTokenCreateOffer","NFTokenMint","OfferCreate","PaymentChannelClaim","Payment","TrustSet","VaultCreate","XChainModifyBridge","isTxToFlagKey","txFlags","flagEnum","resultFlags","warn","booleanFlagMap","transactionTypeFlags","parseAccountRootFlags","setTransactionFlagsToNumber","parseTransactionFlags","generateMnemonic","strength","utils_1","entropyToMnemonic","mnemonicToEntropy","mnemonicToSeed","passphrase","pbkdf2_1","pbkdf2Async","sha2_1","nfkd","psalt","pbkdf2","base_1","isJapanese","norm","aentropy","calcChecksum","bitsLeft","getCoder","Events","EE","addListener","emitter","event","evt","_events","_eventsCount","clearEvent","__proto__","eventNames","events","names","getOwnPropertySymbols","listeners","handlers","ee","listenerCount","a3","a4","a5","removeListener","off","prefixed","module","promisesAwaitingConnection","MaximumAmount","isTfMPTCanTransfer","tfMPTCanTransfer","__webpack_module_cache__","__webpack_exports__","__webpack_require__","moduleId","cachedModule","__webpack_modules__"],"sourceRoot":""}