Compare commits

...

14 Commits

Author SHA1 Message Date
Denis Angell
ecfa0ea3f8 Publish
- @transia/ripple-address-codec@4.2.6-tbeta.0
 - @transia/ripple-binary-codec@1.4.4-tbeta.0
 - @transia/ripple-keypairs@1.1.6-tbeta.0
 - @transia/xrpl@2.7.1-tbeta.0
2023-03-28 18:52:39 +00:00
Denis Angell
cbbeebffa9 update versions 2023-03-28 18:51:51 +00:00
Denis Angell
05f75b7316 update package names 2023-03-28 18:50:43 +00:00
Denis Angell
c04d1c8708 Hooks (#2)
* feature `Hooks`

update definitions

add network id to base transaction

add set hook

update required

update definitions

make network id required

* update hook

update hook

add test and validation

add estimate fee func

fix estimated fee error

add hook utils

* update hookon transaction types

* add invoke tx

* ledger entry objects

* remove sugar export

* update definitions

* remove network id

* export transaction type map from definitions

* lint

* fix error

* fixup unit test

* update hook on calcaulator

* add uritoken (req for hook on calc)

* add network id (req for sethook)

* update tests
2023-03-28 18:45:17 +00:00
Denis Angell
ac2f4bac8b URIToken (#3)
* update definitions

* add transactions

* rename Transactors

revert transactors
2023-03-28 18:35:45 +00:00
Denis Angell
61942003f6 Amm (#6)
* update definitions.json

* add AMMInstanceCreate

* renamed LPTokens to LPToken in definitions.json

* update HISTORY.md

* add amm_info RPC command

* add AMMDeposit

* use null check for missing fields

* add AMMWithdraw

* add AMMVote

* fix lint error

* add max trading fee check to AMMVote

* refactor MAX_TRADING_FEE to be in one place

* add AMMBid

* add AuthAccount interface to AMMBid

* refactor tests

* add AMMID to AMMInfoResponse

* update amm_info docstrings

* fix EPrice type to be Amount

* update EPrice validation error message and add missing tests

* update definitions to fix AMM in LEDGER_ENTRY_TYPES

* add missing test case Asset1In and Asset2In valid

* add missing test case Asset1Out and Asset2Out valid

* add negative FeeVal check

* update HISTORY.md to specify XLS-30

* update wording on AMMDeposit & AMMWithdraw validation errors

* add negative TradingFee check

* fix ammInfo response

* add AMMID as optional param in ammInfo response

* fix EPrice validation checks in AMMDeposit & AMMWithdraw

* add VoteSlots as optional param in AMMInfoResponse

* update VoteEntry interface

* fix deposit and withdraw tests

* fix AMMBid ValidationError

* update definitions.json with different AuthAccounts number

* Change amm_info asset parameters to Currency type

* API name changes with updated definitions.json

* rename amm_info param asset1 -> asset

* fix typo

* change AMM_MAX_TRADING_FEE to 1%

* Use Asset/Asset2 instead of AMMID for Deposit/Withdraw/Bid/Vote

* add Deposit/Withdraw flags

* rename FeeVal -> TradingFee in VoteEntry

* rename MinBidPrice -> BidMin and MaxBidPrice -> BidMax

* update definitions to change Asset & Asset2 nth values to 3 & 4

* update definitions

* add Issue type and tests for Asset/Asset2

* remove AMMID from amm_info and use Issue type

* update amm_info fields

* fix lint errors

* update unit tests

* add AMM codec-fixtures

* update Issue type

* add one asset and withdraw all tests

* refactor amm_info response fields to match AMMDevnet

* update definitions.json with refactored error codes

* update ammInfo.ts response model

* remove invalid fields from ammInfo.ts response model

* update time_interval description

* rename test model names and fix lint errors

* add Owner Reserve Fee for AMMCreate transaction

* add missing asset_frozen field

* replace Issue with IssuedCurrency

* refactor: convert flags to number

* update asset pair to use Currency type

* refactor isIssue to isCurrency

---------

Co-authored-by: Omar Khan <khancodegt@gmail.com>
2023-03-28 18:34:34 +00:00
Denis Angell
6f077f8e51 Network ID (#4)
* update definitions

* add network id to base transaction

* update server info

* update base tx

* add network id to autofill

* update tests and fixtures

* network id option 3

fixup

add network id to server info fixture

fixup!

Revert "update tests and fixtures"

This reverts commit a5deee1274.

* update autofill

* update getNetworkID

* remove set network func

* fixup!

remove autoset network id

remove my mistake

fixup!
2023-03-28 18:26:25 +00:00
Caleb Kniffen
62a39c69ce chore: bump codeql-analysis (#2246) 2023-03-27 18:32:54 -04:00
dependabot[bot]
dfd2fc1ba1 build(deps-dev): bump webpack from 5.75.0 to 5.76.0 (#2241)
Bumps [webpack](https://github.com/webpack/webpack) from 5.75.0 to 5.76.0.
- [Release notes](https://github.com/webpack/webpack/releases)
- [Commits](https://github.com/webpack/webpack/compare/v5.75.0...v5.76.0)

---
updated-dependencies:
- dependency-name: webpack
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-24 16:42:34 -04:00
dependabot[bot]
41563d1529 build(deps-dev): bump expect from 29.4.2 to 29.4.3 (#2230) 2023-03-23 14:13:53 +00:00
Elliot Lee
d57233fc49 CONTRIBUTING: update release checklist (#2238)
---------

Co-authored-by: Jackson Mills <jmills@ripple.com>
2023-03-22 17:07:19 -07:00
tequ
bbbdf06e91 add destination_account field to PathOption(path_find method) (#2160)
* add destination_account field to PathOption(path_find method)

* fix field name

* Fix grammar in comment

* Fix sentence with missing end

* Add HISTORY.md

---------

Co-authored-by: Jackson Mills <jmills@ripple.com>
2023-03-22 17:42:46 -04:00
Jackson Mills
0c6ea2afe2 feat: modifiable definitions.json values at runtime via encode/decode parameter (#2127) 2023-03-16 10:35:50 -07:00
Alexey Novikov
97ff2aa104 Issue 2212. Improve NFToken.URI handling for empty and undefined values (#2218)
* Handle undefined and null values in transactions better.
2023-03-09 13:34:28 -08:00
79 changed files with 4623 additions and 464 deletions

View File

@@ -39,7 +39,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -50,7 +50,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -64,4 +64,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v2

View File

@@ -169,48 +169,86 @@ npm install abbrev -w ripple-keypairs
npm uninstall abbrev -w xrpl
```
## Release process
## Release process + checklist
### Release
## PR process
1. Ensure that all tests passed on the last CI that ran on `main`.
- [ ] Your changes should be on a branch.
- [ ] Your changes should have unit tests.
- [ ] Lint the code with `npm lint`
- [ ] Build your code with `npm build`
- [ ] Run the unit tests with `npm test`
- [ ] Get a full code review.
- [ ] Merge your branch into `main` and push to github.
- [ ] Ensure that all tests passed on the last CI that ran on `main`.
NOW WE ARE READY TO PUBLISH! No new code changes happen manually now.
## Release
2. Checkout `main` (or your beta branch) and `git pull`.
3. Create a new branch (`git checkout -b <BRANCH_NAME>`) to capture updates that take place during this process.
4. Update `HISTORY.md` to reflect release changes.
5. Run `npm run docgen` if the docs were modified in this release to update them (skip this step for a beta).
6. Run `npm run build` to triple check the build still works
7. Run `npx lerna version --no-git-tag-version` - This creates a draft PR and bumps the versions of the packages.
* For each changed package, pick what the new version should be. Lerna will bump the versions, commit version bumps to `main`, and create a new git tag for each published package.
* If publishing a beta, make sure that the versions are all of the form `a.b.c-beta.d`, where `a`, `b`, and `c` are identical to the last normal release except for one, which has been incremented by 1.
8. Run `npm i` to update the package-lock with the updated versions
9. Create a new PR from this branch into `main` and merge it (you can directly merge into the beta branch for a beta).
10. Checkout `main` and `git pull` (you can skip this step for a beta since you already have the latest version of the beta branch).
11. Run `npx lerna publish from-package --yes` - This will actually publish the packages.
* NOTE: if you're releasing a beta, run `npx lerna publish from-package --dist-tag beta --yes` instead.
* If it asks for it, enter your [npmjs.com](https://npmjs.com) OTP (one-time password) to complete publication.
12. Create a new branch (`git checkout -b <BRANCH_NAME>`)to capture the updated packages from the release. Merge those changes into `main`. (You can skip this step on a beta release).
1. Checkout `main` (or your beta branch) and `git pull`.
1. Create a new branch (`git checkout -b <BRANCH_NAME>`) to capture updates that take place during this process.
1. Update `HISTORY.md` to reflect release changes.
NOW YOU HAVE PUBLISHED! But you're not done; we have to notify people!
- [ ] Update the version number and release date, and ensure it lists the changes since the previous release.
13. Pull the most recent changes to main locally.
14. Run `git tag <tagname> -m <tagname>`, where `<tagname>` is the new package and version (e.g. `xrpl@2.1.1`), for each version released.
15. Run `git push --follow-tags`, to push the tags to Github.
16. On Github, click the "releases" link on the right-hand side of the page.
17. Click "Draft a new release"
18. Click "Choose a tag", and choose a tag that you just created.
19. Edit the name of the release to match the tag (IE \<package\>@\<version\>) and edit the description as you see fit.
20. Repeat steps 17-19 for each release.
21. Send an email to [xrpl-announce](https://groups.google.com/g/xrpl-announce).
1. Run `npm run docgen` if the docs were modified in this release to update them (skip this step for a beta).
1. Run `npm run build` to triple check the build still works
1. Run `npx lerna version --no-git-tag-version` - This creates a draft PR and bumps the versions of the packages.
- For each changed package, pick what the new version should be. Lerna will bump the versions, commit version bumps to `main`, and create a new git tag for each published package.
- If publishing a beta, make sure that the versions are all of the form `a.b.c-beta.d`, where `a`, `b`, and `c` are identical to the last normal release except for one, which has been incremented by 1.
1. Run `npm i` to update the package-lock with the updated versions.
1. Create a new PR from this branch into `main` and merge it (you can directly merge into the beta branch for a beta).
1. Checkout `main` and `git pull` (you can skip this step for a beta since you already have the latest version of the beta branch).
1. Actually publish the packages with one of the following:
- Stable release: Run `npx lerna publish from-package --yes`
- Beta release: Run `npx lerna publish from-package --dist-tag beta --yes`
Notice this allows developers to install the package with `npm add xrpl@beta`
1. If requested, enter your [npmjs.com](https://npmjs.com) OTP (one-time password) to complete publication.
1. If not a beta release: Create a new branch (`git checkout -b <BRANCH_NAME>`) to capture the updated packages from the release. Merge those changes into `main`.
NOW YOU HAVE PUBLISHED! But you're not done; we have to notify people!
1. Pull the most recent changes to `main` locally.
1. Run `git tag <tagname> -m <tagname>`, where `<tagname>` is the new package and version (e.g. `xrpl@2.1.1`), for each version released.
1. Run `git push --follow-tags`, to push the tags to Github.
1. On GitHub, click the "Releases" link on the right-hand side of the page.
1. Repeat for each release:
1. Click "Draft a new release"
1. Click "Choose a tag", and choose a tag that you just created.
1. Edit the name of the release to match the tag (IE \<package\>@\<version\>) and edit the description as you see fit.
1. Lastly, send an email to [xrpl-announce](https://groups.google.com/g/xrpl-announce).
# ripple-lib 1.x releases
- [ ] Publish the release to npm.
- [ ] If you are publishing a 1.x release to the `xrpl` package, use:
npm publish --tag ripple-lib
This prevents the release from taking the `latest` tag.
For ripple-lib:
- Have one of the ripple-lib package maintainers push to `ripple-lib` (npm package name). You can contact [@intelliot](https://github.com/intelliot) to request the npm publish.
- For ripple-lib releases, cross-publish the package to `xrpl` with `--tag ripple-lib`
- [Here's why](https://blog.greenkeeper.io/one-simple-trick-for-javascript-package-maintainers-to-avoid-breaking-their-user-s-software-and-to-6edf06dc5617).
- https://www.npmjs.com/package/ripple-lib
- https://www.npmjs.com/package/xrpl
## Mailing Lists
We have a low-traffic mailing list for announcements of new `xrpl.js` releases. (About 1 email every couple of weeks)
+ [Subscribe to xrpl-announce](https://groups.google.com/g/xrpl-announce)
- [Subscribe to xrpl-announce](https://groups.google.com/g/xrpl-announce)
If you're using the XRP Ledger in production, you should run a [rippled server](https://github.com/ripple/rippled) and subscribe to the ripple-server mailing list as well.
+ [Subscribe to ripple-server](https://groups.google.com/g/ripple-server)
- [Subscribe to ripple-server](https://groups.google.com/g/ripple-server)

522
package-lock.json generated
View File

@@ -1074,12 +1074,12 @@
}
},
"node_modules/@jest/expect-utils": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.4.2.tgz",
"integrity": "sha512-Dd3ilDJpBnqa0GiPN7QrudVs0cczMMHtehSo2CSTjm3zdHx0RcpmhFNVEltuEFeqfLIyWKFI224FsMSQ/nsJQA==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.4.3.tgz",
"integrity": "sha512-/6JWbkxHOP8EoS8jeeTd9dTfc9Uawi+43oLKHfp6zzux3U2hqOOVnV3ai4RpDYHOccL6g+5nrxpoc8DmJxtXVQ==",
"dev": true,
"dependencies": {
"jest-get-type": "^29.4.2"
"jest-get-type": "^29.4.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
@@ -1161,9 +1161,9 @@
}
},
"node_modules/@jest/schemas": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.2.tgz",
"integrity": "sha512-ZrGzGfh31NtdVH8tn0mgJw4khQuNHiKqdzJAFbCaERbyCP9tHlxWuL/mnMu8P7e/+k4puWjI1NOzi/sFsjce/g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.3.tgz",
"integrity": "sha512-VLYKXQmtmuEz6IxJsrZwzG9NvtkQsWNnWMsKxqWNu3+CnfzJQhp0WDDKWLVV9hLKr0l3SLLFRqcYHjhtyuDVxg==",
"dev": true,
"dependencies": {
"@sinclair/typebox": "^0.25.16"
@@ -1243,12 +1243,12 @@
}
},
"node_modules/@jest/types": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.4.2.tgz",
"integrity": "sha512-CKlngyGP0fwlgC1BRUtPZSiWLBhyS9dKwKmyGxk8Z6M82LBEGB2aLQSg+U1MyLsU+M7UjnlLllBM2BLWKVm/Uw==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.4.3.tgz",
"integrity": "sha512-bPYfw8V65v17m2Od1cv44FH+SiKW7w2Xu7trhcdTLUmSv85rfKsP+qXSjO4KGJr4dtPSzl/gvslZBXctf1qGEA==",
"dev": true,
"dependencies": {
"@jest/schemas": "^29.4.2",
"@jest/schemas": "^29.4.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
@@ -2684,9 +2684,9 @@
"dev": true
},
"node_modules/@sinclair/typebox": {
"version": "0.25.21",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.21.tgz",
"integrity": "sha512-gFukHN4t8K4+wVC+ECqeqwzBDeFeTzBXroBTqE6vcWrQGbEUpHO7LYdG0f4xnvYq4VOEwITSlHlp0JBAIFMS/g==",
"version": "0.25.24",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.24.tgz",
"integrity": "sha512-XJfwUVUKDHF5ugKwIcxEgc9k8b7HbznCp6eUfWgu710hMPNIO4aw4/zB5RogDQz8nd6gyCDpU9O/m6qYEWY6yQ==",
"dev": true
},
"node_modules/@sinonjs/commons": {
@@ -2722,6 +2722,22 @@
"node": ">= 6"
}
},
"node_modules/@transia/ripple-address-codec": {
"resolved": "packages/ripple-address-codec",
"link": true
},
"node_modules/@transia/ripple-binary-codec": {
"resolved": "packages/ripple-binary-codec",
"link": true
},
"node_modules/@transia/ripple-keypairs": {
"resolved": "packages/ripple-keypairs",
"link": true
},
"node_modules/@transia/xrpl": {
"resolved": "packages/xrpl",
"link": true
},
"node_modules/@tsconfig/node10": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz",
@@ -5871,9 +5887,9 @@
}
},
"node_modules/diff-sequences": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.2.tgz",
"integrity": "sha512-R6P0Y6PrsH3n4hUXxL3nns0rbRk6Q33js3ygJBeEpbzLzgcNuJ61+u0RXasFpTKISw99TxUzFnumSnRLsjhLaw==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.3.tgz",
"integrity": "sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==",
"dev": true,
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
@@ -7121,16 +7137,16 @@
}
},
"node_modules/expect": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/expect/-/expect-29.4.2.tgz",
"integrity": "sha512-+JHYg9O3hd3RlICG90OPVjRkPBoiUH7PxvDVMnRiaq1g6JUgZStX514erMl0v2Dc5SkfVbm7ztqbd6qHHPn+mQ==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/expect/-/expect-29.4.3.tgz",
"integrity": "sha512-uC05+Q7eXECFpgDrHdXA4k2rpMyStAYPItEDLyQDo5Ta7fVkJnNA/4zh/OIVkVVNZ1oOK1PipQoyNjuZ6sz6Dg==",
"dev": true,
"dependencies": {
"@jest/expect-utils": "^29.4.2",
"jest-get-type": "^29.4.2",
"jest-matcher-utils": "^29.4.2",
"jest-message-util": "^29.4.2",
"jest-util": "^29.4.2"
"@jest/expect-utils": "^29.4.3",
"jest-get-type": "^29.4.3",
"jest-matcher-utils": "^29.4.3",
"jest-message-util": "^29.4.3",
"jest-util": "^29.4.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
@@ -9650,15 +9666,15 @@
}
},
"node_modules/jest-diff": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.4.2.tgz",
"integrity": "sha512-EK8DSajVtnjx9sa1BkjZq3mqChm2Cd8rIzdXkQMA8e0wuXq53ypz6s5o5V8HRZkoEt2ywJ3eeNWFKWeYr8HK4g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.4.3.tgz",
"integrity": "sha512-YB+ocenx7FZ3T5O9lMVMeLYV4265socJKtkwgk/6YUz/VsEzYDkiMuMhWzZmxm3wDRQvayJu/PjkjjSkjoHsCA==",
"dev": true,
"dependencies": {
"chalk": "^4.0.0",
"diff-sequences": "^29.4.2",
"jest-get-type": "^29.4.2",
"pretty-format": "^29.4.2"
"diff-sequences": "^29.4.3",
"jest-get-type": "^29.4.3",
"pretty-format": "^29.4.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
@@ -9710,9 +9726,9 @@
}
},
"node_modules/jest-get-type": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.2.tgz",
"integrity": "sha512-vERN30V5i2N6lqlFu4ljdTqQAgrkTFMC9xaIIfOPYBw04pufjXRty5RuXBiB1d72tGbURa/UgoiHB90ruOSivg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.3.tgz",
"integrity": "sha512-J5Xez4nRRMjk8emnTpWrlkyb9pfRQQanDrvWHhsR1+VUfbwxi30eVcZFlcdGInRibU4G5LwHXpI7IRHU0CY+gg==",
"dev": true,
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
@@ -9757,33 +9773,33 @@
}
},
"node_modules/jest-matcher-utils": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.4.2.tgz",
"integrity": "sha512-EZaAQy2je6Uqkrm6frnxBIdaWtSYFoR8SVb2sNLAtldswlR/29JAgx+hy67llT3+hXBaLB0zAm5UfeqerioZyg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.4.3.tgz",
"integrity": "sha512-TTciiXEONycZ03h6R6pYiZlSkvYgT0l8aa49z/DLSGYjex4orMUcafuLXYyyEDWB1RKglq00jzwY00Ei7yFNVg==",
"dev": true,
"dependencies": {
"chalk": "^4.0.0",
"jest-diff": "^29.4.2",
"jest-get-type": "^29.4.2",
"pretty-format": "^29.4.2"
"jest-diff": "^29.4.3",
"jest-get-type": "^29.4.3",
"pretty-format": "^29.4.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/jest-message-util": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.4.2.tgz",
"integrity": "sha512-SElcuN4s6PNKpOEtTInjOAA8QvItu0iugkXqhYyguRvQoXapg5gN+9RQxLAkakChZA7Y26j6yUCsFWN+hlKD6g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.4.3.tgz",
"integrity": "sha512-1Y8Zd4ZCN7o/QnWdMmT76If8LuDv23Z1DRovBj/vcSFNlGCJGoO8D1nJDw1AdyAGUk0myDLFGN5RbNeJyCRGCw==",
"dev": true,
"dependencies": {
"@babel/code-frame": "^7.12.13",
"@jest/types": "^29.4.2",
"@jest/types": "^29.4.3",
"@types/stack-utils": "^2.0.0",
"chalk": "^4.0.0",
"graceful-fs": "^4.2.9",
"micromatch": "^4.0.4",
"pretty-format": "^29.4.2",
"pretty-format": "^29.4.3",
"slash": "^3.0.0",
"stack-utils": "^2.0.3"
},
@@ -9976,12 +9992,12 @@
}
},
"node_modules/jest-util": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.4.2.tgz",
"integrity": "sha512-wKnm6XpJgzMUSRFB7YF48CuwdzuDIHenVuoIb1PLuJ6F+uErZsuDkU+EiExkChf6473XcawBrSfDSnXl+/YG4g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.4.3.tgz",
"integrity": "sha512-ToSGORAz4SSSoqxDSylWX8JzkOQR7zoBtNRsA7e+1WUX5F8jrOwaNpuh1YfJHJKDHXLHmObv5eOjejUd+/Ws+Q==",
"dev": true,
"dependencies": {
"@jest/types": "^29.4.2",
"@jest/types": "^29.4.3",
"@types/node": "*",
"chalk": "^4.0.0",
"ci-info": "^3.2.0",
@@ -13474,12 +13490,12 @@
}
},
"node_modules/pretty-format": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.4.2.tgz",
"integrity": "sha512-qKlHR8yFVCbcEWba0H0TOC8dnLlO4vPlyEjRPw31FZ2Rupy9nLa8ZLbYny8gWEl8CkEhJqAE6IzdNELTBVcBEg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.4.3.tgz",
"integrity": "sha512-cvpcHTc42lcsvOOAzd3XuNWTcvk1Jmnzqeu+WsOuiPmxUJTnkbAcFNsRKvEpBEUFVUgy/GTZLulZDcDEi+CIlA==",
"dev": true,
"dependencies": {
"@jest/schemas": "^29.4.2",
"@jest/schemas": "^29.4.3",
"ansi-styles": "^5.0.0",
"react-is": "^18.0.0"
},
@@ -16529,9 +16545,9 @@
}
},
"node_modules/webpack": {
"version": "5.75.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.75.0.tgz",
"integrity": "sha512-piaIaoVJlqMsPtX/+3KTTO6jfvrSYgauFVdt8cr9LTHKmcq/AMd4mhzsiP7ZF/PGRNPGA8336jldh9l2Kt2ogQ==",
"version": "5.76.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.76.0.tgz",
"integrity": "sha512-l5sOdYBDunyf72HW8dF23rFtWq/7Zgvt/9ftMof71E/yUb1YLOBmTgA2K4vQthB3kotMrSj609txVE0dnr2fjA==",
"dev": true,
"dependencies": {
"@types/eslint-scope": "^3.7.3",
@@ -17124,7 +17140,8 @@
}
},
"packages/ripple-address-codec": {
"version": "4.2.5",
"name": "@transia/ripple-address-codec",
"version": "4.2.6-tbeta.0",
"license": "ISC",
"dependencies": {
"base-x": "^3.0.9",
@@ -17135,7 +17152,8 @@
}
},
"packages/ripple-binary-codec": {
"version": "1.4.3",
"name": "@transia/ripple-binary-codec",
"version": "1.4.4-tbeta.0",
"license": "ISC",
"dependencies": {
"assert": "^2.0.0",
@@ -17157,8 +17175,21 @@
"ieee754": "^1.1.4"
}
},
"packages/ripple-binary-codec/node_modules/ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"dependencies": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
},
"engines": {
"node": ">= 10"
}
},
"packages/ripple-keypairs": {
"version": "1.1.5",
"name": "@transia/ripple-keypairs",
"version": "1.1.6-tbeta.0",
"license": "ISC",
"dependencies": {
"bn.js": "^5.1.1",
@@ -17171,8 +17202,21 @@
"node": ">= 10"
}
},
"packages/ripple-keypairs/node_modules/ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"dependencies": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
},
"engines": {
"node": ">= 10"
}
},
"packages/xrpl": {
"version": "2.7.0",
"name": "@transia/xrpl",
"version": "2.7.1-tbeta.0",
"license": "ISC",
"dependencies": {
"bignumber.js": "^9.0.0",
@@ -17203,6 +17247,58 @@
"engines": {
"node": ">=10.13.0"
}
},
"packages/xrpl/node_modules/buffer": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.6.0.tgz",
"integrity": "sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==",
"dependencies": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"packages/xrpl/node_modules/ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"dependencies": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
},
"engines": {
"node": ">= 10"
}
},
"packages/xrpl/node_modules/ripple-binary-codec": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ripple-binary-codec/-/ripple-binary-codec-1.4.3.tgz",
"integrity": "sha512-P4ALjAJWBJpRApTQO+dJCrHE6mZxm7ypZot9OS0a3RCKOWTReNw0pDWfdhCGh1qXh71TeQnAk4CHdMLwR/76oQ==",
"dependencies": {
"assert": "^2.0.0",
"big-integer": "^1.6.48",
"buffer": "5.6.0",
"create-hash": "^1.2.0",
"decimal.js": "^10.2.0",
"ripple-address-codec": "^4.2.5"
},
"engines": {
"node": ">= 10"
}
},
"packages/xrpl/node_modules/ripple-keypairs": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/ripple-keypairs/-/ripple-keypairs-1.1.5.tgz",
"integrity": "sha512-wLJXIBsMVazn2Yp/7oP4PvgA4Gd1HtuZLftdEJFNOLgraf82phqa2AnNK3t9f3XeQnApW1jAe/FcFFOY6QUn5w==",
"dependencies": {
"bn.js": "^5.1.1",
"brorand": "^1.0.5",
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.2.5"
},
"engines": {
"node": ">= 10"
}
}
},
"dependencies": {
@@ -17971,12 +18067,12 @@
}
},
"@jest/expect-utils": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.4.2.tgz",
"integrity": "sha512-Dd3ilDJpBnqa0GiPN7QrudVs0cczMMHtehSo2CSTjm3zdHx0RcpmhFNVEltuEFeqfLIyWKFI224FsMSQ/nsJQA==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.4.3.tgz",
"integrity": "sha512-/6JWbkxHOP8EoS8jeeTd9dTfc9Uawi+43oLKHfp6zzux3U2hqOOVnV3ai4RpDYHOccL6g+5nrxpoc8DmJxtXVQ==",
"dev": true,
"requires": {
"jest-get-type": "^29.4.2"
"jest-get-type": "^29.4.3"
}
},
"@jest/fake-timers": {
@@ -18038,9 +18134,9 @@
}
},
"@jest/schemas": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.2.tgz",
"integrity": "sha512-ZrGzGfh31NtdVH8tn0mgJw4khQuNHiKqdzJAFbCaERbyCP9tHlxWuL/mnMu8P7e/+k4puWjI1NOzi/sFsjce/g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.3.tgz",
"integrity": "sha512-VLYKXQmtmuEz6IxJsrZwzG9NvtkQsWNnWMsKxqWNu3+CnfzJQhp0WDDKWLVV9hLKr0l3SLLFRqcYHjhtyuDVxg==",
"dev": true,
"requires": {
"@sinclair/typebox": "^0.25.16"
@@ -18105,12 +18201,12 @@
}
},
"@jest/types": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.4.2.tgz",
"integrity": "sha512-CKlngyGP0fwlgC1BRUtPZSiWLBhyS9dKwKmyGxk8Z6M82LBEGB2aLQSg+U1MyLsU+M7UjnlLllBM2BLWKVm/Uw==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.4.3.tgz",
"integrity": "sha512-bPYfw8V65v17m2Od1cv44FH+SiKW7w2Xu7trhcdTLUmSv85rfKsP+qXSjO4KGJr4dtPSzl/gvslZBXctf1qGEA==",
"dev": true,
"requires": {
"@jest/schemas": "^29.4.2",
"@jest/schemas": "^29.4.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
@@ -19315,9 +19411,9 @@
"dev": true
},
"@sinclair/typebox": {
"version": "0.25.21",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.21.tgz",
"integrity": "sha512-gFukHN4t8K4+wVC+ECqeqwzBDeFeTzBXroBTqE6vcWrQGbEUpHO7LYdG0f4xnvYq4VOEwITSlHlp0JBAIFMS/g==",
"version": "0.25.24",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.24.tgz",
"integrity": "sha512-XJfwUVUKDHF5ugKwIcxEgc9k8b7HbznCp6eUfWgu710hMPNIO4aw4/zB5RogDQz8nd6gyCDpU9O/m6qYEWY6yQ==",
"dev": true
},
"@sinonjs/commons": {
@@ -19350,6 +19446,135 @@
"integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==",
"dev": true
},
"@transia/ripple-address-codec": {
"version": "file:packages/ripple-address-codec",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
},
"@transia/ripple-binary-codec": {
"version": "file:packages/ripple-binary-codec",
"requires": {
"assert": "^2.0.0",
"big-integer": "^1.6.48",
"buffer": "5.6.0",
"create-hash": "^1.2.0",
"decimal.js": "^10.2.0",
"ripple-address-codec": "^4.2.5"
},
"dependencies": {
"buffer": {
"version": "5.6.0",
"requires": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
}
}
},
"@transia/ripple-keypairs": {
"version": "file:packages/ripple-keypairs",
"requires": {
"bn.js": "^5.1.1",
"brorand": "^1.0.5",
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.2.5"
},
"dependencies": {
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
}
}
},
"@transia/xrpl": {
"version": "file:packages/xrpl",
"requires": {
"@geut/browser-node-core": "^2.0.13",
"@types/node": "^14.18.36",
"assert-browserify": "^2.0.0",
"bignumber.js": "^9.0.0",
"bip32": "^2.0.6",
"bip39": "^3.0.4",
"browserify-fs": "^1.0.0",
"constants-browserify": "^1.0.0",
"https-browserify": "^1.0.0",
"https-proxy-agent": "^5.0.0",
"karma": "^6.4.1",
"karma-chrome-launcher": "^3.1.1",
"karma-jasmine": "^5.1.0",
"karma-webpack": "^5.0.0",
"lodash": "^4.17.4",
"node-polyfill-webpack-plugin": "^2.0.1",
"react": "^18.2.0",
"ripple-address-codec": "^4.2.5",
"ripple-binary-codec": "^1.4.3",
"ripple-keypairs": "^1.1.5",
"typedoc": "^0.23.24",
"ws": "^8.2.2"
},
"dependencies": {
"buffer": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.6.0.tgz",
"integrity": "sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==",
"requires": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
},
"ripple-binary-codec": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ripple-binary-codec/-/ripple-binary-codec-1.4.3.tgz",
"integrity": "sha512-P4ALjAJWBJpRApTQO+dJCrHE6mZxm7ypZot9OS0a3RCKOWTReNw0pDWfdhCGh1qXh71TeQnAk4CHdMLwR/76oQ==",
"requires": {
"assert": "^2.0.0",
"big-integer": "^1.6.48",
"buffer": "5.6.0",
"create-hash": "^1.2.0",
"decimal.js": "^10.2.0",
"ripple-address-codec": "^4.2.5"
}
},
"ripple-keypairs": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/ripple-keypairs/-/ripple-keypairs-1.1.5.tgz",
"integrity": "sha512-wLJXIBsMVazn2Yp/7oP4PvgA4Gd1HtuZLftdEJFNOLgraf82phqa2AnNK3t9f3XeQnApW1jAe/FcFFOY6QUn5w==",
"requires": {
"bn.js": "^5.1.1",
"brorand": "^1.0.5",
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.2.5"
}
}
}
},
"@tsconfig/node10": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz",
@@ -21902,9 +22127,9 @@
"dev": true
},
"diff-sequences": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.2.tgz",
"integrity": "sha512-R6P0Y6PrsH3n4hUXxL3nns0rbRk6Q33js3ygJBeEpbzLzgcNuJ61+u0RXasFpTKISw99TxUzFnumSnRLsjhLaw==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.3.tgz",
"integrity": "sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==",
"dev": true
},
"diffie-hellman": {
@@ -22859,16 +23084,16 @@
"dev": true
},
"expect": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/expect/-/expect-29.4.2.tgz",
"integrity": "sha512-+JHYg9O3hd3RlICG90OPVjRkPBoiUH7PxvDVMnRiaq1g6JUgZStX514erMl0v2Dc5SkfVbm7ztqbd6qHHPn+mQ==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/expect/-/expect-29.4.3.tgz",
"integrity": "sha512-uC05+Q7eXECFpgDrHdXA4k2rpMyStAYPItEDLyQDo5Ta7fVkJnNA/4zh/OIVkVVNZ1oOK1PipQoyNjuZ6sz6Dg==",
"dev": true,
"requires": {
"@jest/expect-utils": "^29.4.2",
"jest-get-type": "^29.4.2",
"jest-matcher-utils": "^29.4.2",
"jest-message-util": "^29.4.2",
"jest-util": "^29.4.2"
"@jest/expect-utils": "^29.4.3",
"jest-get-type": "^29.4.3",
"jest-matcher-utils": "^29.4.3",
"jest-message-util": "^29.4.3",
"jest-util": "^29.4.3"
}
},
"extend": {
@@ -24757,15 +24982,15 @@
}
},
"jest-diff": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.4.2.tgz",
"integrity": "sha512-EK8DSajVtnjx9sa1BkjZq3mqChm2Cd8rIzdXkQMA8e0wuXq53ypz6s5o5V8HRZkoEt2ywJ3eeNWFKWeYr8HK4g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.4.3.tgz",
"integrity": "sha512-YB+ocenx7FZ3T5O9lMVMeLYV4265socJKtkwgk/6YUz/VsEzYDkiMuMhWzZmxm3wDRQvayJu/PjkjjSkjoHsCA==",
"dev": true,
"requires": {
"chalk": "^4.0.0",
"diff-sequences": "^29.4.2",
"jest-get-type": "^29.4.2",
"pretty-format": "^29.4.2"
"diff-sequences": "^29.4.3",
"jest-get-type": "^29.4.3",
"pretty-format": "^29.4.3"
}
},
"jest-docblock": {
@@ -24805,9 +25030,9 @@
}
},
"jest-get-type": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.2.tgz",
"integrity": "sha512-vERN30V5i2N6lqlFu4ljdTqQAgrkTFMC9xaIIfOPYBw04pufjXRty5RuXBiB1d72tGbURa/UgoiHB90ruOSivg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.3.tgz",
"integrity": "sha512-J5Xez4nRRMjk8emnTpWrlkyb9pfRQQanDrvWHhsR1+VUfbwxi30eVcZFlcdGInRibU4G5LwHXpI7IRHU0CY+gg==",
"dev": true
},
"jest-haste-map": {
@@ -24841,30 +25066,30 @@
}
},
"jest-matcher-utils": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.4.2.tgz",
"integrity": "sha512-EZaAQy2je6Uqkrm6frnxBIdaWtSYFoR8SVb2sNLAtldswlR/29JAgx+hy67llT3+hXBaLB0zAm5UfeqerioZyg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.4.3.tgz",
"integrity": "sha512-TTciiXEONycZ03h6R6pYiZlSkvYgT0l8aa49z/DLSGYjex4orMUcafuLXYyyEDWB1RKglq00jzwY00Ei7yFNVg==",
"dev": true,
"requires": {
"chalk": "^4.0.0",
"jest-diff": "^29.4.2",
"jest-get-type": "^29.4.2",
"pretty-format": "^29.4.2"
"jest-diff": "^29.4.3",
"jest-get-type": "^29.4.3",
"pretty-format": "^29.4.3"
}
},
"jest-message-util": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.4.2.tgz",
"integrity": "sha512-SElcuN4s6PNKpOEtTInjOAA8QvItu0iugkXqhYyguRvQoXapg5gN+9RQxLAkakChZA7Y26j6yUCsFWN+hlKD6g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.4.3.tgz",
"integrity": "sha512-1Y8Zd4ZCN7o/QnWdMmT76If8LuDv23Z1DRovBj/vcSFNlGCJGoO8D1nJDw1AdyAGUk0myDLFGN5RbNeJyCRGCw==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.12.13",
"@jest/types": "^29.4.2",
"@jest/types": "^29.4.3",
"@types/stack-utils": "^2.0.0",
"chalk": "^4.0.0",
"graceful-fs": "^4.2.9",
"micromatch": "^4.0.4",
"pretty-format": "^29.4.2",
"pretty-format": "^29.4.3",
"slash": "^3.0.0",
"stack-utils": "^2.0.3"
}
@@ -25025,12 +25250,12 @@
}
},
"jest-util": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.4.2.tgz",
"integrity": "sha512-wKnm6XpJgzMUSRFB7YF48CuwdzuDIHenVuoIb1PLuJ6F+uErZsuDkU+EiExkChf6473XcawBrSfDSnXl+/YG4g==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.4.3.tgz",
"integrity": "sha512-ToSGORAz4SSSoqxDSylWX8JzkOQR7zoBtNRsA7e+1WUX5F8jrOwaNpuh1YfJHJKDHXLHmObv5eOjejUd+/Ws+Q==",
"dev": true,
"requires": {
"@jest/types": "^29.4.2",
"@jest/types": "^29.4.3",
"@types/node": "*",
"chalk": "^4.0.0",
"ci-info": "^3.2.0",
@@ -27856,12 +28081,12 @@
}
},
"pretty-format": {
"version": "29.4.2",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.4.2.tgz",
"integrity": "sha512-qKlHR8yFVCbcEWba0H0TOC8dnLlO4vPlyEjRPw31FZ2Rupy9nLa8ZLbYny8gWEl8CkEhJqAE6IzdNELTBVcBEg==",
"version": "29.4.3",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.4.3.tgz",
"integrity": "sha512-cvpcHTc42lcsvOOAzd3XuNWTcvk1Jmnzqeu+WsOuiPmxUJTnkbAcFNsRKvEpBEUFVUgy/GTZLulZDcDEi+CIlA==",
"dev": true,
"requires": {
"@jest/schemas": "^29.4.2",
"@jest/schemas": "^29.4.3",
"ansi-styles": "^5.0.0",
"react-is": "^18.0.0"
},
@@ -28681,6 +28906,15 @@
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
}
}
},
@@ -28692,6 +28926,17 @@
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.2.5"
},
"dependencies": {
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
}
}
},
"run-async": {
@@ -30224,9 +30469,9 @@
"dev": true
},
"webpack": {
"version": "5.75.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.75.0.tgz",
"integrity": "sha512-piaIaoVJlqMsPtX/+3KTTO6jfvrSYgauFVdt8cr9LTHKmcq/AMd4mhzsiP7ZF/PGRNPGA8336jldh9l2Kt2ogQ==",
"version": "5.76.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.76.0.tgz",
"integrity": "sha512-l5sOdYBDunyf72HW8dF23rFtWq/7Zgvt/9ftMof71E/yUb1YLOBmTgA2K4vQthB3kotMrSj609txVE0dnr2fjA==",
"dev": true,
"requires": {
"@types/eslint-scope": "^3.7.3",
@@ -30605,6 +30850,51 @@
"ripple-keypairs": "^1.1.5",
"typedoc": "^0.23.24",
"ws": "^8.2.2"
},
"dependencies": {
"buffer": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.6.0.tgz",
"integrity": "sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==",
"requires": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"ripple-address-codec": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/ripple-address-codec/-/ripple-address-codec-4.2.5.tgz",
"integrity": "sha512-SZ96zZH+0REeyEcYVFl0vqcsGRXiFXS2RUgHupHhtVkOEk6men53vngVjJwBrSnY+oa6Cri15q1zSni3DEoxNw==",
"requires": {
"base-x": "^3.0.9",
"create-hash": "^1.1.2"
}
},
"ripple-binary-codec": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ripple-binary-codec/-/ripple-binary-codec-1.4.3.tgz",
"integrity": "sha512-P4ALjAJWBJpRApTQO+dJCrHE6mZxm7ypZot9OS0a3RCKOWTReNw0pDWfdhCGh1qXh71TeQnAk4CHdMLwR/76oQ==",
"requires": {
"assert": "^2.0.0",
"big-integer": "^1.6.48",
"buffer": "5.6.0",
"create-hash": "^1.2.0",
"decimal.js": "^10.2.0",
"ripple-address-codec": "^4.2.5"
}
},
"ripple-keypairs": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/ripple-keypairs/-/ripple-keypairs-1.1.5.tgz",
"integrity": "sha512-wLJXIBsMVazn2Yp/7oP4PvgA4Gd1HtuZLftdEJFNOLgraf82phqa2AnNK3t9f3XeQnApW1jAe/FcFFOY6QUn5w==",
"requires": {
"bn.js": "^5.1.1",
"brorand": "^1.0.5",
"elliptic": "^6.5.4",
"hash.js": "^1.0.3",
"ripple-address-codec": "^4.2.5"
}
}
}
},
"xtend": {

View File

@@ -1,12 +1,12 @@
{
"name": "ripple-address-codec",
"version": "4.2.5",
"version": "4.2.6-tbeta.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "ripple-address-codec",
"version": "4.2.4",
"version": "4.2.6-tbeta.0",
"license": "ISC",
"dependencies": {
"base-x": "^3.0.9",

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-address-codec",
"version": "4.2.5",
"name": "@transia/ripple-address-codec",
"version": "4.2.6-tbeta.0",
"description": "encodes/decodes base58 encoded XRP Ledger identifiers",
"files": [
"dist/*",
@@ -15,7 +15,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com:Transia-RnD/xrpl.js/tree/transia-beta"
},
"prepublish": "tsc -b",
"prepublishOnly": "tslint -b ./ && jest",

View File

@@ -1,6 +1,8 @@
# ripple-binary-codec Release History
## Unreleased
### Added
- Allow custom type definitions to be used for encoding/decoding transactions at runtime (e.g. for sidechains/new amendments)
## 1.5.0 (2023-03-08)
### Changed

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-binary-codec",
"version": "1.4.3",
"name": "@transia/ripple-binary-codec",
"version": "1.4.4-tbeta.0",
"description": "XRP Ledger binary codec",
"files": [
"dist/*",
@@ -28,7 +28,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com:Transia-RnD/xrpl.js/tree/transia-beta"
},
"bugs": {
"url": "https://github.com/XRPLF/xrpl.js/issues"

View File

@@ -6,7 +6,11 @@ import { AccountID } from './types/account-id'
import { HashPrefix } from './hash-prefixes'
import { BinarySerializer, BytesList } from './serdes/binary-serializer'
import { sha512Half, transactionID } from './hashes'
import { FieldInstance } from './enums'
import {
type XrplDefinitionsBase,
DEFAULT_DEFINITIONS,
type FieldInstance,
} from './enums'
import { STObject } from './types/st-object'
import { JsonObject } from './types/serialized-type'
import { Buffer } from 'buffer/'
@@ -16,26 +20,41 @@ import bigInt = require('big-integer')
* Construct a BinaryParser
*
* @param bytes hex-string to construct BinaryParser from
* @param definitions rippled definitions used to parse the values of transaction types and such.
* Can be customized for sidechains and amendments.
* @returns A BinaryParser
*/
const makeParser = (bytes: string): BinaryParser => new BinaryParser(bytes)
const makeParser = (
bytes: string,
definitions?: XrplDefinitionsBase,
): BinaryParser => new BinaryParser(bytes, definitions)
/**
* Parse BinaryParser into JSON
*
* @param parser BinaryParser object
* @param definitions rippled definitions used to parse the values of transaction types and such.
* Can be customized for sidechains and amendments.
* @returns JSON for the bytes in the BinaryParser
*/
const readJSON = (parser: BinaryParser): JsonObject =>
(parser.readType(coreTypes.STObject) as STObject).toJSON()
const readJSON = (
parser: BinaryParser,
definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,
): JsonObject =>
(parser.readType(coreTypes.STObject) as STObject).toJSON(definitions)
/**
* Parse a hex-string into its JSON interpretation
*
* @param bytes hex-string to parse into JSON
* @param definitions rippled definitions used to parse the values of transaction types and such.
* Can be customized for sidechains and amendments.
* @returns JSON
*/
const binaryToJSON = (bytes: string): JsonObject => readJSON(makeParser(bytes))
const binaryToJSON = (
bytes: string,
definitions?: XrplDefinitionsBase,
): JsonObject => readJSON(makeParser(bytes, definitions), definitions)
/**
* Interface for passing parameters to SerializeObject
@@ -46,17 +65,18 @@ interface OptionObject {
prefix?: Buffer
suffix?: Buffer
signingFieldsOnly?: boolean
definitions?: XrplDefinitionsBase
}
/**
* Function to serialize JSON object representing a transaction
*
* @param object JSON object to serialize
* @param opts options for serializing, including optional prefix, suffix, and signingFieldOnly
* @param opts options for serializing, including optional prefix, suffix, signingFieldOnly, and definitions
* @returns A Buffer containing the serialized object
*/
function serializeObject(object: JsonObject, opts: OptionObject = {}): Buffer {
const { prefix, suffix, signingFieldsOnly = false } = opts
const { prefix, suffix, signingFieldsOnly = false, definitions } = opts
const bytesList = new BytesList()
if (prefix) {
@@ -66,8 +86,9 @@ function serializeObject(object: JsonObject, opts: OptionObject = {}): Buffer {
const filter = signingFieldsOnly
? (f: FieldInstance): boolean => f.isSigningField
: undefined
coreTypes.STObject.from(object, filter).toBytesSink(bytesList)
;(coreTypes.STObject as typeof STObject)
.from(object, filter, definitions)
.toBytesSink(bytesList)
if (suffix) {
bytesList.put(suffix)
@@ -81,13 +102,19 @@ function serializeObject(object: JsonObject, opts: OptionObject = {}): Buffer {
*
* @param transaction Transaction to serialize
* @param prefix Prefix bytes to put before the serialized object
* @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns A Buffer with the serialized object
*/
function signingData(
transaction: JsonObject,
prefix: Buffer = HashPrefix.transactionSig,
opts: { definitions?: XrplDefinitionsBase } = {},
): Buffer {
return serializeObject(transaction, { prefix, signingFieldsOnly: true })
return serializeObject(transaction, {
prefix,
signingFieldsOnly: true,
definitions: opts.definitions,
})
}
/**
@@ -102,6 +129,7 @@ interface ClaimObject extends JsonObject {
* Serialize a signingClaim
*
* @param claim A claim object to serialize
* @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns the serialized object with appropriate prefix
*/
function signingClaimData(claim: ClaimObject): Buffer {
@@ -123,11 +151,15 @@ function signingClaimData(claim: ClaimObject): Buffer {
*
* @param transaction transaction to serialize
* @param signingAccount Account to sign the transaction with
* @param opts.definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns serialized transaction with appropriate prefix and suffix
*/
function multiSigningData(
transaction: JsonObject,
signingAccount: string | AccountID,
opts: { definitions: XrplDefinitionsBase } = {
definitions: DEFAULT_DEFINITIONS,
},
): Buffer {
const prefix = HashPrefix.transactionMultiSig
const suffix = coreTypes.AccountID.from(signingAccount).toBytes()
@@ -135,6 +167,7 @@ function multiSigningData(
prefix,
suffix,
signingFieldsOnly: true,
definitions: opts.definitions,
})
}

View File

@@ -1,4 +1,5 @@
import {
DEFAULT_DEFINITIONS,
Field,
TransactionType,
LedgerEntryType,
@@ -17,6 +18,7 @@ export {
hashes,
binary,
ledgerHashes,
DEFAULT_DEFINITIONS,
Field,
TransactionType,
LedgerEntryType,

View File

@@ -1,5 +1,9 @@
# Definitions
This file is used to serialize/deserialize transactions and ledger objects for the XRPL. It's broken into 5 sections laid out below.
At the bottom of this README you can find instructions and examples for how to define your own types in a definitions file in order to work on a custom sidechain or develop new amendments.
## Types
These are the [types](https://xrpl.org/serialization.html#type-list) associated with a given Serialization Field. Each type has an arbitrary [type_code](https://xrpl.org/serialization.html#type-codes), with lower codes sorting first.
@@ -53,8 +57,88 @@ See:
- https://github.com/ripple/rippled/blob/develop/src/ripple/protocol/TER.h
- https://xrpl.org/transaction-results.html
TODO: Write a script to read rippled's source file and generate the necessary mapping.
To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
## Transaction Types
See https://github.com/ripple/rippled/blob/develop/src/ripple/protocol/TxFormats.h
# Defining Your Own Definitions
If you're building your own sidechain or writing an amendment for the XRPL, you may need to create new XRPL definitions.
To do that there are a couple things you need to do:
1. Generate your own `definitions.json` file from rippled source code using [this tool](https://github.com/RichardAH/xrpl-codec-gen) (The default `definitions.json` for mainnet can be found [here](https://github.com/XRPLF/xrpl.js/blob/main/packages/ripple-binary-codec/src/enums/definitions.json))
2. Create new SerializedType classes for any new Types (So that encode/decode behavior is defined). The SerializedType classes correspond to "ST..." classes in Rippled. Note: This is very rarely required.
- For examples of how to implement that you can look at objects in the [`types` folder](../types/), such as `Amount`, `UInt8`, or `STArray`.
3. Import your `definitions.json` file to construct your own `XrplDefinitions` object.
4. Pass the `XrplDefinitions` object whenever you `encode` or `decode` a transaction.
5. If you added any new transaction types, you should create an `interface` for the transaction that extends `BaseTransaction` from the `xrpl` repo to use it with the functions on `Client` (See the below example of adding a new transaction type)
## Example of adding a new Transaction type
```
// newDefinitionsJson is where you can import your custom defined definitions.json file
const newDefinitionsJson = require('./new-transaction-type-definitions.json')
const { XrplDefinitions, Client } = require('xrpl')
const newDefs = new XrplDefinitions(newDefinitionsJson)
// Change to point at the server you care about
const serverAddress = 'wss://s.devnet.rippletest.net:51233'
const client = new Client(serverAddress)
const wallet1 = await client.fundWallet()
// Extending BaseTransaction allows typescript to recognize this as a transaction type
interface NewTx extends BaseTransaction {
Amount: Amount
}
const tx: NewTx = {
// The TransactionType here needs to match what you added in your newDefinitionsJson file
TransactionType: 'NewTx',
Account: wallet1.address,
Amount: '100',
}
// By passing in your newDefs, your new transaction should be serializable.
// Rippled will still throw an error though if it's not a supported transaction type.
const result = await client.submitAndWait(tx, {
wallet: wallet1,
definitions: newDefs,
})
```
## Example of adding a new serializable Type
```
const { XrplDefinitions } = require('../dist/coretypes')
// newDefinitionsJson is where you can import your custom defined definitions.json file
const newDefinitionsJson = require('./fixtures/new-definitions.json')
// For any new Types you create, you'll need to make a class with the same name which extends a SerializedType object
// In order to define how to serialize/deserialize that field. Here we simply make our NewType act like a UInt32.
const { UInt32 } = require('../dist/types/uint-32')
class NewType extends UInt32 {
// Should be the same as UInt32
}
const extendedCoreTypes = { NewType }
const newDefs = new XrplDefinitions(newDefinitionsJson, extendedCoreTypes)
// From this point on, we should be able to serialize / deserialize Transactions with fields that have 'NewType' as their Type.
const encoded = encode(my_tx, newDefs)
const decoded = decode(encoded, newDefs)
```
## Other examples
You can find other examples of how to modify `definitions.json` in `definition.test.js` which contains tests for this feature, and uses various example modified `definition` files. You can find the tests and the corresponding example `definition` files in [this folder of test cases](https://github.com/XRPLF/xrpl.js/tree/main/packages/ripple-binary-codec/test)

View File

@@ -0,0 +1,75 @@
import { BytesList, BinaryParser } from '../binary'
import { Buffer } from 'buffer/'
/*
* @brief: Bytes, name, and ordinal representing one type, ledger_type, transaction type, or result
*/
export class Bytes {
readonly bytes: Buffer
constructor(
readonly name: string,
readonly ordinal: number,
readonly ordinalWidth: number,
) {
this.bytes = Buffer.alloc(ordinalWidth)
for (let i = 0; i < ordinalWidth; i++) {
this.bytes[ordinalWidth - i - 1] = (ordinal >>> (i * 8)) & 0xff
}
}
toJSON(): string {
return this.name
}
toBytesSink(sink: BytesList): void {
sink.put(this.bytes)
}
toBytes(): Uint8Array {
return this.bytes
}
}
/*
* @brief: Collection of Bytes objects, mapping bidirectionally
*/
export class BytesLookup {
constructor(types: Record<string, number>, readonly ordinalWidth: number) {
Object.entries(types).forEach(([k, v]) => {
this.add(k, v)
})
}
/**
* Add a new name value pair to the BytesLookup.
*
* @param name - A human readable name for the field.
* @param value - The numeric value for the field.
* @throws if the name or value already exist in the lookup because it's unclear how to decode.
*/
add(name: string, value: number): void {
if (this[name]) {
throw new SyntaxError(
`Attempted to add a value with a duplicate name "${name}". This is not allowed because it is unclear how to decode.`,
)
}
if (this[value.toString()]) {
throw new SyntaxError(
`Attempted to add a duplicate value under a different name (Given name: "${name}" and previous name: "${
this[value.toString()]
}. This is not allowed because it is unclear how to decode.\nGiven value: ${value.toString()}`,
)
}
this[name] = new Bytes(name, value, this.ordinalWidth)
this[value.toString()] = this[name]
}
from(value: Bytes | string): Bytes {
return value instanceof Bytes ? value : (this[value] as Bytes)
}
fromParser(parser: BinaryParser): Bytes {
return this.from(parser.readUIntN(this.ordinalWidth).toString())
}
}

View File

@@ -0,0 +1,4 @@
export const TYPE_WIDTH = 2
export const LEDGER_ENTRY_WIDTH = 2
export const TRANSACTION_TYPE_WIDTH = 2
export const TRANSACTION_RESULT_WIDTH = 1

View File

@@ -44,11 +44,16 @@
"NegativeUNL": 78,
"NFTokenPage": 80,
"NFTokenOffer": 55,
"URIToken": 85,
"Any": -3,
"Child": -2,
"Nickname": 110,
"Contract": 99,
"GeneratorMap": 103
"GeneratorMap": 103,
"Hook": 72,
"HookState": 118,
"HookDefinition": 68,
"EmittedTxn": 69
},
"FIELDS": [
[
@@ -321,6 +326,16 @@
"type": "UInt16"
}
],
[
"NetworkID",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Flags",
{
@@ -761,6 +776,16 @@
"type": "UInt32"
}
],
[
"LockCount",
{
"nth": 47,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"IndexNext",
{
@@ -891,16 +916,6 @@
"type": "UInt64"
}
],
[
"HookOn",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"HookInstructionCount",
{
@@ -1151,6 +1166,16 @@
"type": "Hash256"
}
],
[
"HookOn",
{
"nth": 20,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"Digest",
{
@@ -1281,6 +1306,36 @@
"type": "Hash256"
}
],
[
"OfferID",
{
"nth": 34,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"EscrowID",
{
"nth": 35,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"URITokenID",
{
"nth": 36,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"Amount",
{
@@ -1421,6 +1476,26 @@
"type": "Amount"
}
],
[
"HookCallbackFee",
{
"nth": 20,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"LockedBalance",
{
"nth": 21,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"PublicKey",
{
@@ -1661,6 +1736,16 @@
"type": "Blob"
}
],
[
"Blob",
{
"nth": 26,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"Account",
{
@@ -1801,6 +1886,16 @@
"type": "Vector256"
}
],
[
"HookNamespaces",
{
"nth": 5,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Vector256"
}
],
[
"Paths",
{
@@ -2176,6 +2271,10 @@
"telCAN_NOT_QUEUE_BLOCKED": -389,
"telCAN_NOT_QUEUE_FEE": -388,
"telCAN_NOT_QUEUE_FULL": -387,
"telWRONG_NETWORK": -386,
"telREQUIRES_NETWORK_ID": -385,
"telNETWORK_ID_MAKES_TX_NON_CANONICAL": -384,
"telNON_LOCAL_EMITTED_TXN": -383,
"temMALFORMED": -299,
"temBAD_AMOUNT": -298,
@@ -2215,6 +2314,16 @@
"temUNKNOWN": -264,
"temSEQ_AND_TICKET": -263,
"temBAD_NFTOKEN_TRANSFER_FEE": -262,
"temAMM_BAD_TOKENS": -261,
"temEQUAL_DOOR_ACCOUNTS": -260,
"temBAD_XCHAIN_PROOF": -259,
"temSIDECHAIN_BAD_ISSUES": -258,
"temSIDECHAIN_NONDOOR_OWNER": -257,
"temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT": -256,
"temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT": -255,
"temXCHAIN_TOO_MANY_ATTESTATIONS": -254,
"temHOOK_DATA_TOO_LARGE": -253,
"temHOOK_REJECTED": -252,
"tefFAILURE": -199,
"tefALREADY": -198,
@@ -2250,6 +2359,7 @@
"terNO_RIPPLE": -90,
"terQUEUED": -89,
"terPRE_TICKET": -88,
"terNO_HOOK": -87,
"tesSUCCESS": 0,
@@ -2291,6 +2401,7 @@
"tecKILLED": 150,
"tecHAS_OBLIGATIONS": 151,
"tecTOO_SOON": 152,
"tecHOOK_REJECTED": 153,
"tecMAX_SEQUENCE_REACHED": 154,
"tecNO_SUITABLE_NFTOKEN_PAGE": 155,
"tecNFTOKEN_BUY_SELL_MISMATCH": 156,
@@ -2298,7 +2409,32 @@
"tecCANT_ACCEPT_OWN_NFTOKEN_OFFER": 158,
"tecINSUFFICIENT_FUNDS": 159,
"tecOBJECT_NOT_FOUND": 160,
"tecINSUFFICIENT_PAYMENT": 161
"tecINSUFFICIENT_PAYMENT": 161,
"tecAMM_UNFUNDED": 162,
"tecAMM_BALANCE": 163,
"tecAMM_FAILED_DEPOSIT": 164,
"tecAMM_FAILED_WITHDRAW": 165,
"tecAMM_INVALID_TOKENS": 166,
"tecAMM_FAILED_BID": 167,
"tecAMM_FAILED_VOTE": 168,
"tecREQUIRES_FLAG": 169,
"tecPRECISION_LOSS": 170,
"tecBAD_XCHAIN_TRANSFER_ISSUE": 171,
"tecXCHAIN_NO_CLAIM_ID": 172,
"tecXCHAIN_BAD_CLAIM_ID": 173,
"tecXCHAIN_CLAIM_NO_QUORUM": 174,
"tecXCHAIN_PROOF_UNKNOWN_KEY": 175,
"tecXCHAIN_CREATE_ACCOUNT_NONXRP_ISSUE": 176,
"tecXCHAIN_WRONG_CHAIN": 177,
"tecXCHAIN_REWARD_MISMATCH": 178,
"tecXCHAIN_NO_SIGNERS_LIST": 179,
"tecXCHAIN_SENDING_ACCOUNT_MISMATCH": 180,
"tecXCHAIN_INSUFF_CREATE_AMOUNT": 181,
"tecXCHAIN_ACCOUNT_CREATE_PAST": 182,
"tecXCHAIN_ACCOUNT_CREATE_TOO_MANY": 183,
"tecXCHAIN_PAYMENT_FAILED": 184,
"tecXCHAIN_SELF_COMMIT": 185,
"tecXCHAIN_BAD_PUBLIC_KEY_ACCOUNT_PAIR": 186
},
"TRANSACTION_TYPES": {
"Invalid": -1,
@@ -2330,8 +2466,15 @@
"NFTokenCreateOffer": 27,
"NFTokenCancelOffer": 28,
"NFTokenAcceptOffer": 29,
"URITokenMint": 45,
"URITokenBurn": 46,
"URITokenBuy": 47,
"URITokenCreateSellOffer": 48,
"URITokenCancelSellOffer": 49,
"Invoke": 99,
"EnableAmendment": 100,
"SetFee": 101,
"UNLModify": 102
"UNLModify": 102,
"EmitFailure": 103
}
}

View File

@@ -0,0 +1,85 @@
import { Bytes } from './bytes'
import { SerializedType } from '../types/serialized-type'
import { TYPE_WIDTH } from './constants'
import { Buffer } from 'buffer/'
/**
* Encoding information for a rippled field, often used in transactions.
* 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.
*/
export interface FieldInfo {
nth: number
isVLEncoded: boolean
isSerialized: boolean
isSigningField: boolean
type: string
}
export interface FieldInstance {
readonly nth: number
readonly isVariableLengthEncoded: boolean
readonly isSerialized: boolean
readonly isSigningField: boolean
readonly type: Bytes
readonly ordinal: number
readonly name: string
readonly header: Buffer
readonly associatedType: typeof SerializedType
}
/*
* @brief: Serialize a field based on type_code and Field.nth
*/
function fieldHeader(type: number, nth: number): Buffer {
const header: Array<number> = []
if (type < 16) {
if (nth < 16) {
header.push((type << 4) | nth)
} else {
header.push(type << 4, nth)
}
} else if (nth < 16) {
header.push(nth, type)
} else {
header.push(0, type, nth)
}
return Buffer.from(header)
}
function buildField(
[name, info]: [string, FieldInfo],
typeOrdinal: number,
): FieldInstance {
const field = fieldHeader(typeOrdinal, info.nth)
return {
name: name,
nth: info.nth,
isVariableLengthEncoded: info.isVLEncoded,
isSerialized: info.isSerialized,
isSigningField: info.isSigningField,
ordinal: (typeOrdinal << 16) | info.nth,
type: new Bytes(info.type, typeOrdinal, TYPE_WIDTH),
header: field,
associatedType: SerializedType, // For later assignment in ./types/index.js or Definitions.updateAll(...)
}
}
/*
* @brief: The collection of all fields as defined in definitions.json
*/
export class FieldLookup {
constructor(
fields: Array<[string, FieldInfo]>,
types: Record<string, number>,
) {
fields.forEach(([name, field_info]) => {
const typeOrdinal = types[field_info.type]
this[name] = buildField([name, field_info], typeOrdinal)
this[this[name].ordinal.toString()] = this[name]
})
}
fromString(value: string): FieldInstance {
return this[value] as FieldInstance
}
}

View File

@@ -1,164 +1,36 @@
import * as enums from './definitions.json'
import { SerializedType } from '../types/serialized-type'
import { Buffer } from 'buffer/'
import { BytesList } from '../binary'
import {
XrplDefinitionsBase,
FieldInstance,
Bytes,
} from './xrpl-definitions-base'
/**
* By default, coreTypes from the `types` folder is where known type definitions are initialized to avoid import cycles.
*/
const DEFAULT_DEFINITIONS = new XrplDefinitionsBase(enums, {})
const Type = DEFAULT_DEFINITIONS.type
const LedgerEntryType = DEFAULT_DEFINITIONS.ledgerEntryType
const TransactionType = DEFAULT_DEFINITIONS.transactionType
const TransactionResult = DEFAULT_DEFINITIONS.transactionResult
const Field = DEFAULT_DEFINITIONS.field
/*
* @brief: All valid transaction types
*/
export const TRANSACTION_TYPES = Object.entries(enums.TRANSACTION_TYPES)
.filter(([_key, value]) => value >= 0)
.map(([key, _value]) => key)
const TYPE_WIDTH = 2
const LEDGER_ENTRY_WIDTH = 2
const TRANSACTION_TYPE_WIDTH = 2
const TRANSACTION_RESULT_WIDTH = 1
/*
* @brief: Serialize a field based on type_code and Field.nth
*/
function fieldHeader(type: number, nth: number): Buffer {
const header: Array<number> = []
if (type < 16) {
if (nth < 16) {
header.push((type << 4) | nth)
} else {
header.push(type << 4, nth)
}
} else if (nth < 16) {
header.push(nth, type)
} else {
header.push(0, type, nth)
}
return Buffer.from(header)
}
/*
* @brief: Bytes, name, and ordinal representing one type, ledger_type, transaction type, or result
*/
export class Bytes {
readonly bytes: Buffer
constructor(
readonly name: string,
readonly ordinal: number,
readonly ordinalWidth: number,
) {
this.bytes = Buffer.alloc(ordinalWidth)
for (let i = 0; i < ordinalWidth; i++) {
this.bytes[ordinalWidth - i - 1] = (ordinal >>> (i * 8)) & 0xff
}
}
toJSON(): string {
return this.name
}
toBytesSink(sink: BytesList): void {
sink.put(this.bytes)
}
toBytes(): Uint8Array {
return this.bytes
}
}
/*
* @brief: Collection of Bytes objects, mapping bidirectionally
*/
class BytesLookup {
constructor(types: Record<string, number>, readonly ordinalWidth: number) {
Object.entries(types).forEach(([k, v]) => {
this[k] = new Bytes(k, v, ordinalWidth)
this[v.toString()] = this[k]
})
}
from(value: Bytes | string): Bytes {
return value instanceof Bytes ? value : (this[value] as Bytes)
}
fromParser(parser): Bytes {
return this.from(parser.readUIntN(this.ordinalWidth).toString())
}
}
/*
* type FieldInfo is the type of the objects containing information about each field in definitions.json
*/
interface FieldInfo {
nth: number
isVLEncoded: boolean
isSerialized: boolean
isSigningField: boolean
type: string
}
interface FieldInstance {
readonly nth: number
readonly isVariableLengthEncoded: boolean
readonly isSerialized: boolean
readonly isSigningField: boolean
readonly type: Bytes
readonly ordinal: number
readonly name: string
readonly header: Buffer
readonly associatedType: typeof SerializedType
}
function buildField([name, info]: [string, FieldInfo]): FieldInstance {
const typeOrdinal = enums.TYPES[info.type]
const field = fieldHeader(typeOrdinal, info.nth)
return {
name: name,
nth: info.nth,
isVariableLengthEncoded: info.isVLEncoded,
isSerialized: info.isSerialized,
isSigningField: info.isSigningField,
ordinal: (typeOrdinal << 16) | info.nth,
type: new Bytes(info.type, typeOrdinal, TYPE_WIDTH),
header: field,
associatedType: SerializedType, // For later assignment in ./types/index.js
}
}
/*
* @brief: The collection of all fields as defined in definitions.json
*/
class FieldLookup {
constructor(fields: Array<[string, FieldInfo]>) {
fields.forEach(([k, v]) => {
this[k] = buildField([k, v])
this[this[k].ordinal.toString()] = this[k]
})
}
fromString(value: string): FieldInstance {
return this[value] as FieldInstance
}
}
const Type = new BytesLookup(enums.TYPES, TYPE_WIDTH)
const LedgerEntryType = new BytesLookup(
enums.LEDGER_ENTRY_TYPES,
LEDGER_ENTRY_WIDTH,
)
const TransactionType = new BytesLookup(
enums.TRANSACTION_TYPES,
TRANSACTION_TYPE_WIDTH,
)
const TransactionResult = new BytesLookup(
enums.TRANSACTION_RESULTS,
TRANSACTION_RESULT_WIDTH,
)
const Field = new FieldLookup(enums.FIELDS as Array<[string, FieldInfo]>)
const TRANSACTION_TYPES = DEFAULT_DEFINITIONS.transactionNames
const TRANSACTION_TYPE_MAP = DEFAULT_DEFINITIONS.transactionMap
export {
Bytes,
XrplDefinitionsBase,
DEFAULT_DEFINITIONS,
Field,
FieldInstance,
Type,
LedgerEntryType,
TransactionResult,
TransactionType,
TRANSACTION_TYPES,
TRANSACTION_TYPE_MAP,
}

View File

@@ -0,0 +1,123 @@
import { SerializedType } from '../types/serialized-type'
import { Bytes, BytesLookup } from './bytes'
import { FieldInfo, FieldLookup, FieldInstance } from './field'
import {
TYPE_WIDTH,
LEDGER_ENTRY_WIDTH,
TRANSACTION_TYPE_WIDTH,
TRANSACTION_RESULT_WIDTH,
} from './constants'
interface DefinitionsData {
TYPES: Record<string, number>
LEDGER_ENTRY_TYPES: Record<string, number>
FIELDS: (string | FieldInfo)[][]
TRANSACTION_RESULTS: Record<string, number>
TRANSACTION_TYPES: Record<string, number>
}
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* XrplDefinitions should be instantiated instead of this class.
*/
class XrplDefinitionsBase {
// A collection of fields that can be included in transactions
field: FieldLookup
// A collection of ids corresponding to types of ledger objects
ledgerEntryType: BytesLookup
// A collection of type flags used to determine how to serialize a field's data
type: BytesLookup
// Errors and result codes for transactions
transactionResult: BytesLookup
// Defined transactions that can be submitted to the ledger
transactionType: BytesLookup
// Valid transaction names
transactionNames: string[]
// Valid transaction names
transactionMap: Record<string, number>
// Maps serializable types to their TypeScript class implementation
dataTypes: Record<string, typeof SerializedType>
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param types - A list of type objects with the same name as the fields defined.
* You can use the coreTypes object if you are not adding new types.
*/
constructor(
enums: DefinitionsData,
types: Record<string, typeof SerializedType>,
) {
this.type = new BytesLookup(enums.TYPES, TYPE_WIDTH)
this.ledgerEntryType = new BytesLookup(
enums.LEDGER_ENTRY_TYPES,
LEDGER_ENTRY_WIDTH,
)
this.transactionType = new BytesLookup(
enums.TRANSACTION_TYPES,
TRANSACTION_TYPE_WIDTH,
)
this.transactionResult = new BytesLookup(
enums.TRANSACTION_RESULTS,
TRANSACTION_RESULT_WIDTH,
)
this.field = new FieldLookup(
enums.FIELDS as Array<[string, FieldInfo]>,
enums.TYPES,
)
this.transactionNames = Object.entries(enums.TRANSACTION_TYPES)
.filter(([_key, value]) => value >= 0)
.map(([key, _value]) => key)
const ignoreList = ['EnableAmendment', 'SetFee', 'UNLModify', 'EmitFailure']
this.transactionMap = Object.assign(
{},
...Object.entries(enums.TRANSACTION_TYPES)
.filter(([_key, _value]) => _value >= 0 || ignoreList.includes(_key))
.map(([key, value]) => ({ [key]: value })),
)
this.dataTypes = {} // Filled in via associateTypes
this.associateTypes(types)
}
/**
* Associates each Field to a corresponding class that TypeScript can recognize.
*
* @param types a list of type objects with the same name as the fields defined.
* Defaults to xrpl.js's core type definitions.
*/
public associateTypes(types: Record<string, typeof SerializedType>): void {
// Overwrite any existing type definitions with the given types
this.dataTypes = Object.assign({}, this.dataTypes, types)
Object.values(this.field).forEach((field) => {
field.associatedType = this.dataTypes[field.type.name]
})
this.field['TransactionType'].associatedType = this.transactionType
this.field['TransactionResult'].associatedType = this.transactionResult
this.field['LedgerEntryType'].associatedType = this.ledgerEntryType
}
public getAssociatedTypes(): Record<string, typeof SerializedType> {
return this.dataTypes
}
}
export {
DefinitionsData,
XrplDefinitionsBase,
FieldLookup,
FieldInfo,
FieldInstance,
Bytes,
BytesLookup,
}

View File

@@ -0,0 +1,32 @@
import {
type DefinitionsData,
XrplDefinitionsBase,
} from './xrpl-definitions-base'
import { coreTypes } from '../types'
import { SerializedType } from '../types/serialized-type'
/**
* Stores the various types and fields for rippled to be used to encode/decode information later on.
* Should be used instead of XrplDefinitionsBase since this defines default `types` for serializing/deserializing
* ledger data.
*/
export class XrplDefinitions extends XrplDefinitionsBase {
/**
* Present rippled types in a typed and updatable format.
* For an example of the input format see `definitions.json`
* To generate a new definitions file from rippled source code, use this tool: https://github.com/RichardAH/xrpl-codec-gen
*
* See the definitions.test.js file for examples of how to create your own updated definitions.json.
*
* @param enums - A json encoding of the core types, transaction types, transaction results, transaction names, and fields.
* @param additionalTypes - A list of SerializedType objects with the same name as the fields defined.
* These types will be included in addition to the coreTypes used on mainnet.
*/
constructor(
enums: DefinitionsData,
additionalTypes?: Record<string, typeof SerializedType>,
) {
const types = Object.assign({}, coreTypes, additionalTypes)
super(enums, types)
}
}

View File

@@ -1,9 +1,16 @@
import * as assert from 'assert'
import { quality, binary } from './coretypes'
import { quality, binary, HashPrefix } from './coretypes'
import { decodeLedgerData } from './ledger-hashes'
import { ClaimObject } from './binary'
import { JsonObject } from './types/serialized-type'
import { TRANSACTION_TYPES } from './enums'
import {
XrplDefinitionsBase,
TRANSACTION_TYPES,
TRANSACTION_TYPE_MAP,
DEFAULT_DEFINITIONS,
} from './enums'
import { XrplDefinitions } from './enums/xrpl-definitions'
import { coreTypes } from './types'
const {
signingData,
@@ -17,22 +24,25 @@ const {
* Decode a transaction
*
* @param binary hex-string of the encoded transaction
* @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns the JSON representation of the transaction
*/
function decode(binary: string): JsonObject {
function decode(binary: string, definitions?: XrplDefinitionsBase): JsonObject {
assert.ok(typeof binary === 'string', 'binary must be a hex string')
return binaryToJSON(binary)
return binaryToJSON(binary, definitions)
}
/**
* Encode a transaction
*
* @param json The JSON representation of a transaction
* @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
*
* @returns A hex-string of the encoded transaction
*/
function encode(json: object): string {
function encode(json: object, definitions?: XrplDefinitionsBase): string {
assert.ok(typeof json === 'object')
return serializeObject(json as JsonObject)
return serializeObject(json as JsonObject, { definitions })
.toString('hex')
.toUpperCase()
}
@@ -42,11 +52,17 @@ function encode(json: object): string {
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns a hex string of the encoded transaction
*/
function encodeForSigning(json: object): string {
function encodeForSigning(
json: object,
definitions?: XrplDefinitionsBase,
): string {
assert.ok(typeof json === 'object')
return signingData(json as JsonObject)
return signingData(json as JsonObject, HashPrefix.transactionSig, {
definitions,
})
.toString('hex')
.toUpperCase()
}
@@ -56,6 +72,7 @@ function encodeForSigning(json: object): string {
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns a hex string of the encoded transaction
*/
function encodeForSigningClaim(json: object): string {
@@ -70,12 +87,18 @@ function encodeForSigningClaim(json: object): string {
*
* @param json JSON object representing the transaction
* @param signer string representing the account to sign the transaction with
* @param definitions Custom rippled types to use instead of the default. Used for sidechains and amendments.
* @returns a hex string of the encoded transaction
*/
function encodeForMultisigning(json: object, signer: string): string {
function encodeForMultisigning(
json: object,
signer: string,
definitions?: XrplDefinitionsBase,
): string {
assert.ok(typeof json === 'object')
assert.equal(json['SigningPubKey'], '')
return multiSigningData(json as JsonObject, signer)
const definitionsOpt = definitions ? { definitions } : undefined
return multiSigningData(json as JsonObject, signer, definitionsOpt)
.toString('hex')
.toUpperCase()
}
@@ -112,4 +135,9 @@ export {
decodeQuality,
decodeLedgerData,
TRANSACTION_TYPES,
TRANSACTION_TYPE_MAP,
XrplDefinitions,
XrplDefinitionsBase,
DEFAULT_DEFINITIONS,
coreTypes,
}

View File

@@ -11,6 +11,7 @@ import { UInt8 } from './types/uint-8'
import { BinaryParser } from './serdes/binary-parser'
import { JsonObject } from './types/serialized-type'
import bigInt = require('big-integer')
import { XrplDefinitionsBase } from './enums'
/**
* Computes the hash of a list of objects
@@ -160,11 +161,16 @@ function ledgerHash(header: ledgerObject): Hash256 {
* Decodes a serialized ledger header
*
* @param binary A serialized ledger header
* @param definitions Type definitions to parse the ledger objects.
* Used if there are non-default ledger objects to decode.
* @returns A JSON object describing a ledger header
*/
function decodeLedgerData(binary: string): object {
function decodeLedgerData(
binary: string,
definitions?: XrplDefinitionsBase,
): object {
assert.ok(typeof binary === 'string', 'binary must be a hex string')
const parser = new BinaryParser(binary)
const parser = new BinaryParser(binary, definitions)
return {
ledger_index: parser.readUInt32(),
total_coins: parser.readType(UInt64).valueOf().toString(),

View File

@@ -1,6 +1,10 @@
import * as assert from 'assert'
import { Field, FieldInstance } from '../enums'
import { SerializedType } from '../types/serialized-type'
import {
XrplDefinitionsBase,
DEFAULT_DEFINITIONS,
FieldInstance,
} from '../enums'
import { type SerializedType } from '../types/serialized-type'
import { Buffer } from 'buffer/'
/**
@@ -8,14 +12,21 @@ import { Buffer } from 'buffer/'
*/
class BinaryParser {
private bytes: Buffer
definitions: XrplDefinitionsBase
/**
* Initialize bytes to a hex string
*
* @param hexBytes a hex string
* @param definitions Rippled definitions used to parse the values of transaction types and such.
* Can be customized for sidechains and amendments.
*/
constructor(hexBytes: string) {
constructor(
hexBytes: string,
definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,
) {
this.bytes = Buffer.from(hexBytes, 'hex')
this.definitions = definitions
}
/**
@@ -146,7 +157,7 @@ class BinaryParser {
* @return The field represented by the bytes at the head of the BinaryParser
*/
readField(): FieldInstance {
return Field.fromString(this.readFieldOrdinal().toString())
return this.definitions.field.fromString(this.readFieldOrdinal().toString())
}
/**

View File

@@ -1,6 +1,6 @@
import * as assert from 'assert'
import { FieldInstance } from '../enums'
import { SerializedType } from '../types/serialized-type'
import { type SerializedType } from '../types/serialized-type'
import { Buffer } from 'buffer/'
/**

View File

@@ -130,7 +130,7 @@ class ShaMapInner extends ShaMapNode {
*/
hash(): Hash256 {
if (this.empty()) {
return coreTypes.Hash256.ZERO_256
return (coreTypes.Hash256 as typeof Hash256).ZERO_256
}
const hash = Sha512Half.put(this.hashPrefix())
this.toBytesSink(hash)
@@ -145,7 +145,9 @@ class ShaMapInner extends ShaMapNode {
toBytesSink(list: BytesList): void {
for (let i = 0; i < this.branches.length; i++) {
const branch = this.branches[i]
const hash = branch ? branch.hash() : coreTypes.Hash256.ZERO_256
const hash = branch
? branch.hash()
: (coreTypes.Hash256 as typeof Hash256).ZERO_256
hash.toBytesSink(list)
}
}

View File

@@ -1,9 +1,3 @@
import {
Field,
TransactionResult,
TransactionType,
LedgerEntryType,
} from '../enums'
import { AccountID } from './account-id'
import { Amount } from './amount'
import { Blob } from './blob'
@@ -11,6 +5,7 @@ import { Currency } from './currency'
import { Hash128 } from './hash-128'
import { Hash160 } from './hash-160'
import { Hash256 } from './hash-256'
import { Issue } from './issue'
import { PathSet } from './path-set'
import { STArray } from './st-array'
import { STObject } from './st-object'
@@ -19,8 +14,35 @@ import { UInt32 } from './uint-32'
import { UInt64 } from './uint-64'
import { UInt8 } from './uint-8'
import { Vector256 } from './vector-256'
import { type SerializedType } from './serialized-type'
import { DEFAULT_DEFINITIONS } from '../enums'
const coreTypes = {
const coreTypes: Record<string, typeof SerializedType> = {
AccountID,
Amount,
Blob,
Currency,
Hash128,
Hash160,
Hash256,
Issue,
PathSet,
STArray,
STObject,
UInt8,
UInt16,
UInt32,
UInt64,
Vector256,
}
// Ensures that the DEFAULT_DEFINITIONS object connects these types to fields for serializing/deserializing
// This is done here instead of in enums/index.ts to avoid a circular dependency
// because some of the above types depend on BinarySerailizer which depends on enums/index.ts.
DEFAULT_DEFINITIONS.associateTypes(coreTypes)
export {
coreTypes,
AccountID,
Amount,
Blob,
@@ -37,13 +59,3 @@ const coreTypes = {
UInt64,
Vector256,
}
Object.values(Field).forEach((field) => {
field.associatedType = coreTypes[field.type.name]
})
Field['TransactionType'].associatedType = TransactionType
Field['TransactionResult'].associatedType = TransactionResult
Field['LedgerEntryType'].associatedType = LedgerEntryType
export { coreTypes }

View File

@@ -0,0 +1,96 @@
import { BinaryParser } from '../serdes/binary-parser'
import { AccountID } from './account-id'
import { Currency } from './currency'
import { JsonObject, SerializedType } from './serialized-type'
import { Buffer } from 'buffer/'
/**
* Interface for JSON objects that represent amounts
*/
interface IssueObject extends JsonObject {
currency: string
issuer?: string
}
/**
* Type guard for AmountObject
*/
function isIssueObject(arg): arg is IssueObject {
const keys = Object.keys(arg).sort()
if (keys.length === 1) {
return keys[0] === 'currency'
}
return keys.length === 2 && keys[0] === 'currency' && keys[1] === 'issuer'
}
/**
* Class for serializing/Deserializing Amounts
*/
class Issue extends SerializedType {
static readonly ZERO_ISSUED_CURRENCY: Issue = new Issue(Buffer.alloc(20))
constructor(bytes: Buffer) {
super(bytes ?? Issue.ZERO_ISSUED_CURRENCY.bytes)
}
/**
* Construct an amount from an IOU or string amount
*
* @param value An Amount, object representing an IOU, or a string
* representing an integer amount
* @returns An Amount object
*/
static from<T extends Issue | IssueObject>(value: T): Issue {
if (value instanceof Issue) {
return value
}
if (isIssueObject(value)) {
const currency = Currency.from(value.currency).toBytes()
if (value.issuer == null) {
return new Issue(currency)
}
const issuer = AccountID.from(value.issuer).toBytes()
return new Issue(Buffer.concat([currency, issuer]))
}
throw new Error('Invalid type to construct an Amount')
}
/**
* Read an amount from a BinaryParser
*
* @param parser BinaryParser to read the Amount from
* @returns An Amount object
*/
static fromParser(parser: BinaryParser): Issue {
const currency = parser.read(20)
if (new Currency(currency).toJSON() === 'XRP') {
return new Issue(currency)
}
const currencyAndIssuer = [currency, parser.read(20)]
return new Issue(Buffer.concat(currencyAndIssuer))
}
/**
* Get the JSON representation of this Amount
*
* @returns the JSON interpretation of this.bytes
*/
toJSON(): IssueObject {
const parser = new BinaryParser(this.toString())
const currency = Currency.fromParser(parser) as Currency
if (currency.toJSON() === 'XRP') {
return { currency: currency.toJSON() }
}
const issuer = AccountID.fromParser(parser) as AccountID
return {
currency: currency.toJSON(),
issuer: issuer.toJSON(),
}
}
}
export { Issue, IssueObject }

View File

@@ -1,4 +1,9 @@
import { Field, FieldInstance, Bytes } from '../enums'
import {
DEFAULT_DEFINITIONS,
FieldInstance,
Bytes,
XrplDefinitionsBase,
} from '../enums'
import { SerializedType, JsonObject } from './serialized-type'
import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec'
import { BinaryParser } from '../serdes/binary-parser'
@@ -83,11 +88,13 @@ class STObject extends SerializedType {
*
* @param value An object to include
* @param filter optional, denote which field to include in serialized object
* @param definitions optional, types and values to use to encode/decode a transaction
* @returns a STObject object
*/
static from<T extends STObject | JsonObject>(
value: T,
filter?: (...any) => boolean,
definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS,
): STObject {
if (value instanceof STObject) {
return value
@@ -108,7 +115,7 @@ class STObject extends SerializedType {
}, {})
let sorted = Object.keys(xAddressDecoded)
.map((f: string): FieldInstance => Field[f] as FieldInstance)
.map((f: string): FieldInstance => definitions.field[f] as FieldInstance)
.filter(
(f: FieldInstance): boolean =>
f !== undefined &&
@@ -155,11 +162,12 @@ class STObject extends SerializedType {
/**
* Get the JSON interpretation of this.bytes
*
* @param definitions rippled definitions used to parse the values of transaction types and such.
* Can be customized for sidechains and amendments.
* @returns a JSON object
*/
toJSON(): JsonObject {
const objectParser = new BinaryParser(this.toString())
toJSON(definitions?: XrplDefinitionsBase): JsonObject {
const objectParser = new BinaryParser(this.toString(), definitions)
const accumulator = {}
while (!objectParser.end()) {

View File

@@ -0,0 +1,100 @@
const { encode, decode, XrplDefinitions } = require('../src')
const normalDefinitionsJson = require('../src/enums/definitions.json')
const { UInt32 } = require('../dist/types/uint-32')
const txJson = {
Account: 'r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ',
Amount: '1000',
Destination: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
Fee: '10',
Flags: 0,
Sequence: 1,
TransactionType: 'Payment',
}
describe('encode and decode using new types as a parameter', function () {
test('can encode and decode a new TransactionType', function () {
const tx = { ...txJson, TransactionType: 'NewTestTransaction' }
// Before updating the types, this should not be encodable
expect(() => encode(tx)).toThrow()
// Normally this would be generated directly from rippled with something like `server_definitions`.
// Added here to make it easier to see what is actually changing in the definitions.json file.
const definitions = JSON.parse(JSON.stringify(normalDefinitionsJson))
definitions.TRANSACTION_TYPES['NewTestTransaction'] = 30
const newDefs = new XrplDefinitions(definitions)
const encoded = encode(tx, newDefs)
expect(() => decode(encoded)).toThrow()
const decoded = decode(encoded, newDefs)
expect(decoded).toStrictEqual(tx)
})
test('can encode and decode a new Field', function () {
const tx = { ...txJson, NewFieldDefinition: 10 }
// Before updating the types, undefined fields will be ignored on encode
expect(decode(encode(tx))).not.toStrictEqual(tx)
// Normally this would be generated directly from rippled with something like `server_definitions`.
// Added here to make it easier to see what is actually changing in the definitions.json file.
const definitions = JSON.parse(JSON.stringify(normalDefinitionsJson))
definitions.FIELDS.push([
'NewFieldDefinition',
{
nth: 100,
isVLEncoded: false,
isSerialized: true,
isSigningField: true,
type: 'UInt32',
},
])
const newDefs = new XrplDefinitions(definitions)
const encoded = encode(tx, newDefs)
expect(() => decode(encoded)).toThrow()
const decoded = decode(encoded, newDefs)
expect(decoded).toStrictEqual(tx)
})
test('can encode and decode a new Type', function () {
const tx = {
...txJson,
TestField: 10, // Should work the same as a UInt32
}
// Normally this would be generated directly from rippled with something like `server_definitions`.
// Added here to make it easier to see what is actually changing in the definitions.json file.
const definitions = JSON.parse(JSON.stringify(normalDefinitionsJson))
definitions.TYPES.NewType = 24
definitions.FIELDS.push([
'TestField',
{
nth: 100,
isVLEncoded: true,
isSerialized: true,
isSigningField: true,
type: 'NewType',
},
])
// Test that before updating the types this tx fails to decode correctly. Note that undefined fields are ignored on encode.
expect(decode(encode(tx))).not.toStrictEqual(tx)
class NewType extends UInt32 {
// Should be the same as UInt32
}
const extendedCoreTypes = { NewType }
const newDefs = new XrplDefinitions(definitions, extendedCoreTypes)
const encoded = encode(tx, newDefs)
expect(() => decode(encoded)).toThrow()
const decoded = decode(encoded, newDefs)
expect(decoded).toStrictEqual(tx)
})
})

View File

@@ -4448,6 +4448,213 @@
"Flags": 0,
"Sequence": 62
}
},
{
"binary": "12002315000A220000000024000000026140000000000027106840000000000000016BD5838D7EA4C680000000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C7321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440913E39EC2BA0E5BC4C5DF1222B1AE9E76758F2B8FFEF1F056076147BB0ADC8117CD0296360DA08B3D48BE9EFC8693C03A253E0D9F166C19CA8D936F9E61A1100811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMCreate",
"TxnSignature": "913E39EC2BA0E5BC4C5DF1222B1AE9E76758F2B8FFEF1F056076147BB0ADC8117CD0296360DA08B3D48BE9EFC8693C03A253E0D9F166C19CA8D936F9E61A1100",
"Amount": "10000",
"Amount2": {
"currency": "ETH",
"issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9",
"value": "10000"
},
"TradingFee": 10,
"Fee": "1",
"Flags": 0,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0"
}
},
{
"binary": "120024220001000024000000026840000000000000016014D5438D7EA4C68000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0487321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D074409EEE8CF88C668B955E7EEAB1B4A1B059EDF4F51B7F1546810F87E3E48B09237F015C651E37FB40A979E00EA21361D4E18D7A33DB7DD23070CEEAB2648AB3BB0D811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMDeposit",
"TxnSignature": "9EEE8CF88C668B955E7EEAB1B4A1B059EDF4F51B7F1546810F87E3E48B09237F015C651E37FB40A979E00EA21361D4E18D7A33DB7DD23070CEEAB2648AB3BB0D",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"LPTokenOut": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "1000"},
"Fee": "1",
"Flags": 65536,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0"
}
},
{
"binary": "120024220008000024000000026140000000000003E86840000000000000017321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440BD18A6E2B10B451F61CFADC32B59A0243702DC5DAAE556D51CB9C79981D40C78101FFA9DE6163CFBDF6E7578DF02F2AE3B8A5AB60697E0746D65064D91E8F90A811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMDeposit",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"Fee": "1",
"Flags": 524288,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "BD18A6E2B10B451F61CFADC32B59A0243702DC5DAAE556D51CB9C79981D40C78101FFA9DE6163CFBDF6E7578DF02F2AE3B8A5AB60697E0746D65064D91E8F90A"
}
},
{
"binary": "120024220010000024000000026140000000000003E86840000000000000016BD511C37937E080000000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C7321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440E0B1AE32A0F731BF0CEF0D019295BD7F35B22F11A5962F65FA99EE4D38993B14B53DB11C15E36D756E282812E9015D38A6F225940A157693F43F9B795C59950F811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMDeposit",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"Amount2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9", "value": "500"},
"Fee": "1",
"Flags": 1048576,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "E0B1AE32A0F731BF0CEF0D019295BD7F35B22F11A5962F65FA99EE4D38993B14B53DB11C15E36D756E282812E9015D38A6F225940A157693F43F9B795C59950F"
}
},
{
"binary": "120024220020000024000000026140000000000003E86840000000000000016014D5438D7EA4C68000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0487321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440452BC59F9EE12C224EC983EFDF580F20C4A50E897105FD1FB13520D9753CFB02BD210599181574DF6AD0DB6A42C1EA48D9E48FC3D11B9008E4C76FBB163D5B00811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMDeposit",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"LPTokenOut": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "1000"},
"Fee": "1",
"Flags": 2097152,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "452BC59F9EE12C224EC983EFDF580F20C4A50E897105FD1FB13520D9753CFB02BD210599181574DF6AD0DB6A42C1EA48D9E48FC3D11B9008E4C76FBB163D5B00"
}
},
{
"binary": "120024220040000024000000026140000000000003E8684000000000000001601640000000000000197321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440DD6685DC586FAA6AD2D50D785900122EB147D4AC09A55D7080267A9B38180F87CEC44B823359FC3F0AC0104D47B53FFC6B80415664C3C4582672420A0100F70C811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMDeposit",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"EPrice": "25",
"Fee": "1",
"Flags": 4194304,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "DD6685DC586FAA6AD2D50D785900122EB147D4AC09A55D7080267A9B38180F87CEC44B823359FC3F0AC0104D47B53FFC6B80415664C3C4582672420A0100F70C"
}
},
{
"binary": "120025220001000024000000026840000000000000016015D5438D7EA4C68000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0487321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0744066944797E9F03808C9A00AAEFF786AD74FEB2E64B51A9601E89ABA820AAA15927C2E961A9CCA22C4B0D2A2B55E342BD6E297BD765B6F4D3FDCA578A3416BB505811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMWithdraw",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"LPTokenIn": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "1000"},
"Fee": "1",
"Flags": 65536,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "66944797E9F03808C9A00AAEFF786AD74FEB2E64B51A9601E89ABA820AAA15927C2E961A9CCA22C4B0D2A2B55E342BD6E297BD765B6F4D3FDCA578A3416BB505"
}
},
{
"binary": "120025220008000024000000026140000000000003E86840000000000000017321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440E30397CE7E99B13D35FFB5C66725B17F4F103675E10293C7B1D63C1BE3FA81B884BD3FBD31B52F6B811F99C5FBB5102D170EC379C268DF80DABF04E7F2DD4F0C811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMWithdraw",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"Fee": "1",
"Flags": 524288,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "E30397CE7E99B13D35FFB5C66725B17F4F103675E10293C7B1D63C1BE3FA81B884BD3FBD31B52F6B811F99C5FBB5102D170EC379C268DF80DABF04E7F2DD4F0C"
}
},
{
"binary": "120025220010000024000000026140000000000003E86840000000000000016BD511C37937E080000000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C7321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D07440C0818312B269A4EF16C1C7EBBB74EFD1852A288BB214A714B8BE3B5F4B2F9CFDFF4F66C931B8434244A8016035B9EC9493B7CF5E0ACF4570A88DF808D79E4300811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMWithdraw",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"Amount2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9", "value": "500"},
"Fee": "1",
"Flags": 1048576,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "C0818312B269A4EF16C1C7EBBB74EFD1852A288BB214A714B8BE3B5F4B2F9CFDFF4F66C931B8434244A8016035B9EC9493B7CF5E0ACF4570A88DF808D79E4300"
}
},
{
"binary": "120025220020000024000000026140000000000003E86840000000000000016015D5438D7EA4C68000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0487321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0744073552B3DC7AE99DDF4E4FF0D60E6D0BE4688E3474D363603FA25DA6AD8BBA8F0E4E3EA82ADB2B57F5B9A6C379969E00095546DDA0E74FF3D0F0689351C2F8C06811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMWithdraw",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"LPTokenIn": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "1000"},
"Fee": "1",
"Flags": 2097152,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "73552B3DC7AE99DDF4E4FF0D60E6D0BE4688E3474D363603FA25DA6AD8BBA8F0E4E3EA82ADB2B57F5B9A6C379969E00095546DDA0E74FF3D0F0689351C2F8C06"
}
},
{
"binary": "120025220040000024000000026140000000000003E8684000000000000001601640000000000000197321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0744023BAFE5BFE58E7BF0B02B5875983D007C10796C8E62A190BF688EBE5D8A104DAD2DE7EDE995FE2E494883FD8140F38E22E3376A2F49C50EFCAA00C7499A4690E811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMWithdraw",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"Amount": "1000",
"EPrice": "25",
"Fee": "1",
"Flags": 4194304,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "23BAFE5BFE58E7BF0B02B5875983D007C10796C8E62A190BF688EBE5D8A104DAD2DE7EDE995FE2E494883FD8140F38E22E3376A2F49C50EFCAA00C7499A4690E"
}
},
{
"binary": "120027220000000024000000026840000000000000016CD4C8E1BC9BF04000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0486DD4CC6F3B40B6C000B3813FCAB4EE68B3D0D735D6849465A9113EE048B3813FCAB4EE68B3D0D735D6849465A9113EE0487321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D074406B2A1548E6DC14681356C27CCBE7072CAB2AD8C72D0D7A045916FB0E0DBE6BF71A429CC519E9200172829D3EEF79100899D3A8710C1C3C1A2B664FD64086AD0A811462D4D845D20B4F09CFEA8BB4C01063D99FC9673EF01AE01C81149A91957F8F16BC57F3F200CD8C98375BF1791586E1F10318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMBid",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"AuthAccounts": [{"AuthAccount": {"Account": "rEaHTti4HZsMBpxTAF4ncWxkcdqDh1h6P7"}}],
"BidMax": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "35"},
"BidMin": {"currency": "B3813FCAB4EE68B3D0D735D6849465A9113EE048", "issuer": "rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg", "value": "25"},
"Fee": "1",
"Flags": 0,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "6B2A1548E6DC14681356C27CCBE7072CAB2AD8C72D0D7A045916FB0E0DBE6BF71A429CC519E9200172829D3EEF79100899D3A8710C1C3C1A2B664FD64086AD0A"
}
},
{
"binary": "1200261500EA220000000024000000026840000000000000017321ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0744072767CF9A0F5E9C9DA6BBB6E84905B0ECDF122D3E2D730843EFD377521E8E73664AD809D0A54E8C75CD1735ACB64E310BB49FDED10913FA150B8C006D4ACEC00811462D4D845D20B4F09CFEA8BB4C01063D99FC9673E0318000000000000000000000000000000000000000004180000000000000000000000004554480000000000FBEF9A3A2B814E807745FA3D9C32FFD155FA2E8C",
"json": {
"Account": "rwr2UWxNwoBdysPSiDDraTQjAQKZEeZAcV",
"TransactionType": "AMMVote",
"Asset": {"currency": "XRP"},
"Asset2": {"currency": "ETH", "issuer": "rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9"},
"TradingFee": 234,
"Fee": "1",
"Flags": 0,
"Sequence": 2,
"SigningPubKey": "ED8A00C1D29E762266576408B08D583B987673550655F930635678B436D5CDF7D0",
"TxnSignature": "72767CF9A0F5E9C9DA6BBB6E84905B0ECDF122D3E2D730843EFD377521E8E73664AD809D0A54E8C75CD1735ACB64E310BB49FDED10913FA150B8C006D4ACEC00"
}
}],
"ledgerData": [{
"binary": "01E91435016340767BF1C4A3EACEB081770D8ADE216C85445DD6FB002C6B5A2930F2DECE006DA18150CB18F6DD33F6F0990754C962A7CCE62F332FF9C13939B03B864117F0BDA86B6E9B4F873B5C3E520634D343EF5D9D9A4246643D64DAD278BA95DC0EAC6EB5350CF970D521276CDE21276CE60A00",

View File

@@ -4,6 +4,9 @@ const {
encodeForSigningClaim,
encodeForMultisigning,
} = require('../src')
const { XrplDefinitions } = require('../src/enums/xrpl-definitions')
const normalDefinitions = require('../src/enums/definitions.json')
const tx_json = {
Account: 'r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ',
@@ -67,6 +70,53 @@ describe('Signing data', function () {
)
})
test('can create single signing blobs with modified type', function () {
const customPaymentDefinitions = JSON.parse(
JSON.stringify(normalDefinitions),
)
customPaymentDefinitions.TRANSACTION_TYPES.Payment = 31
const newDefs = new XrplDefinitions(customPaymentDefinitions)
const actual = encodeForSigning(tx_json, newDefs)
expect(actual).toBe(
[
'53545800', // signingPrefix
// TransactionType
'12',
'001F',
// Flags
'22',
'80000000',
// Sequence
'24',
'00000001',
// Amount
'61',
// native amount
'40000000000003E8',
// Fee
'68',
// native amount
'400000000000000A',
// SigningPubKey
'73',
// VLLength
'21',
'ED5F5AC8B98974A3CA843326D9B88CEBD0560177B973EE0B149F782CFAA06DC66A',
// Account
'81',
// VLLength
'14',
'5B812C9D57731E27A2DA8B1830195F88EF32A3B6',
// Destination
'83',
// VLLength
'14',
'B5F762798A53D543A014CAF8B297CFF8F2F937E8',
].join(''),
)
})
test('can fail gracefully for invalid TransactionType', function () {
const invalidTransactionType = {
...tx_json,
@@ -78,7 +128,7 @@ describe('Signing data', function () {
test('can create multi signing blobs', function () {
const signingAccount = 'rJZdUusLDtY9NEsGea7ijqhVrXv98rYBYN'
const signingJson = Object.assign({}, tx_json, { SigningPubKey: '' })
const signingJson = { ...tx_json, SigningPubKey: '' }
const actual = encodeForMultisigning(signingJson, signingAccount)
expect(actual).toBe(
[
@@ -120,6 +170,58 @@ describe('Signing data', function () {
].join(''),
)
})
test('can create multi signing blobs with custom definitions', function () {
const customPaymentDefinitions = JSON.parse(
JSON.stringify(normalDefinitions),
)
customPaymentDefinitions.TRANSACTION_TYPES.Payment = 31
const newDefs = new XrplDefinitions(customPaymentDefinitions)
const signingAccount = 'rJZdUusLDtY9NEsGea7ijqhVrXv98rYBYN'
const signingJson = { ...tx_json, SigningPubKey: '' }
const actual = encodeForMultisigning(signingJson, signingAccount, newDefs)
expect(actual).toBe(
[
'534D5400', // signingPrefix
// TransactionType
'12',
'001F',
// Flags
'22',
'80000000',
// Sequence
'24',
'00000001',
// Amount
'61',
// native amount
'40000000000003E8',
// Fee
'68',
// native amount
'400000000000000A',
// SigningPubKey
'73',
// VLLength
'00',
// '',
// Account
'81',
// VLLength
'14',
'5B812C9D57731E27A2DA8B1830195F88EF32A3B6',
// Destination
'83',
// VLLength
'14',
'B5F762798A53D543A014CAF8B297CFF8F2F937E8',
// signingAccount suffix
'C0A5ABEF242802EFED4B041E8F2D4A8CC86AE3D1',
].join(''),
)
})
test('can create claim blob', function () {
const channel =
'43904CBFCDCEC530B4037871F86EE90BF799DF8D2E0EA564BC8A3F332E4F5FB1'

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-keypairs",
"version": "1.1.5",
"name": "@transia/ripple-keypairs",
"version": "1.1.6-tbeta.0",
"description": "Cryptographic key pairs for the XRP Ledger",
"scripts": {
"build": "tsc -b",
@@ -25,7 +25,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com:Transia-RnD/xrpl.js/tree/transia-beta"
},
"license": "ISC",
"prettier": "@xrplf/prettier-config",

View File

@@ -3,6 +3,12 @@
Subscribe to [the **xrpl-announce** mailing list](https://groups.google.com/g/xrpl-announce) for release announcements. We recommend that xrpl.js (ripple-lib) users stay up-to-date with the latest stable release.
## Unreleased
### Added
* Null and undefined values in transactions are now treated as though the field was not passed in.
### Fixed
* Added `destination_amount` to `PathOption` which is returned as part of a `path_find` request
## 2.7.0 (2023-03-08)
### Fixed
@@ -53,6 +59,9 @@ Wallet.fromMmnemonic()
* `Wallet.fromMnemonic` detects when an invalid encoding is provided, and throws an error
* Made unexpected errors in `submitAndWait` more verbose to make them easier to debug.
### Added
* Support for Automated Market Maker (AMM) transactions and requests as defined in XLS-30.
## 2.3.1 (2022-06-27)
### Fixed
* Signing tx with standard currency codes with lowercase and allowed symbols causing an error on decode.

View File

@@ -1,6 +1,6 @@
{
"name": "xrpl",
"version": "2.7.0",
"name": "@transia/xrpl",
"version": "2.7.1-tbeta.0",
"license": "ISC",
"description": "A TypeScript/JavaScript API for interacting with the XRP Ledger in Node.js and the browser",
"files": [
@@ -75,7 +75,7 @@
"prettier": "@xrplf/prettier-config",
"repository": {
"type": "git",
"url": "git@github.com:XRPLF/xrpl.js.git"
"url": "git@github.com:Transia-RnD/xrpl.js/tree/transia-beta"
},
"readmeFilename": "README.md",
"engines": {

View File

@@ -3,6 +3,7 @@ import BigNumber from 'bignumber.js'
import { fromSeed } from 'bip32'
import { mnemonicToSeedSync, validateMnemonic } from 'bip39'
import isEqual from 'lodash/isEqual'
import omitBy from 'lodash/omitBy'
import {
classicAddressToXAddress,
isValidXAddress,
@@ -26,7 +27,7 @@ import {
import ECDSA from '../ECDSA'
import { ValidationError, XrplError } from '../errors'
import { IssuedCurrencyAmount } from '../models/common'
import { Transaction } from '../models/transactions'
import { Transaction, validate } from '../models/transactions'
import { isIssuedCurrency } from '../models/transactions/common'
import { isHex } from '../models/utils'
import { ensureClassicAddress } from '../sugar/utils'
@@ -323,7 +324,12 @@ class Wallet {
multisignAddress = this.classicAddress
}
const tx = { ...transaction }
// clean null & undefined valued tx properties
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- ensure Transaction flows through
const tx = omitBy(
{ ...transaction },
(value) => value == null,
) as unknown as Transaction
if (tx.TxnSignature || tx.Signers) {
throw new ValidationError(
@@ -333,6 +339,12 @@ class Wallet {
removeTrailingZeros(tx)
/*
* This will throw a more clear error for JS users if the supplied transaction has incorrect formatting
*/
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- validate does not accept Transaction type
validate(tx as unknown as Record<string, unknown>)
const txToSignAndEncode = { ...tx }
txToSignAndEncode.SigningPubKey = multisignAddress ? '' : this.publicKey
@@ -460,9 +472,6 @@ class Wallet {
})
if (txCopy.TransactionType === 'NFTokenMint' && txCopy.URI) {
if (!isHex(txCopy.URI)) {
throw new ValidationError('URI must be a hex value')
}
txCopy.URI = txCopy.URI.toUpperCase()
}

View File

@@ -25,6 +25,9 @@ import {
AccountOffersResponse,
AccountTxRequest,
AccountTxResponse,
// AMM methods
AMMInfoRequest,
AMMInfoResponse,
GatewayBalancesRequest,
GatewayBalancesResponse,
NoRippleCheckRequest,
@@ -101,6 +104,7 @@ import {
getXrpBalance,
submit,
submitAndWait,
getNetworkID,
} from '../sugar'
import fundWallet from '../Wallet/fundWallet'
@@ -200,6 +204,13 @@ class Client extends EventEmitter {
*/
public readonly maxFeeXRP: string
/**
* Network ID of the server this sdk is connected to
*
* @category Fee
*/
public networkID: number
/**
* Creates a new Client with a websocket connection to a rippled server.
*
@@ -218,6 +229,7 @@ class Client extends EventEmitter {
this.feeCushion = options.feeCushion ?? DEFAULT_FEE_CUSHION
this.maxFeeXRP = options.maxFeeXRP ?? DEFAULT_MAX_FEE_XRP
this.networkID = 1
this.connection = new Connection(server, options)
@@ -299,6 +311,7 @@ class Client extends EventEmitter {
): Promise<AccountObjectsResponse>
public async request(r: AccountOffersRequest): Promise<AccountOffersResponse>
public async request(r: AccountTxRequest): Promise<AccountTxResponse>
public async request(r: AMMInfoRequest): Promise<AMMInfoResponse>
public async request(r: BookOffersRequest): Promise<BookOffersResponse>
public async request(r: ChannelVerifyRequest): Promise<ChannelVerifyResponse>
public async request(
@@ -634,6 +647,11 @@ class Client extends EventEmitter {
*/
public getLedgerIndex = getLedgerIndex
/**
* @category Abstraction
*/
public getNetworkID = getNetworkID
/**
* @category Faucet
*/

View File

@@ -4,7 +4,7 @@ interface XRP {
currency: 'XRP'
}
interface IssuedCurrency {
export interface IssuedCurrency {
currency: string
issuer: string
}
@@ -51,6 +51,83 @@ interface PathStep {
export type Path = PathStep[]
/**
* The object that describes the grant in HookGrants.
*/
export interface HookGrant {
/**
* The object that describes the grant in HookGrants.
*/
HookGrant: {
/**
* The hook hash of the grant.
*/
HookHash: string
/**
* The account authorized on the grant.
*/
Authorize?: string
}
}
/**
* The object that describes the parameter in HookParameters.
*/
export interface HookParameter {
/**
* The object that describes the parameter in HookParameters.
*/
HookParameter: {
/**
* The name of the parameter.
*/
HookParameterName: string
/**
* The value of the parameter.
*/
HookParameterValue: string
}
}
/**
* The object that describes the hook in Hooks.
*/
export interface Hook {
/**
* The object that describes the hook in Hooks.
*/
Hook: {
/**
* The code that is executed when the hook is triggered.
*/
CreateCode: string
/**
* The flags that are set on the hook.
*/
Flags: number
/**
* The transactions that triggers the hook. Represented as a 256Hash
*/
HookOn?: string
/**
* The namespace of the hook.
*/
HookNamespace?: string
/**
* The API version of the hook.
*/
HookApiVersion?: number
/**
* The parameters of the hook.
*/
HookParameters?: HookParameter[]
/**
* The grants of the hook.
*/
HookGrants?: HookGrant[]
}
}
/**
* The object that describes the signer in SignerEntries.
*/

View File

@@ -0,0 +1,20 @@
import { Transaction } from '../transactions'
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The EmittedTxn object type contains the
*
* @category Ledger Entries
*/
export default interface EmittedTxn extends BaseLedgerEntry {
LedgerEntryType: 'EmittedTxn'
EmittedTxn: Transaction
/**
* A hint indicating which page of the sender's owner directory links to this
* object, in case the directory consists of multiple pages.
*/
OwnerNode: string
}

View File

@@ -0,0 +1,27 @@
import { Hook as WHook } from '../common'
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The Hook object type contains the
*
* @category Ledger Entries
*/
export default interface Hook extends BaseLedgerEntry {
LedgerEntryType: 'Hook'
/** The identifying (classic) address of this account. */
Account: string
/**
* A hint indicating which page of the sender's owner directory links to this
* object, in case the directory consists of multiple pages.
*/
OwnerNode: string
PreviousTxnID: string
PreviousTxnLgrSeq: number
Hooks: WHook[]
}

View File

@@ -0,0 +1,67 @@
import { HookParameter } from '../common'
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The HookDefintion object type contains the
*
* @category Ledger Entries
*/
export default interface HookDefintion extends BaseLedgerEntry {
LedgerEntryType: 'HookDefintion'
/**
* The flags that are set on the hook.
*/
Flags: number
/**
* This field contains a string that is used to uniquely identify the hook.
*/
HookHash: string
/**
* The transactions that triggers the hook. Represented as a 256Hash
*/
HookOn?: string
/**
* The namespace of the hook.
*/
HookNamespace?: string
/**
* The API version of the hook.
*/
HookApiVersion?: string
/**
* The parameters of the hook.
*/
HookParameters?: HookParameter[]
/**
* The code that is executed when the hook is triggered.
*/
CreateCode?: string
/**
* This is an optional field that contains the transaction ID of the hook set.
*/
HookSetTxnID?: string
/**
* This is an optional field that contains the number of references to this hook.
*/
ReferenceCount?: number
/**
* This is an optional field that contains the fee associated with the hook.
*/
Fee?: string
/**
* This is an optional field that contains the callback fee associated with the hook.
*/
HookCallbackFee?: number
}

View File

@@ -0,0 +1,29 @@
import BaseLedgerEntry from './BaseLedgerEntry'
/**
* The HookState object type contains the
*
* @category Ledger Entries
*/
export default interface HookState extends BaseLedgerEntry {
LedgerEntryType: 'HookState'
/**
* A hint indicating which page of the sender's owner directory links to this
* object, in case the directory consists of multiple pages.
*/
OwnerNode: string
/**
* The HookStateKey property contains the key associated with this hook state,
* and the HookStateData property contains the data associated with this hook state.
*/
HookStateKey: string
/**
* The `HookStateData` property contains the data associated with this hook state.
* It is typically a string containing the data associated with this hook state,
* such as an identifier or other information.
*/
HookStateData: string
}

View File

@@ -3,8 +3,12 @@ import Amendments from './Amendments'
import Check from './Check'
import DepositPreauth from './DepositPreauth'
import DirectoryNode from './DirectoryNode'
import EmittedTxn from './EmittedTxn'
import Escrow from './Escrow'
import FeeSettings from './FeeSettings'
import Hook from './Hook'
import HookDefinition from './HookDefinition'
import HookState from './HookState'
import LedgerHashes from './LedgerHashes'
import NegativeUNL from './NegativeUNL'
import Offer from './Offer'
@@ -19,8 +23,12 @@ type LedgerEntry =
| Check
| DepositPreauth
| DirectoryNode
| EmittedTxn
| Escrow
| FeeSettings
| Hook
| HookDefinition
| HookState
| LedgerHashes
| NegativeUNL
| Offer

View File

@@ -6,8 +6,12 @@ import Amendments from './Amendments'
import Check from './Check'
import DepositPreauth from './DepositPreauth'
import DirectoryNode from './DirectoryNode'
import EmittedTxn from './EmittedTxn'
import Escrow from './Escrow'
import FeeSettings from './FeeSettings'
import Hook from './Hook'
import HookDefinition from './HookDefinition'
import HookState from './HookState'
import Ledger from './Ledger'
import LedgerEntry from './LedgerEntry'
import LedgerHashes from './LedgerHashes'
@@ -26,8 +30,12 @@ export {
Check,
DepositPreauth,
DirectoryNode,
EmittedTxn,
Escrow,
FeeSettings,
Hook,
HookDefinition,
HookState,
Ledger,
LedgerEntry,
LedgerHashes,

View File

@@ -0,0 +1,147 @@
import { Amount, Currency, IssuedCurrencyAmount } from '../common'
import { BaseRequest, BaseResponse } from './baseMethod'
/**
* The `amm_info` command retrieves information about an AMM instance.
* Returns an {@link AMMInfoResponse}.
*
* @category Requests
*/
export interface AMMInfoRequest extends BaseRequest {
command: 'amm_info'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
* Both asset and asset2 must be defined to specify an AMM instance.
*/
asset: Currency
/**
* Specifies the other pool asset of the AMM instance.
* Both asset and asset2 must be defined to specify an AMM instance.
*/
asset2: Currency
}
interface AuthAccount {
account: string
}
interface VoteEntry {
account: string
trading_fee: number
vote_weight: number
}
/**
* Response expected from an {@link AMMInfoRequest}.
*
* @category Responses
*/
export interface AMMInfoResponse extends BaseResponse {
result: {
amm: {
/**
* The account that tracks the balance of LPTokens between the AMM instance via Trustline.
*/
amm_account: string
/**
* One of the pool assets (XRP or token) of the AMM instance.
*/
amount: Amount
/**
* The other pool asset of the AMM instance.
*/
amount2: Amount
/**
* (Omitted for XRP) If true, the amount currency is currently frozen for asset.
*/
asset_frozen: boolean
/**
* (Omitted for XRP) If true, the amount currency is currently frozen for asset2.
*/
asset2_frozen: boolean
/**
* Details of the current owner of the auction slot.
*/
auction_slot?: {
/**
* The current owner of this auction slot.
*/
account: string
/**
* A list of at most 4 additional accounts that are authorized to trade at the discounted fee for this AMM instance.
*/
auth_accounts: AuthAccount[]
/**
* The trading fee to be charged to the auction owner, in the same format as TradingFee.
* By default this is 0, meaning that the auction owner can trade at no fee instead of the standard fee for this AMM.
*/
discounted_fee: number
/**
* The time when this slot expires, in seconds since the Ripple Epoch.
*/
expiration: string
/**
* The amount the auction owner paid to win this slot, in LPTokens.
*/
price: Amount
/**
* Total slot time of 24-hours is divided into 20 equal time intervals.
*/
time_interval: number
}
/**
* The total outstanding balance of liquidity provider tokens from this AMM instance.
* The holders of these tokens can vote on the AMM's trading fee in proportion to their holdings,
* or redeem the tokens for a share of the AMM's assets which grows with the trading fees collected.
*/
lp_token: IssuedCurrencyAmount
/**
* Specifies the fee, in basis point, to be charged to the traders for the trades
* executed against the AMM instance. Trading fee is a percentage of the trading volume.
* Valid values for this field are between 0 and 1000 inclusive.
* A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee
* between 0% and 1%. This field is required.
*/
trading_fee: number
/**
* Keeps a track of up to eight active votes for the instance.
*/
vote_slots?: VoteEntry[]
}
/**
* The identifying hash of the ledger that was used to generate this
* response.
*/
ledger_hash?: string
/**
* The ledger index of the ledger version that was used to generate this
* response.
*/
ledger_index?: number
/**
* If included and set to true, the information in this response comes from
* a validated ledger version. Otherwise, the information is subject to
* change.
*/
validated?: boolean
}
}

View File

@@ -16,6 +16,7 @@ import {
AccountOffersResponse,
} from './accountOffers'
import { AccountTxRequest, AccountTxResponse } from './accountTx'
import { AMMInfoRequest, AMMInfoResponse } from './ammInfo'
import { ErrorResponse } from './baseMethod'
import { BookOffersRequest, BookOffer, BookOffersResponse } from './bookOffers'
import { ChannelVerifyRequest, ChannelVerifyResponse } from './channelVerify'
@@ -87,6 +88,7 @@ type Request =
| AccountObjectsRequest
| AccountOffersRequest
| AccountTxRequest
| AMMInfoRequest
| GatewayBalancesRequest
| NoRippleCheckRequest
// ledger methods
@@ -137,6 +139,7 @@ type Response =
| AccountObjectsResponse
| AccountOffersResponse
| AccountTxResponse
| AMMInfoResponse
| GatewayBalancesResponse
| NoRippleCheckResponse
// ledger methods
@@ -195,6 +198,8 @@ export {
AccountOffersResponse,
AccountTxRequest,
AccountTxResponse,
AMMInfoRequest,
AMMInfoResponse,
GatewayBalancesRequest,
GatewayBalancesResponse,
NoRippleCheckRequest,

View File

@@ -137,6 +137,40 @@ export interface LedgerEntryRequest extends BaseRequest {
ticket_sequence: number
}
| string
/**
* The object ID of a transaction emitted by the ledger entry.
*/
emitted_txn?: string
/**
* The hash of the Hook object to retrieve.
*/
hook_definition?: string
/**
* The Hook object to retrieve. If a string, must be the object ID of the Hook.
* If an object, requires `account` sub-field.
*/
hook?:
| {
/** The account of the Hook object. */
account: string
}
| string
/**
* Object specifying the HookState object to retrieve. Requires the sub-fields
* `account`, `key`, and `namespace_id` to uniquely specify the HookState entry
* to retrieve.
*/
hook_state?: {
/** The account of the Hook object. */
account: string
/** The key of the state. */
key: string
/** The namespace of the state. */
namespace_id: string
}
}
/**

View File

@@ -63,6 +63,11 @@ interface PathOption {
* Destination to receive the desired amount.
*/
source_amount: Amount
/**
* Destination Amount that the destination would receive along this path.
* If the `send_max` field is set, this field will be set.
*/
destination_amount?: Amount
}
/**
@@ -80,7 +85,7 @@ export interface PathFindResponse extends BaseResponse {
alternatives: PathOption[]
/** Unique address of the account that would receive a transaction. */
destination_account: string
/** Currency amount that the destination would receive in a transaction. */
/** Currency amount provided in the WebSocket request. */
destination_amount: Amount
/** Unique address that would send a transaction. */
source_account: string

View File

@@ -136,6 +136,10 @@ export interface ServerInfoResponse extends BaseResponse {
* overall network's load factor.
*/
load_factor?: number
/**
* The network id of the server.
*/
network_id?: number
/**
* Current multiplier to the transaction cost based on
* load to this server.

View File

@@ -0,0 +1,106 @@
/* eslint-disable complexity -- required for validateAMMBid */
import { ValidationError } from '../../errors'
import { Amount, Currency } from '../common'
import {
BaseTransaction,
isAmount,
isCurrency,
validateBaseTransaction,
} from './common'
const MAX_AUTH_ACCOUNTS = 4
interface AuthAccount {
AuthAccount: {
Account: string
}
}
/**
* AMMBid is used for submitting a vote for the trading fee of an AMM Instance.
*
* Any XRPL account that holds LPToken for an AMM instance may submit this
* transaction to vote for the trading fee for that instance.
*/
export interface AMMBid extends BaseTransaction {
TransactionType: 'AMMBid'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
*/
Asset: Currency
/**
* Specifies the other pool asset of the AMM instance.
*/
Asset2: Currency
/**
* This field represents the minimum price that the bidder wants to pay for the slot.
* It is specified in units of LPToken. If specified let BidMin be X and let
* the slot-price computed by price scheduling algorithm be Y, then bidder always pays
* the max(X, Y).
*/
BidMin?: Amount
/**
* This field represents the maximum price that the bidder wants to pay for the slot.
* It is specified in units of LPToken.
*/
BidMax?: Amount
/**
* This field represents an array of XRPL account IDs that are authorized to trade
* at the discounted fee against the AMM instance.
* A maximum of four accounts can be provided.
*/
AuthAccounts?: AuthAccount[]
}
/**
* Verify the form and type of an AMMBid at runtime.
*
* @param tx - An AMMBid Transaction.
* @throws When the AMMBid is Malformed.
*/
export function validateAMMBid(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Asset == null) {
throw new ValidationError('AMMBid: missing field Asset')
}
if (!isCurrency(tx.Asset)) {
throw new ValidationError('AMMBid: Asset must be an Issue')
}
if (tx.Asset2 == null) {
throw new ValidationError('AMMBid: missing field Asset2')
}
if (!isCurrency(tx.Asset2)) {
throw new ValidationError('AMMBid: Asset2 must be an Issue')
}
if (tx.BidMin != null && !isAmount(tx.BidMin)) {
throw new ValidationError('AMMBid: BidMin must be an Amount')
}
if (tx.BidMax != null && !isAmount(tx.BidMax)) {
throw new ValidationError('AMMBid: BidMax must be an Amount')
}
if (tx.AuthAccounts != null) {
if (!Array.isArray(tx.AuthAccounts)) {
throw new ValidationError(
`AMMBid: AuthAccounts must be an AuthAccount array`,
)
}
if (tx.AuthAccounts.length > MAX_AUTH_ACCOUNTS) {
throw new ValidationError(
`AMMBid: AuthAccounts length must not be greater than ${MAX_AUTH_ACCOUNTS}`,
)
}
}
}

View File

@@ -0,0 +1,76 @@
import { ValidationError } from '../../errors'
import { Amount } from '../common'
import { BaseTransaction, isAmount, validateBaseTransaction } from './common'
export const AMM_MAX_TRADING_FEE = 1000
/**
* AMMCreate is used to create AccountRoot and the corresponding
* AMM ledger entries.
*
* This allows for the creation of only one AMM instance per unique asset pair.
*/
export interface AMMCreate extends BaseTransaction {
TransactionType: 'AMMCreate'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
*/
Amount: Amount
/**
* Specifies the other pool asset of the AMM instance.
*/
Amount2: Amount
/**
* Specifies the fee, in basis point, to be charged
* to the traders for the trades executed against the AMM instance.
* Trading fee is a percentage of the trading volume.
* Valid values for this field are between 0 and 1000 inclusive.
* A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee
* between 0% and 1%.
*/
TradingFee: number
}
/**
* Verify the form and type of an AMMCreate at runtime.
*
* @param tx - An AMMCreate Transaction.
* @throws When the AMMCreate is Malformed.
*/
export function validateAMMCreate(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Amount == null) {
throw new ValidationError('AMMCreate: missing field Amount')
}
if (!isAmount(tx.Amount)) {
throw new ValidationError('AMMCreate: Amount must be an Amount')
}
if (tx.Amount2 == null) {
throw new ValidationError('AMMCreate: missing field Amount2')
}
if (!isAmount(tx.Amount2)) {
throw new ValidationError('AMMCreate: Amount2 must be an Amount')
}
if (tx.TradingFee == null) {
throw new ValidationError('AMMCreate: missing field TradingFee')
}
if (typeof tx.TradingFee !== 'number') {
throw new ValidationError('AMMCreate: TradingFee must be a number')
}
if (tx.TradingFee < 0 || tx.TradingFee > AMM_MAX_TRADING_FEE) {
throw new ValidationError(
`AMMCreate: TradingFee must be between 0 and ${AMM_MAX_TRADING_FEE}`,
)
}
}

View File

@@ -0,0 +1,135 @@
/* eslint-disable complexity -- required for validateAMMDeposit */
import { ValidationError } from '../../errors'
import { Amount, Currency, IssuedCurrencyAmount } from '../common'
import {
BaseTransaction,
GlobalFlags,
isAmount,
isCurrency,
isIssuedCurrency,
validateBaseTransaction,
} from './common'
/**
* Enum representing values for AMMDeposit Transaction Flags.
*
* @category Transaction Flags
*/
export enum AMMDepositFlags {
tfLPToken = 0x00010000,
tfSingleAsset = 0x00080000,
tfTwoAsset = 0x00100000,
tfOneAssetLPToken = 0x00200000,
tfLimitLPToken = 0x00400000,
}
export interface AMMDepositFlagsInterface extends GlobalFlags {
tfLPToken?: boolean
tfSingleAsset?: boolean
tfTwoAsset?: boolean
tfOneAssetLPToken?: boolean
tfLimitLPToken?: boolean
}
/**
* AMMDeposit is the deposit transaction used to add liquidity to the AMM instance pool,
* thus obtaining some share of the instance's pools in the form of LPTokenOut.
*
* The following are the recommended valid combinations:
* - LPTokenOut
* - Amount
* - Amount and Amount2
* - Amount and LPTokenOut
* - Amount and EPrice
*/
export interface AMMDeposit extends BaseTransaction {
TransactionType: 'AMMDeposit'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
*/
Asset: Currency
/**
* Specifies the other pool asset of the AMM instance.
*/
Asset2: Currency
/**
* Specifies the amount of shares of the AMM instance pools that the trader
* wants to redeem or trade in.
*/
LPTokenOut?: IssuedCurrencyAmount
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance to
* deposit more of its value.
*/
Amount?: Amount
/**
* Specifies the other pool asset of the AMM instance to deposit more of
* its value.
*/
Amount2?: Amount
/**
* Specifies the maximum effective-price that LPTokenOut can be traded out.
*/
EPrice?: Amount
}
/**
* Verify the form and type of an AMMDeposit at runtime.
*
* @param tx - An AMMDeposit Transaction.
* @throws When the AMMDeposit is Malformed.
*/
export function validateAMMDeposit(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Asset == null) {
throw new ValidationError('AMMDeposit: missing field Asset')
}
if (!isCurrency(tx.Asset)) {
throw new ValidationError('AMMDeposit: Asset must be an Issue')
}
if (tx.Asset2 == null) {
throw new ValidationError('AMMDeposit: missing field Asset2')
}
if (!isCurrency(tx.Asset2)) {
throw new ValidationError('AMMDeposit: Asset2 must be an Issue')
}
if (tx.Amount2 != null && tx.Amount == null) {
throw new ValidationError('AMMDeposit: must set Amount with Amount2')
} else if (tx.EPrice != null && tx.Amount == null) {
throw new ValidationError('AMMDeposit: must set Amount with EPrice')
} else if (tx.LPTokenOut == null && tx.Amount == null) {
throw new ValidationError(
'AMMDeposit: must set at least LPTokenOut or Amount',
)
}
if (tx.LPTokenOut != null && !isIssuedCurrency(tx.LPTokenOut)) {
throw new ValidationError(
'AMMDeposit: LPTokenOut must be an IssuedCurrencyAmount',
)
}
if (tx.Amount != null && !isAmount(tx.Amount)) {
throw new ValidationError('AMMDeposit: Amount must be an Amount')
}
if (tx.Amount2 != null && !isAmount(tx.Amount2)) {
throw new ValidationError('AMMDeposit: Amount2 must be an Amount')
}
if (tx.EPrice != null && !isAmount(tx.EPrice)) {
throw new ValidationError('AMMDeposit: EPrice must be an Amount')
}
}

View File

@@ -0,0 +1,73 @@
import { ValidationError } from '../../errors'
import { Currency } from '../common'
import { AMM_MAX_TRADING_FEE } from './AMMCreate'
import { BaseTransaction, isCurrency, validateBaseTransaction } from './common'
/**
* AMMVote is used for submitting a vote for the trading fee of an AMM Instance.
*
* Any XRPL account that holds LPToken for an AMM instance may submit this
* transaction to vote for the trading fee for that instance.
*/
export interface AMMVote extends BaseTransaction {
TransactionType: 'AMMVote'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
*/
Asset: Currency
/**
* Specifies the other pool asset of the AMM instance.
*/
Asset2: Currency
/**
* Specifies the fee, in basis point.
* Valid values for this field are between 0 and 1000 inclusive.
* A value of 1 is equivalent to 1/10 bps or 0.001%, allowing trading fee
* between 0% and 1%. This field is required.
*/
TradingFee: number
}
/**
* Verify the form and type of an AMMVote at runtime.
*
* @param tx - An AMMVote Transaction.
* @throws When the AMMVote is Malformed.
*/
export function validateAMMVote(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Asset == null) {
throw new ValidationError('AMMVote: missing field Asset')
}
if (!isCurrency(tx.Asset)) {
throw new ValidationError('AMMVote: Asset must be an Issue')
}
if (tx.Asset2 == null) {
throw new ValidationError('AMMVote: missing field Asset2')
}
if (!isCurrency(tx.Asset2)) {
throw new ValidationError('AMMVote: Asset2 must be an Issue')
}
if (tx.TradingFee == null) {
throw new ValidationError('AMMVote: missing field TradingFee')
}
if (typeof tx.TradingFee !== 'number') {
throw new ValidationError('AMMVote: TradingFee must be a number')
}
if (tx.TradingFee < 0 || tx.TradingFee > AMM_MAX_TRADING_FEE) {
throw new ValidationError(
`AMMVote: TradingFee must be between 0 and ${AMM_MAX_TRADING_FEE}`,
)
}
}

View File

@@ -0,0 +1,137 @@
/* eslint-disable complexity -- required for validateAMMWithdraw */
import { ValidationError } from '../../errors'
import { Amount, Currency, IssuedCurrencyAmount } from '../common'
import {
BaseTransaction,
GlobalFlags,
isAmount,
isCurrency,
isIssuedCurrency,
validateBaseTransaction,
} from './common'
/**
* Enum representing values for AMMWithdrawFlags Transaction Flags.
*
* @category Transaction Flags
*/
export enum AMMWithdrawFlags {
tfLPToken = 0x00010000,
tfWithdrawAll = 0x00020000,
tfOneAssetWithdrawAll = 0x00040000,
tfSingleAsset = 0x00080000,
tfTwoAsset = 0x00100000,
tfOneAssetLPToken = 0x00200000,
tfLimitLPToken = 0x00400000,
}
export interface AMMWithdrawFlagsInterface extends GlobalFlags {
tfLPToken?: boolean
tfWithdrawAll?: boolean
tfOneAssetWithdrawAll?: boolean
tfSingleAsset?: boolean
tfTwoAsset?: boolean
tfOneAssetLPToken?: boolean
tfLimitLPToken?: boolean
}
/**
* AMMWithdraw is the withdraw transaction used to remove liquidity from the AMM
* instance pool, thus redeeming some share of the pools that one owns in the form
* of LPTokenIn.
*
* The following are the recommended valid combinations:
* - LPTokenIn
* - Amount
* - Amount and Amount2
* - Amount and LPTokenIn
* - Amount and EPrice
*/
export interface AMMWithdraw extends BaseTransaction {
TransactionType: 'AMMWithdraw'
/**
* Specifies one of the pool assets (XRP or token) of the AMM instance.
*/
Asset: Currency
/**
* Specifies the other pool asset of the AMM instance.
*/
Asset2: Currency
/**
* Specifies the amount of shares of the AMM instance pools that the trader
* wants to redeem or trade in.
*/
LPTokenIn?: IssuedCurrencyAmount
/**
* Specifies one of the pools assets that the trader wants to remove.
* If the asset is XRP, then the Amount is a string specifying the number of drops.
* Otherwise it is an IssuedCurrencyAmount object.
*/
Amount?: Amount
/**
* Specifies the other pool asset that the trader wants to remove.
*/
Amount2?: Amount
/**
* Specifies the effective-price of the token out after successful execution of
* the transaction.
*/
EPrice?: Amount
}
/**
* Verify the form and type of an AMMWithdraw at runtime.
*
* @param tx - An AMMWithdraw Transaction.
* @throws When the AMMWithdraw is Malformed.
*/
export function validateAMMWithdraw(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Asset == null) {
throw new ValidationError('AMMWithdraw: missing field Asset')
}
if (!isCurrency(tx.Asset)) {
throw new ValidationError('AMMWithdraw: Asset must be an Issue')
}
if (tx.Asset2 == null) {
throw new ValidationError('AMMWithdraw: missing field Asset2')
}
if (!isCurrency(tx.Asset2)) {
throw new ValidationError('AMMWithdraw: Asset2 must be an Issue')
}
if (tx.Amount2 != null && tx.Amount == null) {
throw new ValidationError('AMMWithdraw: must set Amount with Amount2')
} else if (tx.EPrice != null && tx.Amount == null) {
throw new ValidationError('AMMWithdraw: must set Amount with EPrice')
}
if (tx.LPTokenIn != null && !isIssuedCurrency(tx.LPTokenIn)) {
throw new ValidationError(
'AMMWithdraw: LPTokenIn must be an IssuedCurrencyAmount',
)
}
if (tx.Amount != null && !isAmount(tx.Amount)) {
throw new ValidationError('AMMWithdraw: Amount must be an Amount')
}
if (tx.Amount2 != null && !isAmount(tx.Amount2)) {
throw new ValidationError('AMMWithdraw: Amount2 must be an Amount')
}
if (tx.EPrice != null && !isAmount(tx.EPrice)) {
throw new ValidationError('AMMWithdraw: EPrice must be an Amount')
}
}

View File

@@ -86,8 +86,11 @@ export interface NFTokenMint extends BaseTransaction {
*
* This field must be hex-encoded. You can use `convertStringToHex` to
* convert this field to the proper encoding.
*
* This field must not be an empty string. Omit it from the transaction or
* set to `undefined` value if you do not use it.
*/
URI?: string
URI?: string | null
Flags?: number | NFTokenMintFlagsInterface
}
@@ -106,6 +109,10 @@ export function validateNFTokenMint(tx: Record<string, unknown>): void {
)
}
if (typeof tx.URI === 'string' && tx.URI === '') {
throw new ValidationError('NFTokenMint: URI must not be empty string')
}
if (typeof tx.URI === 'string' && !isHex(tx.URI)) {
throw new ValidationError('NFTokenMint: URI must be in hex format')
}

View File

@@ -4,7 +4,7 @@
import { TRANSACTION_TYPES } from 'ripple-binary-codec'
import { ValidationError } from '../../errors'
import { Amount, IssuedCurrencyAmount, Memo, Signer } from '../common'
import { Amount, Currency, IssuedCurrencyAmount, Memo, Signer } from '../common'
import { onlyHasFields } from '../utils'
const MEMO_SIZE = 3
@@ -50,17 +50,36 @@ function isSigner(obj: unknown): boolean {
)
}
const XRP_CURRENCY_SIZE = 1
const ISSUE_SIZE = 2
const ISSUED_CURRENCY_SIZE = 3
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object'
}
/**
* Verify the form and type of an IssuedCurrency at runtime.
*
* @param input - The input to check the form and type of.
* @returns Whether the IssuedCurrency is properly formed.
*/
export function isCurrency(input: unknown): input is Currency {
return (
isRecord(input) &&
((Object.keys(input).length === ISSUE_SIZE &&
typeof input.issuer === 'string' &&
typeof input.currency === 'string') ||
(Object.keys(input).length === XRP_CURRENCY_SIZE &&
input.currency === 'XRP'))
)
}
/**
* Verify the form and type of an IssuedCurrencyAmount at runtime.
*
* @param input - The input to check the form and type of.
* @returns Whether the IssuedCurrencyAmount is malformed.
* @returns Whether the IssuedCurrencyAmount is properly formed.
*/
export function isIssuedCurrency(
input: unknown,
@@ -78,7 +97,7 @@ export function isIssuedCurrency(
* Verify the form and type of an Amount at runtime.
*
* @param amount - The object to check the form and type of.
* @returns Whether the Amount is malformed.
* @returns Whether the Amount is properly formed.
*/
export function isAmount(amount: unknown): amount is Amount {
return typeof amount === 'string' || isIssuedCurrency(amount)
@@ -159,6 +178,7 @@ export interface BaseTransaction {
* account it says it is from.
*/
TxnSignature?: string
NetworkID?: number
}
/**
@@ -252,6 +272,9 @@ export function validateBaseTransaction(common: Record<string, unknown>): void {
) {
throw new ValidationError('BaseTransaction: invalid TxnSignature')
}
if (common.NetworkID !== undefined && typeof common.NetworkID !== 'number') {
throw new ValidationError('BaseTransaction: invalid NetworkID')
}
}
/**

View File

@@ -7,6 +7,19 @@ export {
AccountSet,
} from './accountSet'
export { AccountDelete } from './accountDelete'
export { AMMBid } from './AMMBid'
export {
AMMDepositFlags,
AMMDepositFlagsInterface,
AMMDeposit,
} from './AMMDeposit'
export { AMMCreate } from './AMMCreate'
export { AMMVote } from './AMMVote'
export {
AMMWithdrawFlags,
AMMWithdrawFlagsInterface,
AMMWithdraw,
} from './AMMWithdraw'
export { CheckCancel } from './checkCancel'
export { CheckCash } from './checkCash'
export { CheckCreate } from './checkCreate'
@@ -14,6 +27,7 @@ export { DepositPreauth } from './depositPreauth'
export { EscrowCancel } from './escrowCancel'
export { EscrowCreate } from './escrowCreate'
export { EscrowFinish } from './escrowFinish'
export { Invoke } from './invoke'
export { NFTokenAcceptOffer } from './NFTokenAcceptOffer'
export { NFTokenBurn } from './NFTokenBurn'
export { NFTokenCancelOffer } from './NFTokenCancelOffer'
@@ -42,6 +56,16 @@ export {
export { PaymentChannelCreate } from './paymentChannelCreate'
export { PaymentChannelFund } from './paymentChannelFund'
export { SetRegularKey } from './setRegularKey'
export { SetHook } from './setHook'
export { SignerListSet } from './signerListSet'
export { TicketCreate } from './ticketCreate'
export { TrustSetFlagsInterface, TrustSetFlags, TrustSet } from './trustSet'
export {
URITokenMintFlagsInterface,
URITokenMintFlags,
URITokenMint,
} from './uriTokenMint'
export { URITokenBurn } from './uriTokenBurn'
export { URITokenCreateSellOffer } from './uriTokenCreateSellOffer'
export { URITokenBuy } from './uriTokenBuy'
export { URITokenCancelSellOffer } from './uriTokenCancelSellOffer'

View File

@@ -0,0 +1,32 @@
import { ValidationError } from '../../errors'
import { BaseTransaction, validateBaseTransaction } from './common'
/**
*
*
* @category Transaction Models
*/
export interface Invoke extends BaseTransaction {
TransactionType: 'Invoke'
/**
* If present, invokes the Hook on the Destination account.
*/
Destination?: string
}
/**
* Verify the form and type of an Invoke at runtime.
*
* @param tx - An Invoke Transaction.
* @throws When the Invoke is Malformed.
*/
export function validateInvoke(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Account === tx.Destination) {
throw new ValidationError(
'Invoke: Destination and Account must not be equal',
)
}
}

View File

@@ -0,0 +1,56 @@
import { ValidationError } from '../../errors'
import { Hook } from '../common'
import { BaseTransaction, validateBaseTransaction } from './common'
/**
*
*
* @category Transaction Models
*/
export interface SetHook extends BaseTransaction {
TransactionType: 'SetHook'
/**
*
*/
Hooks: Hook[]
}
const MAX_HOOKS = 4
const HEX_REGEX = /^[0-9A-Fa-f]{64}$/u
/**
* Verify the form and type of an SetHook at runtime.
*
* @param tx - An SetHook Transaction.
* @throws When the SetHook is Malformed.
*/
export function validateSetHook(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (!Array.isArray(tx.Hooks)) {
throw new ValidationError('SetHook: invalid Hooks')
}
if (tx.Hooks.length > MAX_HOOKS) {
throw new ValidationError(
`SetHook: maximum of ${MAX_HOOKS} hooks allowed in Hooks`,
)
}
for (const hook of tx.Hooks) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be a Hook
const hookObject = hook as Hook
const { HookOn, HookNamespace } = hookObject.Hook
if (HookOn !== undefined && !HEX_REGEX.test(HookOn)) {
throw new ValidationError(
`SetHook: HookOn in Hook must be a 256-bit (32-byte) hexadecimal value`,
)
}
if (HookNamespace !== undefined && !HEX_REGEX.test(HookNamespace)) {
throw new ValidationError(
`SetHook: HookNamespace in Hook must be a 256-bit (32-byte) hexadecimal value`,
)
}
}
}

View File

@@ -1,15 +1,16 @@
/* eslint-disable complexity -- verifies 19 tx types hence a lot of checks needed */
/* eslint-disable max-lines-per-function -- need to work with a lot of Tx verifications */
import isEqual from 'lodash/isEqual'
import omitBy from 'lodash/omitBy'
import { encode, decode } from 'ripple-binary-codec'
import { ValidationError } from '../../errors'
import { setTransactionFlagsToNumber } from '../utils/flags'
import { AccountDelete, validateAccountDelete } from './accountDelete'
import { AccountSet, validateAccountSet } from './accountSet'
import { AMMBid, validateAMMBid } from './AMMBid'
import { AMMCreate, validateAMMCreate } from './AMMCreate'
import { AMMDeposit, validateAMMDeposit } from './AMMDeposit'
import { AMMVote, validateAMMVote } from './AMMVote'
import { AMMWithdraw, validateAMMWithdraw } from './AMMWithdraw'
import { CheckCancel, validateCheckCancel } from './checkCancel'
import { CheckCash, validateCheckCash } from './checkCash'
import { CheckCreate, validateCheckCreate } from './checkCreate'
@@ -47,10 +48,22 @@ import {
PaymentChannelFund,
validatePaymentChannelFund,
} from './paymentChannelFund'
import { SetHook, validateSetHook } from './setHook'
import { SetRegularKey, validateSetRegularKey } from './setRegularKey'
import { SignerListSet, validateSignerListSet } from './signerListSet'
import { TicketCreate, validateTicketCreate } from './ticketCreate'
import { TrustSet, validateTrustSet } from './trustSet'
import { URITokenBurn, validateURITokenBurn } from './uriTokenBurn'
import { URITokenBuy, validateURITokenBuy } from './uriTokenBuy'
import {
URITokenCancelSellOffer,
validateURITokenCancelSellOffer,
} from './uriTokenCancelSellOffer'
import {
URITokenCreateSellOffer,
validateURITokenCreateSellOffer,
} from './uriTokenCreateSellOffer'
import { URITokenMint, validateURITokenMint } from './uriTokenMint'
/**
* @category Transaction Models
@@ -58,6 +71,11 @@ import { TrustSet, validateTrustSet } from './trustSet'
export type Transaction =
| AccountDelete
| AccountSet
| AMMBid
| AMMDeposit
| AMMCreate
| AMMVote
| AMMWithdraw
| CheckCancel
| CheckCash
| CheckCreate
@@ -76,10 +94,16 @@ export type Transaction =
| PaymentChannelClaim
| PaymentChannelCreate
| PaymentChannelFund
| SetHook
| SetRegularKey
| SignerListSet
| TicketCreate
| TrustSet
| URITokenBurn
| URITokenBuy
| URITokenCancelSellOffer
| URITokenMint
| URITokenCreateSellOffer
/**
* @category Transaction Models
@@ -116,6 +140,26 @@ export function validate(transaction: Record<string, unknown>): void {
validateAccountSet(tx)
break
case 'AMMBid':
validateAMMBid(tx)
break
case 'AMMDeposit':
validateAMMDeposit(tx)
break
case 'AMMCreate':
validateAMMCreate(tx)
break
case 'AMMVote':
validateAMMVote(tx)
break
case 'AMMWithdraw':
validateAMMWithdraw(tx)
break
case 'CheckCancel':
validateCheckCancel(tx)
break
@@ -192,6 +236,10 @@ export function validate(transaction: Record<string, unknown>): void {
validateSetRegularKey(tx)
break
case 'SetHook':
validateSetHook(tx)
break
case 'SignerListSet':
validateSignerListSet(tx)
break
@@ -204,18 +252,29 @@ export function validate(transaction: Record<string, unknown>): void {
validateTrustSet(tx)
break
case 'URITokenMint':
validateURITokenMint(tx)
break
case 'URITokenBurn':
validateURITokenBurn(tx)
break
case 'URITokenCreateSellOffer':
validateURITokenCreateSellOffer(tx)
break
case 'URITokenBuy':
validateURITokenBuy(tx)
break
case 'URITokenCancelSellOffer':
validateURITokenCancelSellOffer(tx)
break
default:
throw new ValidationError(
`Invalid field TransactionType: ${tx.TransactionType}`,
)
}
if (
!isEqual(
decode(encode(tx)),
omitBy(tx, (value) => value == null),
)
) {
throw new ValidationError(`Invalid Transaction: ${tx.TransactionType}`)
}
}

View File

@@ -0,0 +1,60 @@
import { ValidationError } from '../../errors'
import { BaseTransaction, validateBaseTransaction } from './common'
/**
* Map of flags to boolean values representing {@link URITokenBurn} transaction
* flags.
*
* @category Transaction Flags
*
* @example
* ```typescript
* const tx: URITokenBurn = {
* Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* TransactionType: 'URITokenBurn',
* }
*
* // Autofill the tx to see how flags actually look compared to the interface usage.
* const autofilledTx = await client.autofill(tx)
* console.log(autofilledTx)
* // {
* // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* // URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* // TransactionType: 'URITokenBurn',
* // Sequence: 21970384,
* // Fee: '12',
* // LastLedgerSequence: 21970404
* // }
* ```
*/
/**
* An URITokenBurn transaction is effectively a limit order . It defines an
* intent to exchange currencies, and creates an Offer object if not completely.
* Fulfilled when placed. Offers can be partially fulfilled.
*
* @category Transaction Models
*/
export interface URITokenBurn extends BaseTransaction {
TransactionType: 'URITokenBurn'
/**
* Identifies the URIToken object to be removed by the transaction.
*/
URITokenID: string
}
/**
* Verify the form and type of an URITokenBurn at runtime.
*
* @param tx - An URITokenBurn Transaction.
* @throws When the URITokenBurn is Malformed.
*/
export function validateURITokenBurn(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.URITokenID == null) {
throw new ValidationError('NFTokenBurn: missing field URITokenID')
}
}

View File

@@ -0,0 +1,83 @@
import { ValidationError } from '../../errors'
import { Amount } from '../common'
import { BaseTransaction, isAmount, validateBaseTransaction } from './common'
/**
* Map of flags to boolean values representing {@link URITokenBuy} transaction
* flags.
*
* @category Transaction Flags
*
* @example
* ```typescript
* const tx: URITokenBuy = {
* Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* Amount: '1000000',
* TransactionType: 'URITokenBuy',
* }
*
* // Autofill the tx to see how flags actually look compared to the interface usage.
* const autofilledTx = await client.autofill(tx)
* console.log(autofilledTx)
* // {
* // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* // URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* // Amount: '1000000',
* // TransactionType: 'URITokenBuy',
* // Sequence: 21970384,
* // Fee: '12',
* // LastLedgerSequence: 21970404
* // }
* ```
*/
/**
* An URITokenBuy transaction is effectively a limit order . It defines an
* intent to exchange currencies, and creates an Offer object if not completely.
* Fulfilled when placed. Offers can be partially fulfilled.
*
* @category Transaction Models
*/
export interface URITokenBuy extends BaseTransaction {
TransactionType: 'URITokenBuy'
/**
* Identifies the URITokenID of the NFToken object that the
* offer references.
*/
URITokenID: string
/**
* Indicates the amount expected or offered for the Token.
*
* The amount must be non-zero, except when this is a sell
* offer and the asset is XRP. This would indicate that the current
* owner of the token is giving it away free, either to anyone at all,
* or to the account identified by the Destination field.
*/
Amount: Amount
}
/**
* Verify the form and type of an URITokenBuy at runtime.
*
* @param tx - An URITokenBuy Transaction.
* @throws When the URITokenBuy is Malformed.
*/
export function validateURITokenBuy(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (tx.Account === tx.Destination) {
throw new ValidationError(
'URITokenBuy: Destination and Account must not be equal',
)
}
if (tx.URITokenID == null) {
throw new ValidationError('URITokenBuy: missing field URITokenID')
}
if (!isAmount(tx.Amount)) {
throw new ValidationError('URITokenBuy: invalid Amount')
}
}

View File

@@ -0,0 +1,65 @@
import { ValidationError } from '../../errors'
import { BaseTransaction, validateBaseTransaction } from './common'
/**
* Map of flags to boolean values representing {@link URITokenCancelSellOffer} transaction
* flags.
*
* @category Transaction Flags
*
* @example
* ```typescript
* const tx: URITokenCancelSellOffer = {
* Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* TransactionType: 'URITokenCancelSellOffer',
* }
*
* // Autofill the tx to see how flags actually look compared to the interface usage.
* const autofilledTx = await client.autofill(tx)
* console.log(autofilledTx)
* // {
* // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* // URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* // TransactionType: 'URITokenCancelSellOffer',
* // Sequence: 21970384,
* // Fee: '12',
* // LastLedgerSequence: 21970404
* // }
* ```
*/
/**
* An URITokenCancelSellOffer transaction is effectively a limit order . It defines an
* intent to exchange currencies, and creates an Offer object if not completely.
* Fulfilled when placed. Offers can be partially fulfilled.
*
* @category Transaction Models
*/
export interface URITokenCancelSellOffer extends BaseTransaction {
TransactionType: 'URITokenCancelSellOffer'
/**
* Identifies the URITokenID of the NFToken object that the
* offer references.
*/
URITokenID: string
}
/**
* Verify the form and type of an URITokenCancelSellOffer at runtime.
*
* @param tx - An URITokenCancelSellOffer Transaction.
* @throws When the URITokenCancelSellOffer is Malformed.
*/
export function validateURITokenCancelSellOffer(
tx: Record<string, unknown>,
): void {
validateBaseTransaction(tx)
if (tx.URITokenID == null) {
throw new ValidationError(
'URITokenCancelSellOffer: missing field URITokenID',
)
}
}

View File

@@ -0,0 +1,93 @@
import { ValidationError } from '../../errors'
import { Amount } from '../common'
import { BaseTransaction, isAmount, validateBaseTransaction } from './common'
/**
* Map of flags to boolean values representing {@link URITokenCreateSellOffer} transaction
* flags.
*
* @category Transaction Flags
*
* @example
* ```typescript
* const tx: URITokenCreateSellOffer = {
* Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* Amount: '1000000',
* TransactionType: 'URITokenCreateSellOffer',
* }
*
* // Autofill the tx to see how flags actually look compared to the interface usage.
* const autofilledTx = await client.autofill(tx)
* console.log(autofilledTx)
* // {
* // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* // URITokenID: '7AFCE32EBA8BD310CC2D00BE10B76E2183337EA20444D4580E4DBDB396C101FB',
* // Amount: '1000000',
* // TransactionType: 'URITokenCreateSellOffer',
* // Sequence: 21970384,
* // Fee: '12',
* // LastLedgerSequence: 21970404
* // }
* ```
*/
/**
* An URITokenCreateSellOffer transaction is effectively a limit order . It defines an
* intent to exchange currencies, and creates an Offer object if not completely.
* Fulfilled when placed. Offers can be partially fulfilled.
*
* @category Transaction Models
*/
export interface URITokenCreateSellOffer extends BaseTransaction {
TransactionType: 'URITokenCreateSellOffer'
/**
* Identifies the URITokenID of the NFToken object that the
* offer references.
*/
URITokenID: string
/**
* Indicates the amount expected or offered for the Token.
*
* The amount must be non-zero, except when this is a sell
* offer and the asset is XRP. This would indicate that the current
* owner of the token is giving it away free, either to anyone at all,
* or to the account identified by the Destination field.
*/
Amount: Amount
/**
* If present, indicates that this offer may only be
* accepted by the specified account. Attempts by other
* accounts to accept this offer MUST fail.
*/
Destination?: string
}
/**
* Verify the form and type of an URITokenCreateSellOffer at runtime.
*
* @param tx - An URITokenCreateSellOffer Transaction.
* @throws When the URITokenCreateSellOffer is Malformed.
*/
export function validateURITokenCreateSellOffer(
tx: Record<string, unknown>,
): void {
validateBaseTransaction(tx)
if (tx.Account === tx.Destination) {
throw new ValidationError(
'URITokenCreateSellOffer: Destination and Account must not be equal',
)
}
if (tx.URITokenID == null) {
throw new ValidationError(
'URITokenCreateSellOffer: missing field URITokenID',
)
}
if (!isAmount(tx.Amount)) {
throw new ValidationError('URITokenCreateSellOffer: invalid Amount')
}
}

View File

@@ -0,0 +1,92 @@
import { ValidationError } from '../../errors'
import { isHex } from '../utils'
import { BaseTransaction, GlobalFlags, validateBaseTransaction } from './common'
/**
* Transaction Flags for an URITokenMint Transaction.
*
* @category Transaction Flags
*/
export enum URITokenMintFlags {
/**
* If set, indicates that the minted token may be burned by the issuer even
* if the issuer does not currently hold the token. The current holder of
* the token may always burn it.
*/
tfBurnable = 0x00000001,
}
/**
* Map of flags to boolean values representing {@link URITokenMint} transaction
* flags.
*
* @category Transaction Flags
*
* @example
* ```typescript
* const tx: URITokenMint = {
* Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* URI: '697066733A2F2F434944',
* TransactionType: 'URITokenMint',
* Flags: {
* tfBurnable: true,
* },
* }
*
* // Autofill the tx to see how flags actually look compared to the interface usage.
* const autofilledTx = await client.autofill(tx)
* console.log(autofilledTx)
* // {
* // Account: 'rhFcpWDHLqpBmX4ezWiA5VLSS4e1BHqhHd',
* // URI: '697066733A2F2F434944',
* // TransactionType: 'URITokenMint',
* // Flags: 0,
* // Sequence: 21970384,
* // Fee: '12',
* // LastLedgerSequence: 21970404
* // }
* ```
*/
export interface URITokenMintFlagsInterface extends GlobalFlags {
tfBurnable?: boolean
}
/**
* An URITokenMint transaction is effectively a limit order . It defines an
* intent to exchange currencies, and creates an Offer object if not completely.
* Fulfilled when placed. Offers can be partially fulfilled.
*
* @category Transaction Models
*/
export interface URITokenMint extends BaseTransaction {
TransactionType: 'URITokenMint'
Flags?: number | URITokenMintFlagsInterface
/**
* URI that points to the data and/or metadata associated with the NFT.
* This field need not be an HTTP or HTTPS URL; it could be an IPFS URI, a
* magnet link, immediate data encoded as an RFC2379 "data" URL, or even an
* opaque issuer-specific encoding. The URI is NOT checked for validity, but
* the field is limited to a maximum length of 256 bytes.
*
* This field must be hex-encoded. You can use `convertStringToHex` to
* convert this field to the proper encoding.
*/
URI: string
Digest?: string
}
/**
* Verify the form and type of an URITokenMint at runtime.
*
* @param tx - An URITokenMint Transaction.
* @throws When the URITokenMint is Malformed.
*/
export function validateURITokenMint(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
if (typeof tx.URI === 'string' && !isHex(tx.URI)) {
throw new ValidationError('URITokenMint: URI must be in hex format')
}
}

View File

@@ -6,22 +6,15 @@ import {
AccountRootFlagsInterface,
AccountRootFlags,
} from '../ledger/AccountRoot'
import {
AccountSetFlagsInterface,
AccountSetTfFlags,
} from '../transactions/accountSet'
import { AccountSetTfFlags } from '../transactions/accountSet'
import { AMMDepositFlags } from '../transactions/AMMDeposit'
import { AMMWithdrawFlags } from '../transactions/AMMWithdraw'
import { GlobalFlags } from '../transactions/common'
import {
OfferCreateFlagsInterface,
OfferCreateFlags,
} from '../transactions/offerCreate'
import { PaymentFlagsInterface, PaymentFlags } from '../transactions/payment'
import {
PaymentChannelClaimFlagsInterface,
PaymentChannelClaimFlags,
} from '../transactions/paymentChannelClaim'
import { OfferCreateFlags } from '../transactions/offerCreate'
import { PaymentFlags } from '../transactions/payment'
import { PaymentChannelClaimFlags } from '../transactions/paymentChannelClaim'
import type { Transaction } from '../transactions/transaction'
import { TrustSetFlagsInterface, TrustSetFlags } from '../transactions/trustSet'
import { TrustSetFlags } from '../transactions/trustSet'
import { isFlagEnabled } from '.'
@@ -61,55 +54,33 @@ export function setTransactionFlagsToNumber(tx: Transaction): void {
switch (tx.TransactionType) {
case 'AccountSet':
tx.Flags = convertAccountSetFlagsToNumber(tx.Flags)
tx.Flags = convertFlagsToNumber(tx.Flags, AccountSetTfFlags)
return
case 'AMMDeposit':
tx.Flags = convertFlagsToNumber(tx.Flags, AMMDepositFlags)
return
case 'AMMWithdraw':
tx.Flags = convertFlagsToNumber(tx.Flags, AMMWithdrawFlags)
return
case 'OfferCreate':
tx.Flags = convertOfferCreateFlagsToNumber(tx.Flags)
tx.Flags = convertFlagsToNumber(tx.Flags, OfferCreateFlags)
return
case 'PaymentChannelClaim':
tx.Flags = convertPaymentChannelClaimFlagsToNumber(tx.Flags)
tx.Flags = convertFlagsToNumber(tx.Flags, PaymentChannelClaimFlags)
return
case 'Payment':
tx.Flags = convertPaymentTransactionFlagsToNumber(tx.Flags)
tx.Flags = convertFlagsToNumber(tx.Flags, PaymentFlags)
return
case 'TrustSet':
tx.Flags = convertTrustSetFlagsToNumber(tx.Flags)
tx.Flags = convertFlagsToNumber(tx.Flags, TrustSetFlags)
return
default:
tx.Flags = 0
}
}
function convertAccountSetFlagsToNumber(
flags: AccountSetFlagsInterface,
): number {
return reduceFlags(flags, AccountSetTfFlags)
}
function convertOfferCreateFlagsToNumber(
flags: OfferCreateFlagsInterface,
): number {
return reduceFlags(flags, OfferCreateFlags)
}
function convertPaymentChannelClaimFlagsToNumber(
flags: PaymentChannelClaimFlagsInterface,
): number {
return reduceFlags(flags, PaymentChannelClaimFlags)
}
function convertPaymentTransactionFlagsToNumber(
flags: PaymentFlagsInterface,
): number {
return reduceFlags(flags, PaymentFlags)
}
function convertTrustSetFlagsToNumber(flags: TrustSetFlagsInterface): number {
return reduceFlags(flags, TrustSetFlags)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- added ValidationError check for flagEnum
function reduceFlags(flags: GlobalFlags, flagEnum: any): number {
function convertFlagsToNumber(flags: GlobalFlags, flagEnum: any): number {
return Object.keys(flags).reduce((resultFlags, flag) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- safe member access
if (flagEnum[flag] == null) {

View File

@@ -8,10 +8,11 @@ import { Transaction } from '../models/transactions'
import { setTransactionFlagsToNumber } from '../models/utils/flags'
import { xrpToDrops } from '../utils'
import getFeeXrp from './getFeeXrp'
import { getFeeXrp } from './getFeeXrp'
// Expire unconfirmed transactions after 20 ledger versions, approximately 1 minute, by default
const LEDGER_OFFSET = 20
const RESTRICTED_NETWORKS = 1024
interface ClassicAccountAndTag {
classicAccount: string
tag: number | false | undefined
@@ -39,8 +40,10 @@ async function autofill<T extends Transaction>(
setValidAddresses(tx)
setTransactionFlagsToNumber(tx)
const promises: Array<Promise<void>> = []
if (this.networkID > RESTRICTED_NETWORKS && tx.NetworkID == null) {
tx.NetworkID = this.networkID
}
if (tx.Sequence == null) {
promises.push(setNextValidSequenceNumber(this, tx))
}
@@ -140,7 +143,7 @@ async function setNextValidSequenceNumber(
tx.Sequence = data.result.account_data.Sequence
}
async function fetchAccountDeleteFee(client: Client): Promise<BigNumber> {
async function fetchOwnerReserveFee(client: Client): Promise<BigNumber> {
const response = await client.request({ command: 'server_state' })
const fee = response.result.state.validated_ledger?.reserve_inc
@@ -172,9 +175,11 @@ async function calculateFeePerTransactionType(
baseFee = product.dp(0, BigNumber.ROUND_CEIL)
}
// AccountDelete Transaction
if (tx.TransactionType === 'AccountDelete') {
baseFee = await fetchAccountDeleteFee(client)
if (
tx.TransactionType === 'AccountDelete' ||
tx.TransactionType === 'AMMCreate'
) {
baseFee = await fetchOwnerReserveFee(client)
}
/*

View File

@@ -14,7 +14,7 @@ const BASE_10 = 10
* @param cushion - The fee cushion to use.
* @returns The transaction fee.
*/
export default async function getFeeXrp(
export async function getFeeXrp(
client: Client,
cushion?: number,
): Promise<string> {
@@ -43,3 +43,22 @@ export default async function getFeeXrp(
// Round fee to 6 decimal places
return new BigNumber(fee.toFixed(NUM_DECIMAL_PLACES)).toString(BASE_10)
}
/**
* Calculates the estimated transaction fee.
* Note: This is a public API that can be called directly.
*
* @param client - The Client used to connect to the ledger.
* @param txBlob - The encoded transaction to estimate the fee for.
* @returns The transaction fee.
*/
export async function getFeeEstimateXrp(
client: Client,
txBlob: string,
): Promise<string> {
const response = await client.request({
command: 'fee',
tx_blob: txBlob,
})
return response.result.drops.base_fee
}

View File

@@ -0,0 +1,15 @@
import type { Client } from '..'
// import { XrplError } from '../errors'
/**
* Returns the network ID of the rippled server.
*
* @param this - The Client used to connect to the ledger.
* @returns The network id.
*/
export default async function getNetworkID(this: Client): Promise<number> {
const response = await this.request({
command: 'server_info',
})
return response.result.info.network_id ?? 1
}

View File

@@ -5,6 +5,9 @@ export { getBalances, getXrpBalance } from './balances'
export { default as getLedgerIndex } from './getLedgerIndex'
export { default as getOrderbook } from './getOrderbook'
export { getFeeXrp, getFeeEstimateXrp } from './getFeeXrp'
export { default as getNetworkID } from './getNetworkID'
export * from './submit'

View File

@@ -0,0 +1,114 @@
/**
* @module tts
* @description
* This module contains the transaction types and the function to calculate the hook on
*/
// eslint-disable-next-line @typescript-eslint/no-require-imports -- Required
import createHash = require('create-hash')
import { TRANSACTION_TYPES, TRANSACTION_TYPE_MAP } from 'ripple-binary-codec'
import { XrplError } from '../errors'
import { HookParameter } from '../models/common'
/**
* @constant tts
* @description
* Transaction types
*/
/**
* @typedef TTS
* @description
* Transaction types
*/
export type TTS = typeof TRANSACTION_TYPE_MAP
/**
* Calculate the hook on
*
* @param arr - array of transaction types
* @returns the hook on
*/
export function calculateHookOn(arr: Array<keyof TTS>): string {
let hash =
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff'
arr.forEach((nth) => {
if (typeof nth !== 'string') {
throw new XrplError(`HookOn transaction type must be string`)
}
if (!TRANSACTION_TYPES.includes(String(nth))) {
throw new XrplError(
`invalid transaction type '${String(nth)}' in HookOn array`,
)
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Required
const tts: Record<string, number> = TRANSACTION_TYPE_MAP
let value = BigInt(hash)
// eslint-disable-next-line no-bitwise -- Required
value ^= BigInt(1) << BigInt(tts[nth])
// eslint-disable-next-line @typescript-eslint/no-magic-numbers -- Required
hash = `0x${value.toString(16)}`
})
hash = hash.replace('0x', '')
// eslint-disable-next-line @typescript-eslint/no-magic-numbers -- Required
hash = hash.padStart(64, '0')
return hash.toUpperCase()
}
/**
* Calculate the sha256 of a string
*
* @param string - the string to calculate the sha256
* @returns the sha256
*/
export async function sha256(string: string): Promise<string> {
const hash = createHash('sha256')
hash.update(string)
const hashBuffer = hash.digest()
const hashArray = Array.from(new Uint8Array(hashBuffer))
const hashHex = hashArray
// eslint-disable-next-line @typescript-eslint/no-magic-numbers -- Required
.map((bytes) => bytes.toString(16).padStart(2, '0'))
.join('')
return hashHex
}
/**
* Calculate the hex of a namespace
*
* @param namespace - the namespace to calculate the hex
* @returns the hex
*/
export async function hexNamespace(namespace: string): Promise<string> {
return (await sha256(namespace)).toUpperCase()
}
/**
* Calculate the hex of the hook parameters
*
* @param data - the hook parameters
* @returns the hex of the hook parameters
*/
export function hexHookParameters(data: HookParameter[]): HookParameter[] {
const hookParameters: HookParameter[] = []
for (const parameter of data) {
hookParameters.push({
HookParameter: {
HookParameterName: Buffer.from(
parameter.HookParameter.HookParameterName,
'utf8',
)
.toString('hex')
.toUpperCase(),
HookParameterValue: Buffer.from(
parameter.HookParameter.HookParameterValue,
'utf8',
)
.toString('hex')
.toUpperCase(),
},
})
}
return hookParameters
}

View File

@@ -40,6 +40,7 @@ import {
hashEscrow,
hashPaymentChannel,
} from './hashes'
import { calculateHookOn, hexNamespace, hexHookParameters, TTS } from './hooks'
import parseNFTokenID from './parseNFTokenID'
import {
percentToTransferRate,
@@ -222,4 +223,8 @@ export {
getNFTokenID,
createCrossChainPayment,
parseNFTokenID,
calculateHookOn,
hexNamespace,
hexHookParameters,
TTS,
}

View File

@@ -1,6 +1,6 @@
import { assert } from 'chai'
import getFeeXrp from '../../src/sugar/getFeeXrp'
import { getFeeXrp } from '../../src/sugar/getFeeXrp'
import rippled from '../fixtures/rippled'
import {
setupClient,

View File

@@ -0,0 +1,123 @@
import { assert } from 'chai'
import { validate, ValidationError } from '../../src'
/**
* AMMBid Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('AMMBid', function () {
let bid
beforeEach(function () {
bid = {
TransactionType: 'AMMBid',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Asset: {
currency: 'XRP',
},
Asset2: {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
},
BidMin: '5',
BidMax: '10',
AuthAccounts: [
{
AuthAccount: {
Account: 'rNZdsTBP5tH1M6GHC6bTreHAp6ouP8iZSh',
},
},
{
AuthAccount: {
Account: 'rfpFv97Dwu89FTyUwPjtpZBbuZxTqqgTmH',
},
},
{
AuthAccount: {
Account: 'rzzYHPGb8Pa64oqxCzmuffm122bitq3Vb',
},
},
{
AuthAccount: {
Account: 'rhwxHxaHok86fe4LykBom1jSJ3RYQJs1h4',
},
},
],
Sequence: 1337,
} as any
})
it(`verifies valid AMMBid`, function () {
assert.doesNotThrow(() => validate(bid))
})
it(`throws w/ missing field Asset`, function () {
delete bid.Asset
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: missing field Asset',
)
})
it(`throws w/ Asset must be an Issue`, function () {
bid.Asset = 1234
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: Asset must be an Issue',
)
})
it(`throws w/ missing field Asset2`, function () {
delete bid.Asset2
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: missing field Asset2',
)
})
it(`throws w/ Asset2 must be an Issue`, function () {
bid.Asset2 = 1234
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: Asset2 must be an Issue',
)
})
it(`throws w/ BidMin must be an Amount`, function () {
bid.BidMin = 5
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: BidMin must be an Amount',
)
})
it(`throws w/ BidMax must be an Amount`, function () {
bid.BidMax = 10
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: BidMax must be an Amount',
)
})
it(`throws w/ AuthAccounts length must not be greater than 4`, function () {
bid.AuthAccounts.push({
AuthAccount: {
Account: 'r3X6noRsvaLapAKCG78zAtWcbhB3sggS1s',
},
})
assert.throws(
() => validate(bid),
ValidationError,
'AMMBid: AuthAccounts length must not be greater than 4',
)
})
})

View File

@@ -0,0 +1,103 @@
import { assert } from 'chai'
import { validate, ValidationError } from '../../src'
/**
* AMMCreate Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('AMMCreate', function () {
let ammCreate
beforeEach(function () {
ammCreate = {
TransactionType: 'AMMCreate',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Amount: '1000',
Amount2: {
currency: 'USD',
issuer: 'rPyfep3gcLzkosKC9XiE77Y8DZWG6iWDT9',
value: '1000',
},
TradingFee: 12,
Sequence: 1337,
} as any
})
it(`verifies valid AMMCreate`, function () {
assert.doesNotThrow(() => validate(ammCreate))
})
it(`throws w/ missing Amount`, function () {
delete ammCreate.Amount
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: missing field Amount',
)
})
it(`throws w/ Amount must be an Amount`, function () {
ammCreate.Amount = 1000
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: Amount must be an Amount',
)
})
it(`throws w/ missing Amount2`, function () {
delete ammCreate.Amount2
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: missing field Amount2',
)
})
it(`throws w/ Amount2 must be an Amount`, function () {
ammCreate.Amount2 = 1000
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: Amount2 must be an Amount',
)
})
it(`throws w/ missing TradingFee`, function () {
delete ammCreate.TradingFee
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: missing field TradingFee',
)
})
it(`throws w/ TradingFee must be a number`, function () {
ammCreate.TradingFee = '12'
assert.throws(
() => validate(ammCreate),
ValidationError,
'AMMCreate: TradingFee must be a number',
)
})
it(`throws when TradingFee is greater than 1000`, function () {
ammCreate.TradingFee = 1001
assert.throws(
() => validate(ammCreate),
ValidationError,
`AMMCreate: TradingFee must be between 0 and 1000`,
)
})
it(`throws when TradingFee is a negative number`, function () {
ammCreate.TradingFee = -1
assert.throws(
() => validate(ammCreate),
ValidationError,
`AMMCreate: TradingFee must be between 0 and 1000`,
)
})
})

View File

@@ -0,0 +1,175 @@
/* eslint-disable no-bitwise -- bitwise necessary for enabling flags */
import { assert } from 'chai'
import { AMMDepositFlags, validate, ValidationError } from '../../src'
/**
* AMMDeposit Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('AMMDeposit', function () {
const LPTokenOut = {
currency: 'B3813FCAB4EE68B3D0D735D6849465A9113EE048',
issuer: 'rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg',
value: '1000',
}
let deposit
beforeEach(function () {
deposit = {
TransactionType: 'AMMDeposit',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Asset: {
currency: 'XRP',
},
Asset2: {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
},
Sequence: 1337,
Flags: 0,
} as any
})
it(`verifies valid AMMDeposit with LPTokenOut`, function () {
deposit.LPTokenOut = LPTokenOut
deposit.Flags |= AMMDepositFlags.tfLPToken
assert.doesNotThrow(() => validate(deposit))
})
it(`verifies valid AMMDeposit with Amount`, function () {
deposit.Amount = '1000'
deposit.Flags |= AMMDepositFlags.tfSingleAsset
assert.doesNotThrow(() => validate(deposit))
})
it(`verifies valid AMMDeposit with Amount and Amount2`, function () {
deposit.Amount = '1000'
deposit.Amount2 = {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
value: '2.5',
}
deposit.Flags |= AMMDepositFlags.tfTwoAsset
assert.doesNotThrow(() => validate(deposit))
})
it(`verifies valid AMMDeposit with Amount and LPTokenOut`, function () {
deposit.Amount = '1000'
deposit.LPTokenOut = LPTokenOut
deposit.Flags |= AMMDepositFlags.tfOneAssetLPToken
assert.doesNotThrow(() => validate(deposit))
})
it(`verifies valid AMMDeposit with Amount and EPrice`, function () {
deposit.Amount = '1000'
deposit.EPrice = '25'
deposit.Flags |= AMMDepositFlags.tfLimitLPToken
assert.doesNotThrow(() => validate(deposit))
})
it(`throws w/ missing field Asset`, function () {
delete deposit.Asset
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: missing field Asset',
)
})
it(`throws w/ Asset must be an Issue`, function () {
deposit.Asset = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: Asset must be an Issue',
)
})
it(`throws w/ missing field Asset2`, function () {
delete deposit.Asset2
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: missing field Asset2',
)
})
it(`throws w/ Asset2 must be an Issue`, function () {
deposit.Asset2 = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: Asset2 must be an Issue',
)
})
it(`throws w/ must set at least LPTokenOut or Amount`, function () {
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: must set at least LPTokenOut or Amount',
)
})
it(`throws w/ must set Amount with Amount2`, function () {
deposit.Amount2 = {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
value: '2.5',
}
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: must set Amount with Amount2',
)
})
it(`throws w/ must set Amount with EPrice`, function () {
deposit.EPrice = '25'
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: must set Amount with EPrice',
)
})
it(`throws w/ LPTokenOut must be an IssuedCurrencyAmount`, function () {
deposit.LPTokenOut = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: LPTokenOut must be an IssuedCurrencyAmount',
)
})
it(`throws w/ Amount must be an Amount`, function () {
deposit.Amount = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: Amount must be an Amount',
)
})
it(`throws w/ Amount2 must be an Amount`, function () {
deposit.Amount = '1000'
deposit.Amount2 = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: Amount2 must be an Amount',
)
})
it(`throws w/ EPrice must be an Amount`, function () {
deposit.Amount = '1000'
deposit.EPrice = 1234
assert.throws(
() => validate(deposit),
ValidationError,
'AMMDeposit: EPrice must be an Amount',
)
})
})

View File

@@ -0,0 +1,104 @@
import { assert } from 'chai'
import { validate, ValidationError } from '../../src'
/**
* AMMVote Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('AMMVote', function () {
let vote
beforeEach(function () {
vote = {
TransactionType: 'AMMVote',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Asset: {
currency: 'XRP',
},
Asset2: {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
},
TradingFee: 25,
Sequence: 1337,
} as any
})
it(`verifies valid AMMVote`, function () {
assert.doesNotThrow(() => validate(vote))
})
it(`throws w/ missing field Asset`, function () {
delete vote.Asset
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: missing field Asset',
)
})
it(`throws w/ Asset must be an Issue`, function () {
vote.Asset = 1234
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: Asset must be an Issue',
)
})
it(`throws w/ missing field Asset2`, function () {
delete vote.Asset2
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: missing field Asset2',
)
})
it(`throws w/ Asset2 must be an Issue`, function () {
vote.Asset2 = 1234
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: Asset2 must be an Issue',
)
})
it(`throws w/ missing field TradingFee`, function () {
delete vote.TradingFee
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: missing field TradingFee',
)
})
it(`throws w/ TradingFee must be a number`, function () {
vote.TradingFee = '25'
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: TradingFee must be a number',
)
})
it(`throws when TradingFee is greater than AMM_MAX_TRADING_FEE`, function () {
vote.TradingFee = 1001
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: TradingFee must be between 0 and 1000',
)
})
it(`throws when TradingFee is a negative number`, function () {
vote.TradingFee = -1
assert.throws(
() => validate(vote),
ValidationError,
'AMMVote: TradingFee must be between 0 and 1000',
)
})
})

View File

@@ -0,0 +1,178 @@
/* eslint-disable no-bitwise -- bitwise necessary for enabling flags */
import { assert } from 'chai'
import { AMMWithdrawFlags, validate, ValidationError } from '../../src'
/**
* AMMWithdraw Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('AMMWithdraw', function () {
const LPTokenIn = {
currency: 'B3813FCAB4EE68B3D0D735D6849465A9113EE048',
issuer: 'rH438jEAzTs5PYtV6CHZqpDpwCKQmPW9Cg',
value: '1000',
}
let withdraw
beforeEach(function () {
withdraw = {
TransactionType: 'AMMWithdraw',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Asset: {
currency: 'XRP',
},
Asset2: {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
},
Sequence: 1337,
Flags: 0,
} as any
})
it(`verifies valid AMMWithdraw with LPTokenIn`, function () {
withdraw.LPTokenIn = LPTokenIn
withdraw.Flags |= AMMWithdrawFlags.tfLPToken
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw with Amount`, function () {
withdraw.Amount = '1000'
withdraw.Flags |= AMMWithdrawFlags.tfSingleAsset
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw with Amount and Amount2`, function () {
withdraw.Amount = '1000'
withdraw.Amount2 = {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
value: '2.5',
}
withdraw.Flags |= AMMWithdrawFlags.tfTwoAsset
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw with Amount and LPTokenIn`, function () {
withdraw.Amount = '1000'
withdraw.LPTokenIn = LPTokenIn
withdraw.Flags |= AMMWithdrawFlags.tfOneAssetLPToken
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw with Amount and EPrice`, function () {
withdraw.Amount = '1000'
withdraw.EPrice = '25'
withdraw.Flags |= AMMWithdrawFlags.tfLimitLPToken
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw one asset withdraw all`, function () {
withdraw.Amount = '1000'
withdraw.Flags |= AMMWithdrawFlags.tfOneAssetWithdrawAll
assert.doesNotThrow(() => validate(withdraw))
})
it(`verifies valid AMMWithdraw withdraw all`, function () {
withdraw.Flags |= AMMWithdrawFlags.tfWithdrawAll
assert.doesNotThrow(() => validate(withdraw))
})
it(`throws w/ missing field Asset`, function () {
delete withdraw.Asset
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: missing field Asset',
)
})
it(`throws w/ Asset must be an Issue`, function () {
withdraw.Asset = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: Asset must be an Issue',
)
})
it(`throws w/ missing field Asset2`, function () {
delete withdraw.Asset2
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: missing field Asset2',
)
})
it(`throws w/ Asset2 must be an Issue`, function () {
withdraw.Asset2 = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: Asset2 must be an Issue',
)
})
it(`throws w/ must set Amount with Amount2`, function () {
withdraw.Amount2 = {
currency: 'ETH',
issuer: 'rP9jPyP5kyvFRb6ZiRghAGw5u8SGAmU4bd',
value: '2.5',
}
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: must set Amount with Amount2',
)
})
it(`throws w/ must set Amount with EPrice`, function () {
withdraw.EPrice = '25'
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: must set Amount with EPrice',
)
})
it(`throws w/ LPTokenIn must be an IssuedCurrencyAmount`, function () {
withdraw.LPTokenIn = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: LPTokenIn must be an IssuedCurrencyAmount',
)
})
it(`throws w/ Amount must be an Amount`, function () {
withdraw.Amount = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: Amount must be an Amount',
)
})
it(`throws w/ Amount2 must be an Amount`, function () {
withdraw.Amount = '1000'
withdraw.Amount2 = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: Amount2 must be an Amount',
)
})
it(`throws w/ EPrice must be an Amount`, function () {
withdraw.Amount = '1000'
withdraw.EPrice = 1234
assert.throws(
() => validate(withdraw),
ValidationError,
'AMMWithdraw: EPrice must be an Amount',
)
})
})

View File

@@ -68,6 +68,26 @@ describe('NFTokenMint', function () {
)
})
it(`throws w/ URI being an empty string`, function () {
const invalid = {
TransactionType: 'NFTokenMint',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
Fee: '5000000',
Sequence: 2470665,
Flags: NFTokenMintFlags.tfTransferable,
NFTokenTaxon: 0,
Issuer: 'r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ',
TransferFee: 1,
URI: '',
} as any
assert.throws(
() => validate(invalid),
ValidationError,
'NFTokenMint: URI must not be empty string',
)
})
it(`throws w/ URI not in hex format`, function () {
const invalid = {
TransactionType: 'NFTokenMint',

View File

@@ -0,0 +1,150 @@
import { assert } from 'chai'
import { validate, ValidationError } from '../../src'
import { validateSetHook } from '../../src/models/transactions/setHook'
/**
* SetHook Transaction Verification Testing.
*
* Providing runtime verification testing for each specific transaction type.
*/
describe('SetHook', function () {
let setHookTx
beforeEach(function () {
setHookTx = {
Flags: 0,
TransactionType: 'SetHook',
Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn',
Fee: '12',
Hooks: [
{
Hook: {
CreateCode:
'0061736D01000000011C0460057F7F7F7F7F017E60037F7F7E017E60027F7F017F60017F017E02230303656E76057472616365000003656E7606616363657074000103656E76025F670002030201030503010002062B077F0141B088040B7F004180080B7F0041A6080B7F004180080B7F0041B088040B7F0041000B7F0041010B07080104686F6F6B00030AC4800001C0800001017F230041106B220124002001200036020C41920841134180084112410010001A410022002000420010011A41012200200010021A200141106A240042000B0B2C01004180080B254163636570742E633A2043616C6C65642E00224163636570742E633A2043616C6C65642E22',
HookOn:
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFF7',
Flags: 1,
HookApiVersion: 0,
HookNamespace:
'4FF9961269BF7630D32E15276569C94470174A5DA79FA567C0F62251AA9A36B9',
},
},
],
} as any
})
it(`verifies valid SetHook`, function () {
assert.doesNotThrow(() => validateSetHook(setHookTx))
assert.doesNotThrow(() => validate(setHookTx))
})
// it(`throws w/ empty Hooks`, function () {
// setHookTx.Hooks = []
// assert.throws(
// () => validateSetHook(setHookTx),
// ValidationError,
// 'SetHook: need at least 1 member in Hooks',
// )
// assert.throws(
// () => validate(setHookTx),
// ValidationError,
// 'SetHook: need at least 1 member in Hooks',
// )
// })
it(`throws w/ invalid Hooks`, function () {
setHookTx.Hooks = 'khgfgyhujk'
assert.throws(
() => validateSetHook(setHookTx),
ValidationError,
'SetHook: invalid Hooks',
)
assert.throws(
() => validate(setHookTx),
ValidationError,
'SetHook: invalid Hooks',
)
})
it(`throws w/ maximum of 4 members allowed in Hooks`, function () {
setHookTx.Hooks = []
const hook = {
Hook: {
CreateCode:
'0061736D01000000011C0460057F7F7F7F7F017E60037F7F7E017E60027F7F017F60017F017E02230303656E76057472616365000003656E7606616363657074000103656E76025F670002030201030503010002062B077F0141B088040B7F004180080B7F0041A6080B7F004180080B7F0041B088040B7F0041000B7F0041010B07080104686F6F6B00030AC4800001C0800001017F230041106B220124002001200036020C41920841134180084112410010001A410022002000420010011A41012200200010021A200141106A240042000B0B2C01004180080B254163636570742E633A2043616C6C65642E00224163636570742E633A2043616C6C65642E22',
HookOn:
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFF7',
Flags: 1,
HookApiVersion: 0,
HookNamespace:
'4FF9961269BF7630D32E15276569C94470174A5DA79FA567C0F62251AA9A36B9',
},
}
setHookTx.Hooks.push(hook)
setHookTx.Hooks.push(hook)
setHookTx.Hooks.push(hook)
setHookTx.Hooks.push(hook)
setHookTx.Hooks.push(hook)
const errorMessage = 'SetHook: maximum of 4 hooks allowed in Hooks'
assert.throws(
() => validateSetHook(setHookTx),
ValidationError,
errorMessage,
)
assert.throws(() => validate(setHookTx), ValidationError, errorMessage)
})
it(`throws w/ invalid HookOn in Hooks`, function () {
setHookTx.SignerQuorum = 2
setHookTx.Hooks = [
{
Hook: {
CreateCode:
'0061736D01000000011C0460057F7F7F7F7F017E60037F7F7E017E60027F7F017F60017F017E02230303656E76057472616365000003656E7606616363657074000103656E76025F670002030201030503010002062B077F0141B088040B7F004180080B7F0041A6080B7F004180080B7F0041B088040B7F0041000B7F0041010B07080104686F6F6B00030AC4800001C0800001017F230041106B220124002001200036020C41920841134180084112410010001A410022002000420010011A41012200200010021A200141106A240042000B0B2C01004180080B254163636570742E633A2043616C6C65642E00224163636570742E633A2043616C6C65642E22',
HookOn: '',
Flags: 1,
HookApiVersion: 0,
HookNamespace:
'4FF9961269BF7630D32E15276569C94470174A5DA79FA567C0F62251AA9A36B9',
},
},
]
const errorMessage =
'SetHook: HookOn in Hook must be a 256-bit (32-byte) hexadecimal value'
assert.throws(
() => validateSetHook(setHookTx),
ValidationError,
errorMessage,
)
assert.throws(() => validate(setHookTx), ValidationError, errorMessage)
})
it(`throws w/ invalid HookNamespace in Hooks`, function () {
setHookTx.SignerQuorum = 2
setHookTx.Hooks = [
{
Hook: {
CreateCode:
'0061736D01000000011C0460057F7F7F7F7F017E60037F7F7E017E60027F7F017F60017F017E02230303656E76057472616365000003656E7606616363657074000103656E76025F670002030201030503010002062B077F0141B088040B7F004180080B7F0041A6080B7F004180080B7F0041B088040B7F0041000B7F0041010B07080104686F6F6B00030AC4800001C0800001017F230041106B220124002001200036020C41920841134180084112410010001A410022002000420010011A41012200200010021A200141106A240042000B0B2C01004180080B254163636570742E633A2043616C6C65642E00224163636570742E633A2043616C6C65642E22',
HookOn:
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFF7',
Flags: 1,
HookApiVersion: 0,
HookNamespace: '',
},
},
]
const errorMessage =
'SetHook: HookNamespace in Hook must be a 256-bit (32-byte) hexadecimal value'
assert.throws(
() => validateSetHook(setHookTx),
ValidationError,
errorMessage,
)
assert.throws(() => validate(setHookTx), ValidationError, errorMessage)
})
})

View File

@@ -0,0 +1,64 @@
import { assert } from 'chai'
import {
calculateHookOn,
hexNamespace,
hexHookParameters,
TTS,
} from '../../src'
describe('test hook on', function () {
it('invalid', function () {
const invokeOn: Array<keyof TTS> = ['AccountSet1']
expect(() => {
calculateHookOn(invokeOn)
}).toThrow("invalid transaction type 'AccountSet1' in HookOn array")
})
it('all', function () {
const result = calculateHookOn([])
assert.equal(
result,
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFF',
)
})
it('one', function () {
const invokeOn: Array<keyof TTS> = ['AccountSet']
const result = calculateHookOn(invokeOn)
assert.equal(
result,
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFF7',
)
})
})
describe('test hook namespace', function () {
it('basic', async function () {
const result = await hexNamespace('starter')
assert.equal(
result,
'4FF9961269BF7630D32E15276569C94470174A5DA79FA567C0F62251AA9A36B9',
)
})
})
describe('test hook parameters', function () {
it('basic', async function () {
const parameters = [
{
HookParameter: {
HookParameterName: 'name1',
HookParameterValue: 'value1',
},
},
]
const result = hexHookParameters(parameters)
assert.deepEqual(result, [
{
HookParameter: {
HookParameterName: '6E616D6531',
HookParameterValue: '76616C756531',
},
},
])
})
})

View File

@@ -864,6 +864,171 @@ describe('Wallet', function () {
assert.deepEqual(result, expectedResult)
})
it('sign throws when NFTokenMint.URI is empty string', async function () {
const tx: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
URI: '',
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
assert.throws(() => {
wallet.sign(tx)
}, /URI must not be empty string/u)
})
it('sign removes undefined NFTokenMint.URI property from transaction blob', async function () {
const tx: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
URI: undefined,
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result = wallet.sign(tx)
const decodedTx = decode(result.tx_blob) as unknown as NFTokenMint
assert.notExists(decodedTx.URI)
})
it('sign removes nulled NFTokenMint.URI property from transaction blob', async function () {
const tx: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
URI: null,
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result = wallet.sign(tx)
const decodedTx = decode(result.tx_blob) as unknown as NFTokenMint
assert.notExists(decodedTx.URI)
})
it('sign allows undefined value for NFTokenMint.URI', async function () {
// transaction with explicit URI: undefined
const tx_1: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
URI: undefined,
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result_1 = wallet.sign(tx_1)
// transaction with no URI
const tx_2: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result_2 = wallet.sign(tx_2)
assert.deepEqual(result_1, result_2)
})
it('sign allows nulled value for NFTokenMint.URI', async function () {
// transaction with explicit URI: null
const tx_1: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
URI: null,
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result_1 = wallet.sign(tx_1)
// transaction with no URI
const tx_2: NFTokenMint = {
TransactionType: 'NFTokenMint',
Account: wallet.address,
TransferFee: 314,
NFTokenTaxon: 0,
Flags: 8,
Fee: '10',
Memos: [
{
Memo: {
MemoType:
'687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963',
MemoData: '72656e74',
},
},
],
}
const result_2 = wallet.sign(tx_2)
assert.deepEqual(result_1, result_2)
})
it('sign allows lowercase hex value for NFTokenMint.URI', async function () {
const tx: NFTokenMint = {
TransactionType: 'NFTokenMint',
@@ -915,7 +1080,7 @@ describe('Wallet', function () {
assert.throws(() => {
wallet.sign(tx)
}, /URI must be a hex value/u)
}, /URI must be in hex format/u)
})
})

View File

@@ -139,7 +139,9 @@ describe('Signer', function () {
it('multisign runs successfully with tx_blobs', function () {
const transactions = [multisignTxToCombine1, multisignTxToCombine2]
const encodedTransactions: string[] = transactions.map(encode)
const encodedTransactions: string[] = transactions.map((transaction) =>
encode(transaction),
)
assert.deepEqual(multisign(encodedTransactions), expectedMultisign)
})