-
Notifications
You must be signed in to change notification settings - Fork 512
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MPT #2661
base: main
Are you sure you want to change the base?
MPT #2661
Conversation
"temBAD_MPTOKEN_TRANSFER_FEE": -261, | ||
"temBAD_AMM_TOKENS": -260, | ||
"temXCHAIN_EQUAL_DOOR_ACCOUNTS": -259, | ||
"temXCHAIN_BAD_PROOF": -258, | ||
"temXCHAIN_BRIDGE_BAD_ISSUES": -257, | ||
"temXCHAIN_BRIDGE_NONDOOR_OWNER": -256, | ||
"temXCHAIN_BRIDGE_BAD_MIN_ACCOUNT_CREATE_AMOUNT": -255, | ||
"temXCHAIN_BRIDGE_BAD_REWARD_AMOUNT": -254, | ||
"temEMPTY_DID": -253, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This changes all the numbers, which isn't backwards-compatible.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
From the README, I thought auto-generating this is sufficient, or do I need to manually add them?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Auto-generating is sufficient, I'm saying this is a rippled problem.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is only a problem if you plan to merge this PR in as-is - if it's just for a beta version or something, it doesn't really matter.
packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts
Outdated
Show resolved
Hide resolved
@CodeRabbit full review |
@coderabbitai full review |
Actions performedFull review triggered. |
WalkthroughThe changes in this pull request involve extensive updates to the Ripple binary codec and XRPL packages. Key modifications include the introduction of new types and interfaces for multi-party tokens (MPTs), enhanced handling of amounts, and the addition of new transaction models related to MPT operations. The updates also include renaming existing types, expanding validation logic, and enhancing serialization/deserialization processes. Additionally, numerous test cases have been added or updated to ensure comprehensive coverage of the new functionalities. Changes
Possibly related PRs
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 38
🧹 Outside diff range and nitpick comments (48)
packages/xrpl/src/models/ledger/MPToken.ts (1)
5-12
: LGTM: Well-structured interface with a minor suggestion.The
MPToken
interface is well-defined and makes good use of TypeScript features such as inheritance (or composition) throughextends
, optional properties, and string literal types. This structure provides both flexibility and type safety.Consider adding JSDoc comments for each property to improve code documentation and developer experience. For example:
export interface MPToken extends BaseLedgerEntry, HasPreviousTxnID { /** The type of the ledger entry, always 'MPToken' for this interface */ LedgerEntryType: 'MPToken' /** The unique identifier for the MPToken issuance */ MPTokenIssuanceID: string /** The amount of the MPToken */ MPTAmount: MPTAmount /** The amount of the MPToken that is locked, if any */ LockedAmount?: MPTAmount /** Flags associated with the MPToken */ Flags: number /** The owner node of the MPToken, if applicable */ OwnerNode?: string }This addition would greatly enhance the self-documentation of the code.
packages/ripple-binary-codec/src/types/hash-192.ts (2)
7-8
: LGTM: Static properties are well-defined.The
width
andZERO_192
properties are correctly implemented. The use ofreadonly
forZERO_192
is a good practice to prevent accidental modifications.Consider adding a brief comment explaining the significance of the
width
value:/** Number of bytes for a 192-bit hash */ static readonly width = 24
10-16
: LGTM: Constructor implementation is robust.The constructor handles various input scenarios well, ensuring a valid hash is always created. The use of the nullish coalescing operator is a nice touch for conciseness.
For improved clarity, consider simplifying the constructor logic:
constructor(bytes?: Uint8Array) { super(bytes?.length ? bytes : Hash192.ZERO_192.bytes) }This achieves the same result with a more concise expression.
packages/xrpl/test/models/MPTokenIssuanceDestroy.test.ts (1)
13-21
: Consider adding more assertions for the valid case.While checking that no exception is thrown is good, consider adding more specific assertions to verify the structure or properties of the validated object. This could provide more comprehensive validation.
packages/xrpl/src/models/transactions/MPTokenIssuanceDestroy.ts (2)
8-21
: LGTM: Well-structured interface with clear documentation.The
MPTokenIssuanceDestroy
interface is well-defined and extendsBaseTransaction
appropriately. The JSDoc comment provides clear information about the transaction's purpose and behavior.Consider adding a brief comment for the
MPTokenIssuanceID
field to explain its format or any constraints, if applicable. For example:/** * Identifies the MPTokenIssuance object to be removed by the transaction. * This should be a valid MPTokenIssuance identifier in the ledger. */ MPTokenIssuanceID: string
23-34
: LGTM: Well-implemented validation function with clear documentation.The
validateMPTokenIssuanceDestroy
function is well-structured and properly validates both the base transaction and the requiredMPTokenIssuanceID
field. The use ofRecord<string, unknown>
as the input type allows for flexible input while maintaining type safety.Consider enhancing the error handling to provide more specific error messages. This could be achieved by wrapping the validation calls in try-catch blocks and rethrowing with more context. For example:
export function validateMPTokenIssuanceDestroy( tx: Record<string, unknown>, ): void { try { validateBaseTransaction(tx) } catch (error) { throw new Error(`Invalid MPTokenIssuanceDestroy base transaction: ${error.message}`) } try { validateRequiredField(tx, 'MPTokenIssuanceID', isString) } catch (error) { throw new Error(`Invalid MPTokenIssuanceID: ${error.message}`) } }This change would provide more specific error messages, making it easier to debug issues with MPTokenIssuanceDestroy transactions.
packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts (1)
46-47
: Consider addressing the@ts-ignore
comment.The use of
@ts-ignore
suggests a potential type mismatch or incomplete type definition. It would be beneficial to investigate the root cause and, if possible, address it without suppressing the TypeScript check.Consider the following options:
- If the type definition for
account_objects
is incomplete, update it to include theMaximumAmount
property.- If the property is optional, use optional chaining:
accountObjectsResponse.result.account_objects?.[0]?.MaximumAmount
.- If the structure is guaranteed but TypeScript can't infer it, use a type assertion instead:
(accountObjectsResponse.result.account_objects[0] as { MaximumAmount: string }).MaximumAmountpackages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts (4)
32-54
: Consider adding error handling for transaction submission and metadata retrieval.While the MPTokenIssuanceCreate transaction setup is correct, it's advisable to add error handling for potential failures in transaction submission or metadata retrieval. This will make the test more robust and easier to debug if issues arise.
Consider wrapping the transaction submission and metadata retrieval in try-catch blocks, or use assertions to check for expected properties before accessing them. For example:
const mptCreateRes = await testTransaction(testContext.client, createTx, testContext.wallet); assert(mptCreateRes.result.tx_json.hash, 'Transaction hash should be present'); const txResponse = await testContext.client.request({ command: 'tx', transaction: mptCreateRes.result.tx_json.hash, }); assert(txResponse.result.meta, 'Transaction metadata should be present'); const meta = txResponse.result.meta as TransactionMetadata<MPTokenIssuanceCreate>; assert(meta.mpt_issuance_id, 'mpt_issuance_id should be present in metadata');
56-65
: Enhance verification of the MPT issuance object.While the test correctly verifies the presence of one issuance object, it would be beneficial to add more specific checks on the properties of this object. This would ensure that the issuance was created with the expected attributes.
Consider adding assertions to verify specific properties of the issuance object. For example:
const issuanceObject = accountObjectsResponse.result.account_objects![0]; assert.equal(issuanceObject.MPTokenIssuanceID, mptID, 'MPTokenIssuanceID should match'); assert.equal(issuanceObject.Flags, MPTokenIssuanceCreateFlags.tfMPTCanLock, 'Flags should match');
67-74
: Add verification steps after MPTokenIssuanceSet transaction.The MPTokenIssuanceSet transaction is correctly created and sent, but the test doesn't verify its effects. To ensure the transaction had the intended impact, consider adding verification steps after the transaction is processed.
Add assertions to verify the effects of the MPTokenIssuanceSet transaction. For example:
await testTransaction(testContext.client, setTx, testContext.wallet); // Verify the effects of the set transaction const updatedAccountObjects = await testContext.client.request({ command: 'account_objects', account: testContext.wallet.classicAddress, type: 'mpt_issuance', }); const updatedIssuance = updatedAccountObjects.result.account_objects![0]; assert.equal(updatedIssuance.Flags & MPTokenIssuanceSetFlags.tfMPTLock, MPTokenIssuanceSetFlags.tfMPTLock, 'MPT should be locked after set transaction');
21-78
: Expand test coverage and clarify file scope.The current test file provides a good base case for MPTokenIssuanceSet, but there's room for improvement in terms of test coverage and file organization.
Consider the following suggestions:
Add more test cases to cover edge cases and potential error scenarios. For example:
- Attempting to set an issuance that doesn't exist
- Setting an issuance with invalid flags
- Attempting to modify a locked issuance
Clarify the scope of this test file. If it's meant to cover both MPTokenIssuanceCreate and MPTokenIssuanceSet, consider renaming the file to reflect this broader scope. Alternatively, if the focus is solely on MPTokenIssuanceSet, move the creation logic to a separate setup function or file.
Add comments explaining the purpose of each test case and the expected behavior being verified.
These changes will enhance the robustness and clarity of your test suite.
packages/xrpl/test/models/MPTokenAuthorize.test.ts (2)
13-58
: LGTM: Comprehensive test case for valid MPTokenAuthorize transactions.The test case covers various valid configurations of the MPTokenAuthorize transaction, including different combinations of required and optional fields. This approach ensures robust validation of the transaction structure.
However, consider the following suggestion:
Instead of using
as any
type assertions, consider creating a partial type for the test objects. This can provide better type safety while still allowing flexibility in the test cases. For example:type PartialMPTokenAuthorize = Partial<MPTokenAuthorize> & { TransactionType: 'MPTokenAuthorize' }; const validMPTokenAuthorize: PartialMPTokenAuthorize = { TransactionType: 'MPTokenAuthorize', Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', MPTokenIssuanceID: TOKEN_ID, };This approach maintains type safety while allowing you to test partial objects.
🧰 Tools
🪛 Gitleaks
25-25: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
53-53: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
60-71
: LGTM: Good negative test case, but consider adding more scenarios.The test case correctly verifies that a ValidationError is thrown when the required MPTokenIssuanceID field is missing. The specific error message is helpful for debugging.
To improve test coverage:
Consider adding more negative test cases to cover other potential validation errors, such as:
- Invalid Account address
- Invalid MPTokenIssuanceID format
- Invalid Flags value
- Missing Account field
Example:
it('throws w/ invalid Account address', function () { const invalid = { TransactionType: 'MPTokenAuthorize', Account: 'invalid_address', MPTokenIssuanceID: TOKEN_ID, }; assert.throws( () => validate(invalid), ValidationError, 'MPTokenAuthorize: invalid Account address' ); });Adding these cases would provide more comprehensive validation testing.
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (3)
13-41
: LGTM: Comprehensive test cases for valid MPTokenIssuanceSet.The test cases cover various scenarios, including required fields, optional fields, and the case without flags. This provides good coverage for the validation logic.
Consider replacing the
as any
type assertions with proper typing to catch potential type errors at compile-time. For example:import { MPTokenIssuanceSet } from '../../src' // ... let validMPTokenIssuanceSet: MPTokenIssuanceSet = { // ... object properties ... }This change would provide better type safety and catch potential issues earlier in the development process.
🧰 Tools
🪛 Gitleaks
26-26: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
37-37: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
43-54
: LGTM: Proper error handling for missing MPTokenIssuanceID.The test case correctly verifies that the validation throws an error when the required MPTokenIssuanceID field is missing. The error message is specific and helpful.
As mentioned earlier, consider replacing the
as any
type assertion with proper typing:import { MPTokenIssuanceSet } from '../../src' // ... const invalid: Partial<MPTokenIssuanceSet> = { TransactionType: 'MPTokenIssuanceSet', Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', }This change would provide better type safety while still allowing for the intentional omission of the required field for testing purposes.
56-70
: LGTM: Proper error handling for conflicting flags.The test case correctly verifies that the validation throws an error when conflicting flags (tfMPTLock and tfMPTUnlock) are set. The use of bitwise OR to set conflicting flags is an effective way to test this scenario.
As suggested in previous comments, consider replacing the
as any
type assertion with proper typing:import { MPTokenIssuanceSet } from '../../src' // ... const invalid: MPTokenIssuanceSet = { TransactionType: 'MPTokenIssuanceSet', Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', MPTokenIssuanceID: TOKEN_ID, Flags: MPTokenIssuanceSetFlags.tfMPTLock | MPTokenIssuanceSetFlags.tfMPTUnlock, }This change would provide better type safety while still allowing for the intentional setting of conflicting flags for testing purposes.
packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts (4)
27-51
: LGTM: MPTokenIssuanceCreate transaction is well-implemented.The creation of the MPToken issuance and retrieval of the
mpt_issuance_id
are correctly implemented. Good use of helper functions for transaction submission.Consider adding a comment explaining the significance of
mpt_issuance_id
for clarity:// Extract mpt_issuance_id from metadata, required for subsequent destroy operation const mptID = meta.mpt_issuance_id
53-62
: LGTM: Proper verification of MPToken issuance creation.The test correctly verifies the creation of the MPToken issuance by querying account objects and asserting the presence of exactly one issuance.
Consider enhancing the verification by also checking the specific properties of the created issuance:
assert.lengthOf( accountObjectsResponse.result.account_objects!, 1, 'Should be exactly one issuance on the ledger', ) const createdIssuance = accountObjectsResponse.result.account_objects![0] assert.equal(createdIssuance.MPTokenIssuanceID, mptID, 'Issuance ID should match')
64-84
: LGTM: MPTokenIssuanceDestroy transaction and verification are well-implemented.The test correctly creates and submits the MPTokenIssuanceDestroy transaction, followed by appropriate verification of the issuance removal.
Consider adding a short delay before the final verification to ensure the ledger has been updated:
await testTransaction(testContext.client, destroyTx, testContext.wallet) // Add a short delay to ensure ledger update await new Promise((resolve) => setTimeout(resolve, 1000)) accountObjectsResponse = await testContext.client.request({ // ... (rest of the code remains the same) })This can help prevent potential race conditions in the test.
1-85
: Overall: Well-structured and comprehensive test for MPTokenIssuanceDestroy.This test file effectively covers the lifecycle of an MPToken issuance, including creation, verification, destruction, and final verification. The code is well-organized and follows good testing practices.
To further enhance the test suite:
- Consider adding edge cases, such as attempting to destroy a non-existent issuance or an issuance owned by a different account.
- If applicable, add tests for different MPToken configurations to ensure the destroy operation works correctly in various scenarios.
- Consider extracting common setup steps (like creating an initial issuance) into a shared helper function to promote code reuse if similar tests are needed for other MPToken operations.
packages/xrpl/src/models/transactions/metadata.ts (1)
86-88
: LGTM: TransactionMetadataBase interface updated correctly.The
DeliveredAmount
anddelivered_amount
properties have been correctly updated to includeMPTAmount
, allowing the interface to handle Multi-Party Token amounts. This is consistent with the newMPTAmount
type import.Consider adding a brief comment explaining the
MPTAmount
type, similar to the existing comment for the 'unavailable' option. This would improve code documentation:DeliveredAmount?: Amount | MPTAmount // MPTAmount for Multi-Party Token transactionspackages/xrpl/test/models/MPTokenIssuanceCreate.test.ts (4)
16-28
: LGTM: Valid test case for MPTokenIssuanceCreate.This test case effectively verifies a valid MPTokenIssuanceCreate object with all required fields. The use of the maximum possible value for MaximumAmount is a good edge case to test.
Consider adding another test case with the minimum valid amount to ensure both extremes are covered.
45-58
: LGTM: Proper validation for non-hex MPTokenMetadata.This test case effectively verifies that non-hex MPTokenMetadata triggers a ValidationError with an appropriate error message. The use of assert.throws is correct for this negative test case.
Consider adding test cases for edge cases such as:
- A string that's partially hex (e.g., "abcd123g").
- An empty hex string ("").
- A very long hex string to test any potential length limitations.
60-96
: LGTM: Comprehensive validation for Invalid MaximumAmount.This test case effectively covers multiple scenarios for invalid MaximumAmount values, including exceeding the maximum value, negative value, and non-numeric hex value. The use of assert.throws is correct for these negative test cases.
Consider the following improvements:
- Split this into three separate test cases for better isolation and easier debugging.
- Add a test case for a MaximumAmount of '0', if it's considered invalid.
- Consider testing with decimal values (e.g., '1.5') to ensure they're properly handled or rejected.
1-97
: Overall, excellent test coverage for MPTokenIssuanceCreate validation.This test suite provides comprehensive coverage of the validation logic for the MPTokenIssuanceCreate transaction. It includes both positive and negative test cases, covering various scenarios and edge cases.
Consider the following improvements to further enhance the test suite:
- Add tests for other fields like AssetScale and TransferFee to ensure their validation is also covered.
- Consider using a test data provider or parameterized tests to reduce code duplication, especially for negative test cases.
- Add tests for any potential interactions between fields, if applicable (e.g., does the presence of certain flags affect the validation of other fields?).
- Ensure that all possible MPTokenIssuanceCreateFlags are tested, both individually and in combination.
packages/ripple-binary-codec/src/types/serialized-type.ts (1)
70-70
: Approved change, with suggestions for documentation and subclass consideration.The addition of the optional
_fieldName
parameter to thetoJSON
method is a good change that maintains backward compatibility. However, there are a couple of points to consider:
- The JSDoc comment above the method should be updated to include documentation for the new
_fieldName
parameter.- It might be worth reviewing if any subclasses of
SerializedType
need to override this method to make use of the new_fieldName
parameter.Here's a suggested update for the JSDoc comment:
/** * Return the JSON representation of a SerializedType * * @param _definitions rippled definitions used to parse the values of transaction types and such. * Unused in default, but used in STObject, STArray * Can be customized for sidechains and amendments. * @param _fieldName Optional field name, can be used by subclasses for field-specific serialization. * @returns any type, if not overloaded returns hexString representation of bytes */packages/xrpl/src/models/transactions/index.ts (1)
1-1
: LGTM. Consider updating documentation.The addition of
isMPTAmount
to the export statement is consistent with the introduction of Multi-Party Token (MPT) functionality. This change doesn't break existing exports and aligns with the PR objectives.Consider updating the relevant documentation to reflect the new
isMPTAmount
export and its usage.packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (2)
34-67
: Suggestion: Specify 'mpt_issuance' type in account_objects request.The MPTokenIssuanceCreate transaction and verification look good. However, to make the account_objects request more specific and efficient, consider adding a 'type' parameter:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: testContext.wallet.classicAddress, type: 'mpt_issuance', })This ensures we're only retrieving MPT issuance objects, making the test more focused and potentially faster.
69-87
: Suggestion: Specify 'mptoken' type in account_objects request.The MPTokenAuthorize transactions and verifications are well-implemented. To make the account_objects request more specific after the initial authorization, consider adding a 'type' parameter:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: wallet2.classicAddress, type: 'mptoken', })This ensures we're only retrieving MPToken objects, making the test more focused and potentially faster.
packages/xrpl/src/models/utils/flags.ts (1)
20-22
: LGTM! Consider grouping related imports.The new imports for MPToken-related flags are correctly added and consistent with the existing import style. This addition supports the integration of Multi-Party Token (MPT) functionality.
For improved readability and organization, consider grouping these related imports together:
import { MPTokenAuthorizeFlags } from '../transactions/MPTokenAuthorize' import { MPTokenIssuanceCreateFlags } from '../transactions/MPTokenIssuanceCreate' import { MPTokenIssuanceSetFlags } from '../transactions/MPTokenIssuanceSet'packages/ripple-binary-codec/test/hash.test.ts (1)
61-86
: LGTM: Comprehensive test suite for Hash192The new test suite for
Hash192
is well-structured and covers essential functionality:
- Static width member check
- ZERO_192 member validation
- Comparison functionality
- Error handling for invalid hash lengths
The tests are consistent with existing test suites for other hash types, which is good for maintainability.
Consider adding a test case for the
toJSON()
method of a non-zeroHash192
instance to ensure proper serialization, similar to the tests for other hash types.packages/xrpl/src/models/transactions/payment.ts (1)
119-119
: LGTM: Payment interface updated correctly. Consider updating the comment.The addition of
MPTAmount
as an alternative type for theAmount
field enhances the flexibility of the Payment interface, likely to support multi-party token transactions. This change is consistent with the import modifications.Consider updating the comment above the
Amount
field to reflect the newMPTAmount
type option. For example:/** * The amount of currency to deliver. For non-XRP amounts, the nested field * names MUST be lower-case. If the tfPartialPayment flag is set, deliver up * to this amount instead. Can also be an MPTAmount for multi-party token transactions. */ Amount: Amount | MPTAmountpackages/xrpl/src/models/transactions/transaction.ts (1)
Line range hint
93-341
: Summary: Multi-Party Token (MPT) functionality successfully integrated.The changes in this file successfully introduce Multi-Party Token (MPT) functionality to the transaction system. The additions include:
- New imports for MPT-related modules
- Updates to the
SubmittableTransaction
type to include new MPT transaction types- Extensions to the
validate
function to handle the new MPT transaction typesThese changes are well-integrated, following existing code patterns and maintaining consistency with the current implementation. The additions enhance the transaction system's capabilities without disrupting existing functionality.
Consider updating the documentation for the
Transaction
andSubmittableTransaction
types to reflect the new MPT-related transaction types. This will help maintain clear and up-to-date documentation for developers using this library.packages/ripple-binary-codec/test/binary-parser.test.ts (2)
211-216
: LGTM: Improved test naming for clarity.The renaming of the test description variable from
testName
tohexToJsonTestName
enhances the clarity of the test's purpose. This change accurately reflects that the test is parsing hex values into JSON format.For consistency, consider using camelCase for the variable name:
hexToJsonTestName
->hexToJsonTestName
.
227-235
: LGTM: Added bidirectional validation for amount parsing.The addition of a new test case to validate JSON to hex conversion complements the existing hex to JSON test. This enhancement provides comprehensive bidirectional validation for amount parsing and serialization, improving the overall test coverage.
For consistency with the previous test naming, consider renaming
jsonToHexTestName
tojsonToHexTestName
.packages/xrpl/src/models/transactions/clawback.ts (1)
25-26
: Grammatical correction in theAmount
field documentationThe description for the
Amount
field contains a grammatical error. The phrase "whom to be clawed back" should be "who is to be clawed back" for proper grammar.Apply the following diff to correct the documentation:
* names MUST be lower-case. If the amount is IOU, the `issuer` field MUST be the holder's address, - * whom to be clawed back. + * who is to be clawed back.packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (1)
51-52
: Fix typo in documentation commentThe JSDoc comment for
MPTokenHolder
has a typo: "this transaction will apply to all any accounts holding MPTs." Please correct it to "this transaction will apply to all accounts holding MPTs."packages/ripple-binary-codec/test/amount.test.ts (2)
31-32
: Correct grammatical errors in commentsThe comments at lines 31 and 32 contain grammatical errors. The phrase should be "it is not valid" instead of "it not valid".
69-70
: Correct grammatical errors in commentsThe comments at lines 69 and 70 contain grammatical errors. The phrase should be "it is not valid" instead of "it not valid".
packages/xrpl/test/models/clawback.test.ts (3)
96-112
: Clarify variable name for better readabilityThe variable
invalidAccount
is used to represent a transaction with an invalidMPTokenHolder
account. To improve clarity, consider renaming the variable toinvalidMPTokenHolderAccount
to more accurately reflect the nature of the invalidity being tested.🧰 Tools
🪛 Gitleaks
104-104: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
114-129
: Improve test description and variable namingIn this test case, the transaction is missing the
MPTokenHolder
field, but the variable is namedinvalidAccount
. To enhance readability, consider renaming it tomissingMPTokenHolder
. Additionally, update the test description to something likethrows w/ missing MPTokenHolder
for consistency.
131-148
: Ensure consistent capitalization in error messagesThe error message
'Clawback: cannot have MPTokenHolder for currency'
uses lowercase at the beginning of the sentence. For consistency and professionalism, consider capitalizing the first word:- 'Clawback: cannot have MPTokenHolder for currency', + 'Clawback: Cannot have MPTokenHolder for currency',🧰 Tools
🪛 Gitleaks
140-140: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (1)
7-7
: Consider renamingSANITY_CHECK
toINTEGER_REGEX
for clarityThe variable name
SANITY_CHECK
is not very descriptive. Renaming it toINTEGER_REGEX
would make its purpose clearer and improve code readability.Apply this change:
-const SANITY_CHECK = /^[0-9]+$/u +const INTEGER_REGEX = /^[0-9]+$/upackages/xrpl/test/integration/transactions/payment.test.ts (1)
112-112
: Remove trailing whitespace in test descriptionThe test description contains an extra space at the end. Consider removing it for consistency and cleanliness.
- 'Validate MPT Payment ', + 'Validate MPT Payment',packages/xrpl/test/integration/transactions/clawback.test.ts (1)
121-123
: Provide a more descriptive test case name.Consider renaming the test case from
'MPToken'
to something more descriptive, such as'MPToken Clawback Functionality'
, to clearly convey the purpose of the test.packages/ripple-binary-codec/src/types/amount.ts (1)
Line range hint
51-60
: Specify parameter type and validate property types inisAmountObjectIOU
The function
isAmountObjectIOU
lacks a parameter type, which may lead to type safety issues. Additionally, it doesn't check the types ofvalue
,currency
, andissuer
. To improve type safety and ensure proper validation, consider specifying the parameter type and checking property types.Apply this change:
-function isAmountObjectIOU(arg): arg is AmountObjectIOU { +function isAmountObjectIOU(arg: any): arg is AmountObjectIOU { const keys = Object.keys(arg).sort() return ( keys.length === 3 && keys[0] === 'currency' && keys[1] === 'issuer' && keys[2] === 'value' + && typeof arg.value === 'string' + && typeof arg.currency === 'string' + && typeof arg.issuer === 'string' ) }packages/xrpl/src/models/transactions/common.ts (2)
63-63
: Consider renamingMPTOKEN_SIZE
toMPT_AMOUNT_SIZE
for consistencyTo maintain consistency with existing constants like
ISSUED_CURRENCY_SIZE
andISSUE_SIZE
, consider renamingMPTOKEN_SIZE
toMPT_AMOUNT_SIZE
.Apply this diff:
-const MPTOKEN_SIZE = 2 +const MPT_AMOUNT_SIZE = 2And update any references to
MPTOKEN_SIZE
accordingly.
125-129
: Clarify documentation to specifyMPTAmount
In the JSDoc comment for
isMPTAmount
, replace "an MPT" with "an MPTAmount" to enhance clarity and maintain consistency with other function comments.Apply this diff:
/** - * Verify the form and type of an MPT at runtime. + * Verify the form and type of an MPTAmount at runtime. * * @param input - The input to check the form and type of. * @returns Whether the MPTAmount is properly formed. */
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (43)
- packages/ripple-binary-codec/src/enums/definitions.json (12 hunks)
- packages/ripple-binary-codec/src/types/amount.ts (12 hunks)
- packages/ripple-binary-codec/src/types/hash-192.ts (1 hunks)
- packages/ripple-binary-codec/src/types/index.ts (3 hunks)
- packages/ripple-binary-codec/src/types/serialized-type.ts (1 hunks)
- packages/ripple-binary-codec/src/types/st-object.ts (4 hunks)
- packages/ripple-binary-codec/src/types/uint-64.ts (4 hunks)
- packages/ripple-binary-codec/test/amount.test.ts (3 hunks)
- packages/ripple-binary-codec/test/binary-parser.test.ts (3 hunks)
- packages/ripple-binary-codec/test/fixtures/data-driven-tests.json (2 hunks)
- packages/ripple-binary-codec/test/hash.test.ts (2 hunks)
- packages/ripple-binary-codec/test/uint.test.ts (3 hunks)
- packages/xrpl/HISTORY.md (1 hunks)
- packages/xrpl/src/client/partialPayment.ts (2 hunks)
- packages/xrpl/src/models/common/index.ts (1 hunks)
- packages/xrpl/src/models/ledger/LedgerEntry.ts (1 hunks)
- packages/xrpl/src/models/ledger/MPToken.ts (1 hunks)
- packages/xrpl/src/models/ledger/MPTokenIssuance.ts (1 hunks)
- packages/xrpl/src/models/ledger/index.ts (2 hunks)
- packages/xrpl/src/models/methods/ledgerEntry.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenAuthorize.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceDestroy.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (1 hunks)
- packages/xrpl/src/models/transactions/clawback.ts (3 hunks)
- packages/xrpl/src/models/transactions/common.ts (4 hunks)
- packages/xrpl/src/models/transactions/index.ts (2 hunks)
- packages/xrpl/src/models/transactions/metadata.ts (4 hunks)
- packages/xrpl/src/models/transactions/payment.ts (3 hunks)
- packages/xrpl/src/models/transactions/transaction.ts (3 hunks)
- packages/xrpl/src/models/utils/flags.ts (2 hunks)
- packages/xrpl/test/integration/transactions/clawback.test.ts (3 hunks)
- packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/payment.test.ts (2 hunks)
- packages/xrpl/test/models/MPTokenAuthorize.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenIssuanceCreate.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenIssuanceDestroy.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (1 hunks)
- packages/xrpl/test/models/clawback.test.ts (1 hunks)
- packages/xrpl/test/models/payment.test.ts (1 hunks)
🧰 Additional context used
🪛 Gitleaks
packages/ripple-binary-codec/test/uint.test.ts
123-123: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/MPTokenAuthorize.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
25-25: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
53-53: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/MPTokenIssuanceDestroy.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
26-26: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
37-37: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/clawback.test.ts
90-90: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
104-104: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
140-140: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🔇 Additional comments (105)
packages/xrpl/src/models/ledger/MPToken.ts (1)
1-3
: LGTM: Import statements are appropriate and well-structured.The import statements are concise and import only the necessary types. The use of relative paths suggests a well-organized project structure.
packages/xrpl/src/models/ledger/MPTokenIssuance.ts (1)
1-1
: LGTM: Import statement is correct.The import statement correctly imports the necessary interfaces (BaseLedgerEntry and HasPreviousTxnID) from the relative path './BaseLedgerEntry'.
packages/ripple-binary-codec/src/types/hash-192.ts (3)
1-6
: LGTM: Import and class declaration look good.The import statement, class declaration, and JSDoc comment are well-structured and provide clear information about the purpose and inheritance of the
Hash192
class.
19-19
: LGTM: Export statement is correct.The named export of the
Hash192
class is properly implemented, allowing for easy import and use in other modules.
1-19
: Overall assessment: Well-implemented Hash192 class.The
Hash192
class is a solid implementation of a 192-bit hash, extending the baseHash
class. It correctly handles various input scenarios, provides useful static properties, and follows good coding practices. The class should integrate well with the existing codebase and provides a clear interface for working with 192-bit hashes.To ensure this new class is being used correctly in the project, let's check for its usage:
This will help verify that the
Hash192
class is being utilized as intended and that there are no conflicting implementations.✅ Verification successful
Verification successful: Hash192 class is properly utilized.
The
Hash192
class is correctly implemented and is consistently used throughout the project without any conflicting 192-bit hash implementations. It integrates seamlessly with the existing codebase, ensuring reliable functionality.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for usage of Hash192 class in the project # Test: Search for Hash192 usage rg --type typescript 'Hash192' # Test: Check if there are any other 192-bit hash implementations rg --type typescript '192.*[Hh]ash'Length of output: 138
Script:
#!/bin/bash # Description: Check for usage of Hash192 class in the project # Test: Search for Hash192 usage in TypeScript files rg --glob "*.ts" 'Hash192' # Test: Check if there are any other 192-bit hash implementations in TypeScript files rg --glob "*.ts" '192.*[Hh]ash'Length of output: 2465
packages/xrpl/test/models/MPTokenIssuanceDestroy.test.ts (3)
7-12
: Well-structured test suite.The test structure is clear and follows best practices. The descriptive comment provides good context for the purpose of these tests.
1-35
: Clean and consistent code style.The code follows consistent naming conventions and indentation. The test cases are concise and focused, which enhances readability and maintainability.
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
5-5
: Consider obfuscating or mocking theTOKEN_ID
value.The
TOKEN_ID
constant appears to contain a specific token identifier. For security and maintainability reasons, consider using a mock value or obfuscating this identifier, especially if it represents real or sensitive data.To verify if this token ID is used elsewhere in the codebase, run the following script:
✅ Verification successful
TOKEN_ID
is used exclusively within test files, ensuring no exposure in production code. For improved maintainability, consider centralizing or mocking this identifier across tests.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for occurrences of the TOKEN_ID value in the codebase # Test: Search for the exact TOKEN_ID value rg --type typescript --type javascript '000004C463C52827307480341125DA0577DEFC38405B0E3E'Length of output: 124
Script:
#!/bin/bash # Description: Search for occurrences of the TOKEN_ID value in .ts and .tsx files # Search for the exact TOKEN_ID value in TypeScript files rg '000004C463C52827307480341125DA0577DEFC38405B0E3E' --type-add 'ts=*.ts' --type-add 'tsx=*.tsx' -t ts -t tsxLength of output: 170
Script:
#!/bin/bash # Description: Search for occurrences of the TOKEN_ID value in .ts and .tsx files # Search for the exact TOKEN_ID value in TypeScript files using glob patterns rg '000004C463C52827307480341125DA0577DEFC38405B0E3E' --glob '*.ts' --glob '*.tsx'Length of output: 926
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/src/models/transactions/MPTokenIssuanceDestroy.ts (2)
1-6
: LGTM: Imports are appropriate and used correctly.The imports from the './common' module are relevant to the functionality of this file and are all utilized in the code.
1-34
: Overall: Well-implemented new transaction type with clear structure and documentation.This new file introduces the
MPTokenIssuanceDestroy
transaction type in a clear and well-structured manner. The code adheres to TypeScript best practices, includes comprehensive documentation, and implements proper validation. The implementation aligns well with the PR objectives of introducing new types and interfaces for multi-party tokens (MPTs).Key strengths:
- Clear and informative JSDoc comments
- Well-defined interface extending BaseTransaction
- Proper validation function with type safety
Minor suggestions for improvement have been provided in previous comments, but these are not critical issues. The overall quality of this implementation is high and it successfully introduces the new MPTokenIssuanceDestroy transaction type to the XRPL package.
packages/xrpl/src/models/ledger/LedgerEntry.ts (1)
54-55
: LGTM. Consider adding documentation for the new filter options.The additions of 'mpt_issuance' and 'mptoken' to the LedgerEntryFilter type are correct and consistent with the existing code style. These new options likely correspond to new ledger entry types for multi-party tokens (MPTs).
Consider adding inline comments or updating the documentation to explain the purpose and usage of these new filter options. This will help developers understand when and how to use them.
To ensure consistency across the codebase, let's verify if these new ledger entry types are properly handled in other relevant files:
packages/ripple-binary-codec/src/types/index.ts (3)
7-7
: LGTM: New import for Hash192 added correctly.The import statement for
Hash192
is consistent with the existing import pattern for other hash types. It maintains the code structure and follows the established naming convention.
7-7
: Summary: Hash192 type integration looks good, but requires further verification.The changes to introduce the
Hash192
type are consistent with the existing code structure and conventions. The type has been properly imported, added tocoreTypes
, and exported. These changes suggest an expansion of hash support in the Ripple binary codec to include 192-bit hashes.To ensure a complete and correct implementation:
- Verify the existence and implementation of
hash-192.ts
.- Check for appropriate unit tests for the
Hash192
type.- Review other files in the project that might need to use or handle
Hash192
.These verifications will help maintain the integrity and consistency of the codebase with this new addition.
Also applies to: 29-29, 56-56
56-56
: LGTM: Hash192 added to exports correctly.The
Hash192
type has been appropriately added to the exports, maintaining consistency with other exported types and preserving alphabetical order. This makesHash192
available for use in other modules.To ensure that
Hash192
is properly utilized where needed, please run the following script:#!/bin/bash # Description: Check for potential usage of Hash192 in other files # Search for files that might need to use Hash192 rg --type typescript -i "hash.*192" packages/ripple-binary-codec packages/xrplpackages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts (3)
1-13
: LGTM: Imports and constants are well-structured.The necessary modules and utilities are correctly imported, and the TIMEOUT constant is appropriately set for integration testing.
15-21
: LGTM: Test suite setup follows best practices.The test suite is well-structured using Mocha's
describe
function, and thebeforeEach
andafterEach
hooks ensure proper setup and teardown for each test case. The use of a typedtestContext
is a good practice for maintaining consistency across tests.
23-52
: LGTM: Well-structured test case for MPTokenIssuanceCreate.The test case is well-designed, covering the creation of an MPTokenIssuanceCreate transaction, its submission, and verification of the resulting issuance object on the ledger. The use of the
testTransaction
utility and proper assertions contribute to a robust integration test.packages/xrpl/src/models/ledger/index.ts (1)
22-23
: LGTM! New MPT-related imports and exports added correctly.The changes look good. The new imports for
MPTokenIssuance
andMPToken
have been added correctly, and they are also properly included in the exports list. The additions maintain the existing structure and alphabetical order of the file.To ensure the correctness of these additions, please run the following script to verify the existence of the new imported files:
This script will help confirm that the new files exist and export the correct entities.
Also applies to: 60-61
packages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts (1)
1-27
: LGTM: Imports and test setup are well-structured.The imports, test suite setup, and test context management are well-organized and follow best practices for integration testing. The use of
beforeEach
andafterEach
hooks ensures a clean state for each test case.packages/xrpl/test/models/MPTokenAuthorize.test.ts (1)
1-5
: LGTM: Imports and constants are well-defined.The imports are appropriate for the test file, including the necessary assertion function and relevant types/functions from the source. The
TOKEN_ID
constant is well-defined and promotes consistency throughout the tests.🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (1)
1-5
: LGTM: Imports and constants are well-defined.The imports are appropriate for the test file, and the use of a constant
TOKEN_ID
promotes consistency throughout the tests.🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts (2)
1-17
: LGTM: Imports and constants are well-defined.The necessary imports are correctly included, and the timeout constant is appropriately set for an integration test.
19-25
: LGTM: Proper test suite setup and teardown.The test suite is well-structured with appropriate setup and teardown procedures. This ensures each test runs in isolation with a fresh client instance.
packages/xrpl/src/models/transactions/metadata.ts (3)
1-1
: LGTM: Import statement updated correctly.The addition of
MPTAmount
import is consistent with the subsequent changes in the file and is necessary for the type updates.
17-20
: LGTM: New import added for MPTokenIssuanceCreate.The import for
MPTokenIssuanceCreate
andMPTokenIssuanceCreateMetadata
is consistent with the existing pattern and necessary for the updates to theTransactionMetadata
type.
Line range hint
1-105
: Summary: Changes successfully implement Multi-Party Token support.The modifications to this file consistently and correctly implement support for Multi-Party Tokens (MPT) in the transaction metadata. The changes include:
- Adding necessary imports
- Updating the
TransactionMetadataBase
interface- Extending the
TransactionMetadata
typeThese changes are well-structured and follow the existing patterns in the codebase. The only suggestions for improvement are minor and relate to documentation. Overall, the implementation appears solid and ready for integration.
packages/xrpl/test/models/MPTokenIssuanceCreate.test.ts (2)
1-14
: LGTM: Imports and description are appropriate.The import statements are concise and import the necessary functions and types for the tests. The brief description provides good context for the test suite's purpose.
30-43
: LGTM: Proper validation for empty MPTokenMetadata.This test case correctly verifies that an empty MPTokenMetadata string triggers a ValidationError with an appropriate error message. The use of assert.throws is correct for this negative test case.
packages/xrpl/src/models/transactions/index.ts (2)
Line range hint
1-57
: Summary: MPToken functionality successfully integratedThe changes in this file successfully integrate Multi-Party Token (MPT) functionality into the XRPL transaction models. The additions are well-structured, consistent with existing patterns, and align with the PR objectives. Key points:
- The
isMPTAmount
function is now exported alongsideBaseTransaction
.- New exports for MPToken-related transactions (Authorize, IssuanceCreate, IssuanceDestroy, and IssuanceSet) have been added.
- The changes maintain the file's organization and don't disrupt existing exports.
These modifications enhance the module's capabilities for handling MPToken operations, providing a solid foundation for further development and usage of MPT features in the XRPL ecosystem.
42-57
: LGTM. Verify completeness of MPToken exports.The new exports for MPToken-related transactions are well-structured and consistent with existing patterns. They align with the PR objectives of introducing Multi-Party Token functionality.
To ensure all necessary MPToken-related exports are included, please run the following verification script:
This script will help identify any MPToken-related files that may have been overlooked in the export statements.
✅ Verification successful
Verified: All MPToken-related exports are complete.
The verification script did not find any missing MPToken exports inindex.ts
. All relevant MPToken-related files are properly exported.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify all MPToken-related files are exported # Test: Check for any MPToken-related files that are not exported fd -e ts '^MPToken' ./packages/xrpl/src/models/transactions | while read -r file; do filename=$(basename "$file" .ts) if ! grep -q "from './$filename'" ./packages/xrpl/src/models/transactions/index.ts; then echo "Warning: $filename is not exported in index.ts" fi doneLength of output: 963
packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (3)
1-27
: LGTM: Imports and test setup are well-structured.The imports, test context setup, and teardown are appropriately implemented. The use of a TIMEOUT constant is a good practice for managing test duration expectations.
106-115
: Suggestion: Specify 'mptoken' type in the final account_objects request.The final state verification is correct, but to make it more specific and consistent with previous suggestions, consider adding a 'type' parameter to the account_objects request:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: wallet2.classicAddress, type: 'mptoken', })This ensures we're only checking for MPToken objects, making the test more focused and consistent with the previous checks.
This suggestion aligns with the previous review comment by khancode. Please apply this change to ensure consistency throughout the test file.
1-119
: Overall: Well-implemented test suite for MPTokenAuthorize transactions.This test file provides a comprehensive integration test for MPTokenAuthorize transactions, covering creation, authorization, and unauthorized scenarios. The test structure is clear, and assertions are well-placed to verify the expected state after each operation.
The suggested improvements for account_objects requests will enhance the specificity and consistency of the tests. Once these minor changes are applied, the test suite will be even more robust and efficient.
Great job on implementing this thorough test case for the new MPToken functionality!
packages/xrpl/src/models/utils/flags.ts (1)
54-56
: LGTM! Verify the integration of new transaction types.The additions to the
txToFlag
object correctly map the new MPToken-related transaction types to their corresponding flag enums. This change enables proper flag handling for these new transaction types.To ensure the correct integration of these new transaction types, please run the following verification script:
This script will help verify the existence of the new transaction type files, the correct export of flag enums, and their usage in test files.
✅ Verification successful
Verified: Correct integration of new transaction types.
All MPToken-related transaction files exist, correctly export their respective flag enums, and are properly utilized in test files. The additions to the
txToFlag
object are successfully integrated.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the existence and correct import of MPToken-related transaction types and flags. # Test 1: Check if the MPToken-related transaction files exist echo "Checking for MPToken-related transaction files:" fd --type f --glob '**/transactions/MPToken*.ts' # Test 2: Verify the content of these files echo "\nVerifying the content of MPToken-related transaction files:" rg --type typescript 'export (enum|type) MPToken.*Flags' --glob '**/transactions/MPToken*.ts' # Test 3: Check for any usage of these new transaction types in test files echo "\nChecking for usage of new transaction types in test files:" rg --type typescript 'MPTokenAuthorize|MPTokenIssuanceCreate|MPTokenIssuanceSet' --glob '**/*.test.ts'Length of output: 690
Script:
#!/bin/bash # Description: Corrected script to verify the existence and correct import of MPToken-related transaction types and flags. # Test 1: Check if the MPToken-related transaction files exist echo "Checking for MPToken-related transaction files:" fd --type f --glob '**/transactions/MPToken*.ts' # Test 2: Verify the content of these files echo "\nVerifying the content of MPToken-related transaction files:" rg --type ts 'export (enum|type) MPToken.*Flags' --glob '**/transactions/MPToken*.ts' # Test 3: Check for any usage of these new transaction types in test files echo "\nChecking for usage of new transaction types in test files:" rg --type ts 'MPTokenAuthorize|MPTokenIssuanceCreate|MPTokenIssuanceSet' --glob '**/*.test.ts'Length of output: 12764
packages/xrpl/src/models/common/index.ts (1)
23-26
: LGTM! Consider adding JSDoc comments for better documentation.The new
MPTAmount
interface is a good addition for supporting Multi-Party Tokens (MPT) in the XRPL package. The structure is consistent with existing interfaces and follows the naming conventions used in the file.To improve the code, consider adding JSDoc comments to explain the purpose of the interface and its properties. For example:
/** * Represents an amount for a Multi-Party Token (MPT). */ export interface MPTAmount { /** * The unique identifier for the MPT issuance. */ mpt_issuance_id: string; /** * The value of the MPT amount. */ value: string; }To ensure this new interface is being used correctly, let's verify its usage across the codebase:
This will help identify where the new interface is being used and ensure it's implemented consistently throughout the project.
✅ Verification successful
LGTM! The
MPTAmount
interface is properly integrated across the codebase.The new
MPTAmount
interface effectively supports the Multi-Party Tokens (MPT) feature within the XRPL package. Its consistent usage in various modules demonstrates thoughtful integration without introducing any type conflicts or issues.To enhance code readability and maintainability, consider adding JSDoc comments to the
MPTAmount
interface and its properties. For example:/** * Represents an amount for a Multi-Party Token (MPT). */ export interface MPTAmount { /** * The unique identifier for the MPT issuance. */ mpt_issuance_id: string; /** * The value of the MPT amount. */ value: string; }🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for usage of the new MPTAmount interface # Search for MPTAmount usage echo "Searching for MPTAmount usage:" rg --type typescript "MPTAmount" # Search for mpt_issuance_id usage (which might indicate implicit usage of MPTAmount) echo "\nSearching for mpt_issuance_id usage:" rg --type typescript "mpt_issuance_id"Length of output: 299
Script:
#!/bin/bash # Description: Check for usage of the new MPTAmount interface # Search for MPTAmount usage in TypeScript files echo "Searching for MPTAmount usage:" rg "MPTAmount" --glob '*.ts' --glob '*.tsx' # Search for mpt_issuance_id usage in TypeScript files echo "\nSearching for mpt_issuance_id usage:" rg "mpt_issuance_id" --glob '*.ts' --glob '*.tsx'Length of output: 6418
packages/ripple-binary-codec/test/hash.test.ts (2)
1-8
: LGTM: Import statement updated correctlyThe import statement has been properly updated to include the new
Hash192
type. This change is consistent with the addition of new tests forHash192
in this file.
Line range hint
10-60
: Existing tests remain consistentThe test suites for
Hash128
,Hash160
,Hash256
, andCurrency
have been left unchanged. This consistency is good for maintainability and suggests that the addition ofHash192
didn't require modifications to other hash types.Also applies to: 87-173
packages/xrpl/src/models/methods/ledgerEntry.ts (3)
24-28
: LGTM: Newmpt_issuance
property added correctly.The
mpt_issuance
property has been added with the correct type (optional string) and includes a clear JSDoc comment explaining its purpose. This addition enhances theLedgerEntryRequest
interface to support retrieving MPTokenIssuance objects from the ledger.
30-38
: LGTM: Newmptoken
property added correctly.The
mptoken
property has been added with the correct type (optional union of object and string) and includes a clear JSDoc comment explaining its purpose. The object type within the union is well-defined with the requiredmpt_issuance_id
andaccount
properties. This addition enhances theLedgerEntryRequest
interface to support retrieving MPToken objects from the ledger.
24-38
: Consider updating related documentation and tests.The additions of
mpt_issuance
andmptoken
properties to theLedgerEntryRequest
interface enhance its functionality to support Multi-Party Tokens (MPT). To ensure comprehensive coverage:
- Update any relevant documentation that describes the
LedgerEntryRequest
interface to include these new properties.- Add or modify unit tests to cover scenarios using these new properties.
- Update any example code or usage guidelines to demonstrate how to use these new properties in ledger entry requests.
To help verify the need for documentation and test updates, you can run the following script:
packages/xrpl/src/models/transactions/payment.ts (3)
2-2
: LGTM: Import statement updated correctly.The addition of
MPTAmount
to the imports is consistent with its usage in the modified interfaces below. This change appropriately prepares the file for the new type integration.
156-157
: LGTM: PaymentMetadata interface updated correctly.The modifications to the
DeliveredAmount
anddelivered_amount
fields in the PaymentMetadata interface are consistent with the changes made to the Payment interface. These updates appropriately allow for MPTAmount to be used in payment metadata, ensuring consistency throughout the transaction process.
Line range hint
166-254
: Consider updating the validatePayment function.While the interfaces have been updated to include the new
MPTAmount
type, thevalidatePayment
function hasn't been modified. To ensure consistency and proper validation of the new type, consider updating this function to handleMPTAmount
in theAmount
,SendMax
, andDeliverMin
fields.To verify if the
validatePayment
function needs updating, we can check if there's a separate validation forMPTAmount
or if it's handled by the existingisAmount
function:If
MPTAmount
is not handled separately or withinisAmount
, you may need to update thevalidatePayment
function to properly validate this new type.packages/xrpl/test/models/payment.test.ts (1)
262-274
: Approve the addition of MPT PaymentTransaction test case with suggestions for improvement.The new test case for MPT PaymentTransaction is a good addition to cover the basic structure and validation of this transaction type. However, there are a few suggestions to enhance the test coverage:
Consider adding more test cases to cover edge scenarios and invalid MPT payment transactions. For example:
- Test with missing
mpt_issuance_id
orvalue
in theAmount
object.- Test with invalid
mpt_issuance_id
format.- Test with negative or zero
value
.The existing test only checks that no exception is thrown. Consider adding assertions to verify the specific properties of the transaction after validation.
Additionally, as per the previous review comment, an equivalent integration test in
test/integration/transactions/payment.test.ts
would be beneficial to ensure end-to-end functionality.packages/xrpl/src/models/transactions/transaction.ts (3)
93-105
: LGTM: New MPT-related imports added correctly.The new import statements for MPT-related modules (MPTokenAuthorize, MPTokenIssuanceCreate, MPTokenIssuanceDestroy, and MPTokenIssuanceSet) have been added correctly. They follow the existing pattern in the file, maintain consistent naming conventions, and preserve the alphabetical order of imports.
131-134
: LGTM: New MPT transaction types added to SubmittableTransaction.The
SubmittableTransaction
type has been correctly updated to include the new MPT-related transaction types: MPTokenAuthorize, MPTokenIssuanceCreate, MPTokenIssuanceDestroy, and MPTokenIssuanceSet. These additions maintain the existing structure and alphabetical order within the union type.
326-341
: LGTM: Validation for new MPT transaction types added correctly.The
validate
function has been properly updated to include new case statements for the MPT-related transaction types. Each new case calls the corresponding validation function, following the existing pattern in the switch statement. The additions maintain alphabetical order and consistency with other transaction types.packages/ripple-binary-codec/test/binary-parser.test.ts (1)
25-25
: LGTM: Enhanced amount validation for MPT support.The addition of the
mpt_issuance_id
comparison in theassertEqualAmountJSON
function improves the validation of amount objects. This change suggests the introduction or support for multi-party tokens (MPTs) in the codebase.packages/ripple-binary-codec/src/enums/definitions.json (6)
265-274
: 🛠️ Refactor suggestionNew fields added for Multi-Party Tokens and other features
Several new fields have been added to support Multi-Party Tokens (MPTs) and other features:
- AssetScale (UInt8)
- LedgerFixType (UInt16)
- MaximumAmount (UInt64)
- OutstandingAmount (UInt64)
- MPTAmount (UInt64)
- MPTokenIssuanceID (Hash192)
- MPTokenHolder (AccountID)
- MPTokenMetadata (Blob)
These additions indicate significant enhancements to the system's capabilities, particularly in handling MPTs and asset-related data. Ensure that:
- The serialization and deserialization logic for these new fields has been implemented correctly.
- Any relevant business logic and validation rules for these fields are in place.
- The system can handle these new fields in all relevant operations (e.g., transactions, ledger entries).
To verify the implementation and usage of these new fields, run the following script:
#!/bin/bash # Search for usage of new fields in the codebase new_fields=("AssetScale" "LedgerFixType" "MaximumAmount" "OutstandingAmount" "MPTAmount" "MPTokenIssuanceID" "MPTokenHolder" "MPTokenMetadata") for field in "${new_fields[@]}"; do echo "Searching for $field usage:" rg --type ts --type js "$field" echo doneAlso applies to: 385-394, 1095-1124, 1175-1184, 2045-2054, 2145-2154
2893-2893
: 🛠️ Refactor suggestionNew transaction results added
Two new transaction results have been added:
- "temBAD_TRANSFER_FEE" (code -251)
- "tefINVALID_LEDGER_FIX_TYPE" (code -178)
These additions indicate enhanced error handling for:
- Transfer fee validation
- Ledger fix type validation
Ensure that:
- The logic for triggering these new error codes is implemented correctly in the relevant parts of the system.
- Error messages and documentation are updated to include explanations for these new result codes.
- Any client-side code that handles transaction results is updated to recognize and handle these new codes appropriately.
To verify the implementation and usage of these new transaction results, run the following script:
#!/bin/bash # Search for usage of new transaction results in the codebase echo "Searching for temBAD_TRANSFER_FEE usage:" rg --type ts --type js 'temBAD_TRANSFER_FEE' echo "Searching for tefINVALID_LEDGER_FIX_TYPE usage:" rg --type ts --type js 'tefINVALID_LEDGER_FIX_TYPE'Also applies to: 2916-2916
3062-3066
: 🛠️ Refactor suggestionNew transaction types added for Ledger State Fix and Multi-Party Tokens
Five new transaction types have been added:
- LedgerStateFix (code 53)
- MPTokenIssuanceCreate (code 54)
- MPTokenIssuanceDestroy (code 55)
- MPTokenAuthorize (code 56)
- MPTokenIssuanceSet (code 57)
These additions indicate support for new operations related to ledger state fixes and Multi-Party Tokens (MPTs). Ensure that:
- The necessary logic for processing these new transaction types has been implemented throughout the system.
- Validation rules for these new transaction types are in place.
- The system can properly serialize, deserialize, and handle these new transaction types in all relevant components (e.g., transaction processing, ledger application).
- Documentation is updated to explain the purpose and usage of these new transaction types.
To verify the implementation and usage of these new transaction types, run the following script:
#!/bin/bash # Search for usage of new transaction types in the codebase new_tx_types=("LedgerStateFix" "MPTokenIssuanceCreate" "MPTokenIssuanceDestroy" "MPTokenAuthorize" "MPTokenIssuanceSet") for tx_type in "${new_tx_types[@]}"; do echo "Searching for $tx_type usage:" rg --type ts --type js "$tx_type" echo done
Line range hint
1-3066
: Summary of changes: Multi-Party Token support and other enhancementsThis update to the
definitions.json
file introduces significant changes to support Multi-Party Tokens (MPTs) and other new features. The modifications include:
- Renaming of the "UInt192" type to "Hash192"
- Addition of new ledger entry types for MPTs
- Introduction of several new fields related to MPTs and asset management
- New transaction results for improved error handling
- Five new transaction types for MPT operations and ledger state fixes
These changes collectively represent a substantial enhancement to the system's capabilities, particularly in handling Multi-Party Tokens. The modifications appear to be consistent and well-structured, following the existing patterns in the file.
To ensure the successful implementation of these new features:
- Verify that all related components of the system (e.g., serialization, deserialization, transaction processing, ledger application) have been updated to support these new definitions.
- Update documentation to explain the new types, fields, and transaction types.
- Ensure that test coverage has been expanded to include these new elements.
- Review any client-side code that may need to be updated to handle the new transaction types and results.
To get an overview of the impact of these changes, run the following script:
#!/bin/bash # Count the number of files affected by the new MPT-related changes echo "Files affected by MPT-related changes:" rg --type ts --type js -l 'MPToken|MPTAmount|MPTokenIssuance' | wc -l # List the files with the most MPT-related changes echo "Top 5 files with most MPT-related changes:" rg --type ts --type js -c 'MPToken|MPTAmount|MPTokenIssuance' | sort -t':' -k2 -nr | head -n 5
21-21
: 🛠️ Refactor suggestionType renaming: UInt192 to Hash192
The type "UInt192" has been renamed to "Hash192". This change suggests a shift in how this type is conceptualized or used within the system. Ensure that all references to this type throughout the codebase have been updated accordingly to maintain consistency.
To verify the impact of this change, run the following script:
✅ Verification successful
Verification Successful: "UInt192" has been fully renamed to "Hash192"
No remaining references to
UInt192
were found in the codebase. All instances have been successfully updated toHash192
, ensuring consistency throughout the project.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining references to UInt192 in the codebase echo "Searching for remaining UInt192 references:" rg --type ts --type js 'UInt192' # Search for new Hash192 usage echo "Searching for new Hash192 usage:" rg --type ts --type js 'Hash192'Length of output: 2152
56-57
: 🛠️ Refactor suggestionNew ledger entry types for Multi-Party Tokens
Two new ledger entry types have been added:
- "MPTokenIssuance" (code 126)
- "MPToken" (code 127)
These additions indicate support for Multi-Party Tokens (MPTs) in the ledger. Ensure that the necessary logic for handling these new ledger entry types has been implemented throughout the system, including serialization, deserialization, and any relevant business logic.
To verify the implementation of these new types, run the following script:
✅ Verification successful
Verification of New Ledger Entry Types
The new ledger entry types "MPTokenIssuance" and "MPToken" are utilized across 30 files in the codebase, including key source and test files:
packages/xrpl/test/models/MPTokenAuthorize.test.ts
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts
packages/xrpl/test/models/MPTokenIssuanceCreate.test.ts
packages/xrpl/src/models/transactions/transaction.ts
packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts
This indicates that the necessary logic for handling these new ledger entry types has been implemented throughout the system, including serialization, deserialization, and relevant business logic.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for MPTokenIssuance and MPToken usage in the codebase echo "Searching for MPTokenIssuance usage:" rg --type ts --type js 'MPTokenIssuance' echo "Searching for MPToken usage:" rg --type ts --type js 'MPToken'Length of output: 639
packages/xrpl/HISTORY.md (4)
Line range hint
47-50
: New API definitions and enhancements addedSeveral new API definitions and enhancements have been introduced:
nfts_by_issuer
API- Additions to
ledgerEntry
request and response- Support for
fixPreviousTxnID
amendment- Support for user version of
feature
RPCThese additions expand the functionality of the library and provide more options for developers.
Line range hint
51-52
: New response field addedA new
hash
field has been added to theledger
command response.This addition provides more information in the ledger command response, which can be useful for developers.
Line range hint
54-55
: Removal of references to Hooks testnet faucetReferences to the Hooks testnet faucet have been removed from the xrpl.js code repository.
This change helps keep the library focused on core functionality and removes potentially outdated references.
Line range hint
1-1078
: Overall development patternThe HISTORY.md file demonstrates a consistent pattern of active development for the xrpl.js library:
Regular updates: The library receives frequent updates, often addressing bug fixes, adding new features, and improving existing functionality.
Breaking changes: Major versions often include breaking changes, which are clearly marked. This indicates that the library evolves significantly over time, potentially requiring users to update their implementations.
Dependency management: There's a consistent effort to keep dependencies up-to-date, which is crucial for security and performance.
Expanding functionality: New features and API endpoints are regularly added, showing that the library is actively expanding to cover more of the XRPL's capabilities.
Performance and security improvements: Many updates focus on improving performance and addressing security concerns.
Documentation updates: There's a clear effort to keep documentation accurate and up-to-date alongside code changes.
This pattern of development indicates that xrpl.js is a well-maintained library that evolves with the XRPL ecosystem. Users should be prepared for regular updates and occasional breaking changes when major versions are released.
packages/ripple-binary-codec/test/fixtures/data-driven-tests.json (20)
Line range hint
2502-2507
: Approved: Correct handling of negative values for native Amount typeThe test case correctly checks that negative values are not allowed for native Amount types. This is an important edge case to test.
2919-2925
: Approved: Proper validation for large MPT Amount valuesThis test case correctly checks that MPT Amount values exceeding the maximum allowed value (2^63 - 1) are rejected. This is crucial for preventing overflow issues.
2927-2933
: Approved: Additional validation for extremely large MPT Amount valuesThis test case checks for rejection of MPT Amount values that exceed the maximum unsigned 64-bit integer. This provides an extra layer of protection against potential overflow issues.
2935-2941
: Approved: Rejection of negative MPT Amount valuesThis test case ensures that negative values are not allowed for MPT Amounts, which is consistent with the expected behavior for these types of tokens.
2943-2949
: Approved: Rejection of decimal values for MPT AmountsThis test case correctly checks that decimal values are not allowed for MPT Amounts, enforcing the use of integer values only.
2951-2957
: Approved: Validation of MPT issuance ID formatThis test case ensures that the MPT issuance ID has the correct length, which is important for maintaining the integrity of the MPT identifier.
2959-2966
: Approved: Rejection of invalid issuer for MPT AmountsThis test case correctly checks that an issuer cannot be specified for MPT Amounts, as they should not have a separate issuer.
2968-2975
: Approved: Rejection of currency specification for MPT AmountsThis test case ensures that a currency cannot be specified for MPT Amounts, as they represent a specific token type defined by the issuance ID.
2977-2983
: Approved: Validation of MPT Amount value formatThis test case checks that the MPT Amount value is in the correct format, rejecting non-numeric inputs.
2985-2991
: Approved: Rejection of invalid hexadecimal format for MPT Amount valuesThis test case ensures that incorrectly formatted hexadecimal values are rejected for MPT Amounts.
2993-2999
: Approved: Rejection of invalid characters in MPT Amount valuesThis test case checks that invalid characters are not allowed in MPT Amount values, maintaining data integrity.
3001-3007
: Approved: Rejection of out-of-range hexadecimal values for MPT AmountsThis test case ensures that hexadecimal values exceeding the maximum allowed value are rejected for MPT Amounts.
3009-3015
: Approved: Additional check for out-of-range hexadecimal valuesThis test case provides another check for rejecting hexadecimal values that are out of the valid range for MPT Amounts.
3017-3026
: Approved: Correct handling of maximum allowed MPT Amount valueThis test case verifies that the maximum allowed value (2^63 - 1) for MPT Amounts is correctly encoded and accepted.
3028-3037
: Approved: Correct handling of zero MPT Amount valueThis test case ensures that a zero value for MPT Amounts is correctly encoded and accepted.
3039-3048
: Approved: Correct handling of negative zero MPT Amount valueThis test case verifies that a negative zero value for MPT Amounts is treated the same as positive zero, which is the expected behavior.
3050-3059
: Approved: Correct encoding of non-zero MPT Amount valueThis test case checks the correct encoding of a non-zero MPT Amount value, ensuring the value is properly represented in the expected hexadecimal format.
3061-3070
: Approved: Correct handling of hexadecimal MPT Amount valueThis test case verifies that a hexadecimal input for MPT Amount values is correctly interpreted and encoded.
3072-3080
: Approved: Correct handling of maximum hexadecimal MPT Amount valueThis test case ensures that the maximum allowed hexadecimal value for MPT Amounts is correctly encoded and accepted.
Line range hint
2502-3080
: Comprehensive test coverage for MPT Amount handlingThe new test cases for MPT (Multi-Party Tokens) Amount handling are well-designed and cover a wide range of scenarios. They include checks for:
- Maximum and minimum allowed values
- Rejection of negative values
- Validation of the MPT issuance ID format
- Rejection of invalid currency and issuer specifications
- Proper handling of zero and edge case values
- Validation of input formats (decimal, hexadecimal)
These test cases significantly enhance the robustness of the MPT Amount handling in the ripple-binary-codec package. They should help prevent potential issues related to overflow, invalid inputs, and incorrect encodings.
packages/ripple-binary-codec/src/types/uint-64.ts (5)
5-5
: Import statement added appropriately.The addition of
DEFAULT_DEFINITIONS
andXrplDefinitionsBase
is necessary for the new functionality and is correctly imported.
8-8
: Validation regex for base 10 integers is accurate.The
BASE10_REGEX
correctly matches base 10 numbers with up to 20 digits, which is suitable forUInt64
values.
42-45
: Method signature update infrom
is appropriate.Adding the optional
fieldName
parameter allows handling field-specific logic without affecting existing functionality.
104-106
: Conversion to base 10 string is implemented correctly.The method accurately converts the hexadecimal bytes to a base 10 string when required by the
fieldName
.
67-72
: Ensure robust handling of base 10 string inputs.The logic correctly identifies when to interpret the input as a base 10 string and converts it to hexadecimal. However, double-check that this conversion handles edge cases and invalid inputs gracefully.
Run the following script to test validation of base 10 inputs:
packages/xrpl/test/models/clawback.test.ts (1)
82-94
: LGTM: Valid MPT Clawback test caseThe test for a valid MPT Clawback transaction is well-constructed and effectively ensures that the
validate
function does not throw an error when supplied with correct parameters.🧰 Tools
🪛 Gitleaks
90-90: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/integration/transactions/payment.test.ts (1)
11-15
: Imports are correctly addedThe new imports for
MPTokenIssuanceCreate
,MPTokenAuthorize
, andTransactionMetadata
from'../../../src'
are appropriate and correctly referenced.packages/xrpl/test/integration/transactions/clawback.test.ts (7)
9-12
: New imports are correctly added and necessary for the test.The imports of
MPTokenIssuanceCreate
,MPTokenIssuanceCreateFlags
,MPTokenAuthorize
, andTransactionMetadata
are appropriate and required for the new test cases.
21-21
: Import ofLedgerEntryResponse
is appropriate.The import is necessary for typing the
ledgerEntryResponse
variable used in the test.
144-146
: Ensure correct access tompt_issuance_id
in transaction metadata.Verify that
mpt_issuance_id
is correctly accessed fromtxResponse.result.meta
. If TypeScript reports an error, you may need to adjust the type definition ofTransactionMetadata
to includempt_issuance_id
, or access it using the correct property path provided by the API response.
159-159
: Confirm the use of the maximum 64-bit integer value inAmount
.The value
'9223372036854775807'
is the maximum value for a 64-bit signed integer. Ensure that using this large value is intentional and that the system can handle it without issues related to integer overflow or precision loss.
181-190
: Validate the presence ofMPTokenHolder
in theClawback
transaction.Ensure that the
MPTokenHolder
field is correctly used in theClawback
transaction and that it aligns with the expected transaction format. Verify that includingMPTokenHolder
is necessary and supported by the XRPL transaction standards.
156-164
: Handle large payment amounts cautiously.When sending a payment with the maximum possible value, ensure that the system can handle such large numbers without causing overflow errors or other issues.
200-204
: Verify the correctness of the expectedMPTAmount
after clawback.The expected
MPTAmount
after clawback is'9223372036854775307'
. Confirm that this value correctly reflects the deduction of'500'
from the original amount and that there are no calculation errors.packages/ripple-binary-codec/src/types/st-object.ts (4)
13-13
: ImportUInt64
type for proper handlingThe addition of the import statement ensures that the
UInt64
type is available for use within this file, which is necessary for handlingUInt64
fields appropriately.
141-142
: HandleUInt64
field types explicitly inSTObject.from
By adding a specific condition for
field.type.name === 'UInt64'
, the code now explicitly handlesUInt64
fields usingUInt64.from
. This ensures thatUInt64
values are correctly instantiated, which is important because they may require special processing compared to other types.
192-192
: Ensure consistency intoJSON
method signaturesThe
toJSON
method is now called withdefinitions
andfield.name
as arguments. Verify that alltoJSON
methods for associated value types acceptfield.name
as a second parameter. This is crucial to avoid runtime errors and ensure the JSON representation is constructed correctly for each field type.Run the following script to find
toJSON
method definitions and check if they acceptfieldName
as a parameter:#!/bin/bash # Description: Find all `toJSON` method definitions and check their parameter lists. # Search for `toJSON` method definitions across the codebase. rg --type ts 'toJSON\(' -A 1
161-165
: VerifyisUnlModifyWorkaround
parameter usage inwriteFieldAndValue
The inclusion of
isUnlModifyWorkaround
as an argument in thebytes.writeFieldAndValue
method introduces a workaround for theUNLModify
pseudo-transaction. Verify that thewriteFieldAndValue
method accepts this additional parameter and that it behaves as intended to address the rippled bug mentioned in the comment.Run the following script to check the method definition of
writeFieldAndValue
and confirm it accepts theisUnlModifyWorkaround
parameter:✅ Verification successful
writeFieldAndValue
correctly accepts theisUnlModifyWorkaround
parameterThe
writeFieldAndValue
method is confirmed to accept theisUnlModifyWorkaround
parameter and behaves as intended to address the rippled bug.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that `writeFieldAndValue` method accepts the `isUnlModifyWorkaround` parameter. # Search for the `writeFieldAndValue` method definition and display its parameters. rg --type ts 'writeFieldAndValue\(' -A 5 --files-with-matches | xargs rg 'writeFieldAndValue\(' -A 5Length of output: 12257
packages/xrpl/src/client/partialPayment.ts (4)
9-9
: Correctly ImportedMPTAmount
,APIVersion
, andDEFAULT_API_VERSION
The addition of
MPTAmount
,APIVersion
, andDEFAULT_API_VERSION
to the imports ensures that the new types and constants are available for use in this module.
16-16
: ImportedisMPTAmount
FunctionImporting
isMPTAmount
from'../models/transactions'
is appropriate for type checking and enhances the functionality of theamountsEqual
function.
34-47
: Verified Logic for HandlingMPTAmount
ComparisonsThe logic added to handle
MPTAmount
comparisons within theamountsEqual
function is sound. It correctly compares both thempt_issuance_id
and the numericalvalue
, and appropriately returnsfalse
when only one of the amounts is anMPTAmount
.
22-25
: Ensure Unit Tests CoveramountsEqual
withMPTAmount
The
amountsEqual
function signature has been updated to acceptAmount | MPTAmount
. Please ensure that unit tests are added or updated to cover all new code paths, including comparisons involvingMPTAmount
.To verify the test coverage, you can run the following script:
packages/ripple-binary-codec/test/uint.test.ts (1)
182-188
: New test cases for MPT amounts are comprehensiveThe added test cases in lines 182-188 effectively verify that
UInt64
values are correctly parsed as base 10 for MPT amounts during both encoding and decoding processes. This enhances the test coverage for MPT-related functionalities.packages/ripple-binary-codec/src/types/amount.ts (2)
176-181
: Validate bitmask logic infromParser
method for amount typesIn the
fromParser
method, the logic determining the type of amount based on bitmasks should be carefully validated to ensure it aligns with the protocol specifications.const isIOU = parser.peek() & 0x80 if (isIOU) return new Amount(parser.read(48)) // the amount can be either MPT or XRP at this point const isMPT = parser.peek() & 0x20 const numBytes = isMPT ? 33 : 8 return new Amount(parser.read(numBytes))Ensure that:
- The bitmask
0x80
correctly identifies IOU amounts.- The bitmask
0x20
correctly identifies MPT amounts.- The number of bytes read (
48
,33
,8
) corresponds correctly to the expected sizes of IOU, MPT, and XRP amounts.
Line range hint
84-315
: Add unit tests for MPT amount functionalityThe new MPT-related functionality in the
Amount
class should be accompanied by comprehensive unit tests to ensure correct behavior. This includes testing:
- Creation of MPT amounts using
Amount.from
.- Parsing MPT amounts from binary data.
- Serializing MPT amounts to JSON.
- Validation logic in
assertMptIsValid
.- Bitmask operations in type-checking methods.
Would you like assistance in writing these unit tests or opening a GitHub issue to track this task?
packages/xrpl/src/models/transactions/common.ts (2)
12-12
: Import ofMPTAmount
is correctThe import statement correctly adds
MPTAmount
for use in this file.
164-168
: Extension ofisAmount
function to includeisMPTAmount
is appropriateThe addition of
isMPTAmount(amount)
to theisAmount
function appropriately extends the validation to includeMPTAmount
types.
export interface MPTokenIssuance extends BaseLedgerEntry, HasPreviousTxnID { | ||
LedgerEntryType: 'MPTokenIssuance' | ||
Flags: number | ||
Issuer: string | ||
AssetScale?: number | ||
MaximumAmount?: string | ||
OutstandingAmount: string | ||
LockedAmount?: string | ||
TransferFee?: number | ||
MPTokenMetadata?: string | ||
OwnerNode?: string | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Action Required: Use BigNumber for Large Numerical Properties
The MPTokenIssuance
interface currently uses string
types for properties handling large numerical values (MaximumAmount
, OutstandingAmount
, LockedAmount
). To ensure consistency and improve precision across the codebase, consider using BigNumber
for these properties.
- MaximumAmount: Change from
string
toBigNumber.Value
- OutstandingAmount: Change from
string
toBigNumber.Value
- LockedAmount: Change from
string
toBigNumber.Value
This alignment will enhance type safety and consistency in handling large numbers within the XRPL system.
🔗 Analysis chain
LGTM: MPTokenIssuance interface structure is well-defined.
The MPTokenIssuance interface is well-structured and extends the appropriate base interfaces. The property types are generally appropriate for their purposes.
However, consider the following suggestion:
For properties that might represent large numerical values (MaximumAmount, OutstandingAmount, LockedAmount), verify if using a more precise type like BigNumber would be more appropriate than string. This depends on the specific requirements and constraints of the XRPL system.
To check if BigNumber is used elsewhere in the project for similar purposes, run:
If BigNumber is commonly used, consider updating these properties accordingly.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for BigNumber usage in the project
rg --type typescript 'BigNumber' packages/xrpl/src
Length of output: 85
Script:
#!/bin/bash
# Search for BigNumber usage in TypeScript files within the xrpl package
rg --type ts 'BigNumber' packages/xrpl/src
Length of output: 6446
it(`throws w/ missing MPTokenIssuanceID`, function () { | ||
const invalid = { | ||
TransactionType: 'MPTokenIssuanceDestroy', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
} as any | ||
|
||
assert.throws( | ||
() => validate(invalid), | ||
ValidationError, | ||
'MPTokenIssuanceDestroy: missing field MPTokenIssuanceID', | ||
) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Good negative test case, but consider removing as any
.
The negative test case correctly checks for the specific error message, which is a good practice. However, the use of as any
type assertion might be masking potential type issues. Consider defining a proper type for the transaction object to maintain type safety.
You could define a type like this:
type PartialMPTokenIssuanceDestroy = Partial<{
TransactionType: string;
Account: string;
MPTokenIssuanceID: string;
}>;
Then use it in your test:
const invalid: PartialMPTokenIssuanceDestroy = {
TransactionType: 'MPTokenIssuanceDestroy',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
};
@@ -25,6 +26,7 @@ const coreTypes: Record<string, typeof SerializedType> = { | |||
Currency, | |||
Hash128, | |||
Hash160, | |||
Hash192, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Issue: Incomplete implementation of Hash192
class.
- The
Hash192
class inpackages/ripple-binary-codec/src/types/hash-192.ts
is missing thestatic readonly width = 24;
property.
🔗 Analysis chain
LGTM: Hash192 added to coreTypes correctly.
The Hash192
type has been appropriately added to the coreTypes
object, maintaining consistency with other hash types and preserving alphabetical order.
To ensure the Hash192
type is fully implemented, please run the following script:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify the implementation of Hash192 type
# Test 1: Check if hash-192.ts file exists
fd -t f "hash-192.ts" packages/ripple-binary-codec/src/types
# Test 2: Verify Hash192 class implementation
ast-grep --lang typescript --pattern $'class Hash192 {
$$$
static readonly width = 24;
$$$
}'
# Test 3: Check for unit tests
fd -t f "hash-192.test.ts" packages/ripple-binary-codec/src/types
Length of output: 375
Script:
#!/bin/bash
# Description: Re-verify the implementation of Hash192 type with corrected commands
# Test 1: Check if hash-192.ts file exists
fd -t f "hash-192.ts" packages/ripple-binary-codec/src/types
# Test 2: Verify Hash192 class implementation
ast-grep --lang typescript --pattern $'class Hash192 {
$$$
static readonly width = 24;
$$$
}'
# Test 3: Check for unit tests
fd -t f "hash-192.test.ts" packages/ripple-binary-codec/src/types
Length of output: 278
import { assert } from 'chai' | ||
|
||
import { MPTokenIssuanceCreate } from '../../../src' | ||
import serverUrl from '../serverUrl' | ||
import { | ||
setupClient, | ||
teardownClient, | ||
type XrplIntegrationTestContext, | ||
} from '../setup' | ||
import { testTransaction } from '../utils' | ||
|
||
// how long before each test case times out | ||
const TIMEOUT = 20000 | ||
|
||
describe('MPTokenIssuanceCreate', function () { | ||
let testContext: XrplIntegrationTestContext | ||
|
||
beforeEach(async () => { | ||
testContext = await setupClient(serverUrl) | ||
}) | ||
afterEach(async () => teardownClient(testContext)) | ||
|
||
it( | ||
'base', | ||
async () => { | ||
const tx: MPTokenIssuanceCreate = { | ||
TransactionType: 'MPTokenIssuanceCreate', | ||
Account: testContext.wallet.classicAddress, | ||
MaximumAmount: '9223372036854775807', // 0x7fffffffffffffff | ||
AssetScale: 2, | ||
} | ||
|
||
await testTransaction(testContext.client, tx, testContext.wallet) | ||
|
||
let accountObjectsResponse = await testContext.client.request({ | ||
command: 'account_objects', | ||
account: testContext.wallet.classicAddress, | ||
type: 'mpt_issuance', | ||
}) | ||
assert.lengthOf( | ||
accountObjectsResponse.result.account_objects!, | ||
1, | ||
'Should be exactly one issuance on the ledger', | ||
) | ||
assert.equal( | ||
// @ts-ignore | ||
accountObjectsResponse.result.account_objects[0].MaximumAmount, | ||
`9223372036854775807`, | ||
) | ||
}, | ||
TIMEOUT, | ||
) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider expanding test coverage for MPTokenIssuanceCreate.
The current test case effectively covers the basic functionality of creating an MPTokenIssuanceCreate transaction. To enhance the robustness of the test suite, consider adding the following test cases:
- Test with minimum valid values for required fields.
- Test with optional fields (if any) included.
- Test error cases, such as invalid
MaximumAmount
orAssetScale
values. - Test the behavior when attempting to create multiple issuances for the same account.
These additional tests would help ensure comprehensive coverage of the MPTokenIssuanceCreate functionality.
import { assert } from 'chai' | ||
|
||
import { validate, ValidationError, MPTokenAuthorizeFlags } from '../../src' | ||
|
||
const TOKEN_ID = '000004C463C52827307480341125DA0577DEFC38405B0E3E' | ||
|
||
/** | ||
* MPTokenAuthorize Transaction Verification Testing. | ||
* | ||
* Providing runtime verification testing for each specific transaction type. | ||
*/ | ||
describe('MPTokenAuthorize', function () { | ||
it(`verifies valid MPTokenAuthorize`, function () { | ||
let validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenHolder: 'rajgkBmMxmz161r8bWYH7CQAFZP5bA9oSG', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
MPTokenHolder: 'rajgkBmMxmz161r8bWYH7CQAFZP5bA9oSG', | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
}) | ||
|
||
it(`throws w/ missing MPTokenIssuanceID`, function () { | ||
const invalid = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
} as any | ||
|
||
assert.throws( | ||
() => validate(invalid), | ||
ValidationError, | ||
'MPTokenAuthorize: missing field MPTokenIssuanceID', | ||
) | ||
}) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Good start on MPTokenAuthorize tests, consider expanding coverage.
The current test suite provides a solid foundation for testing MPTokenAuthorize transactions. To further enhance the robustness and coverage of these tests, consider the following suggestions:
-
Edge Cases: Add tests for edge cases, such as maximum/minimum values for numeric fields, if any.
-
Boundary Testing: If there are any size limits on fields (e.g., MPTokenIssuanceID), test at and around these boundaries.
-
Flags Combinations: Test different combinations of flags to ensure they're handled correctly.
-
Integration Tests: Consider adding integration tests that verify the actual effects of MPTokenAuthorize transactions on the ledger state, if applicable.
-
Fuzz Testing: Implement some basic fuzz testing by providing random or semi-random input to the validate function to catch unexpected edge cases.
Example of a fuzz test:
it('handles fuzzed input gracefully', function() {
const fuzzCases = 100;
for (let i = 0; i < fuzzCases; i++) {
const fuzzed = {
TransactionType: 'MPTokenAuthorize',
Account: `r${Math.random().toString(36).substring(2, 15)}`,
MPTokenIssuanceID: Math.random().toString(36).substring(2, 15),
Flags: Math.floor(Math.random() * 100000),
};
assert.doesNotThrow(() => validate(fuzzed), 'Validation should not throw on fuzzed input');
}
});
These additions would significantly improve the test coverage and increase confidence in the MPTokenAuthorize transaction validation.
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
25-25: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
53-53: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
interface AmountObjectMPT extends JsonObject { | ||
value: string | ||
mpt_issuance_id: string | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use camelCase for property names in AmountObjectMPT
The property mpt_issuance_id
in the AmountObjectMPT
interface uses snake_case
, which is inconsistent with the standard camelCase naming convention in TypeScript and JavaScript. Consider renaming it to mptIssuanceId
to maintain consistency throughout the codebase.
Apply this change:
interface AmountObjectMPT extends JsonObject {
value: string
- mpt_issuance_id: string
+ mptIssuanceId: string
}
And update all references to mpt_issuance_id
accordingly.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
interface AmountObjectMPT extends JsonObject { | |
value: string | |
mpt_issuance_id: string | |
} | |
interface AmountObjectMPT extends JsonObject { | |
value: string | |
mptIssuanceId: string | |
} |
function isAmountObjectMPT(arg): arg is AmountObjectMPT { | ||
const keys = Object.keys(arg).sort() | ||
|
||
return ( | ||
keys.length === 2 && keys[0] === 'mpt_issuance_id' && keys[1] === 'value' | ||
) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Specify parameter type and validate property types in isAmountObjectMPT
Similar to isAmountObjectIOU
, the isAmountObjectMPT
function lacks a parameter type and doesn't validate the types of its properties. To improve type safety and ensure accurate type guarding, consider specifying the parameter type and checking property types.
Apply this change:
-function isAmountObjectMPT(arg): arg is AmountObjectMPT {
+function isAmountObjectMPT(arg: any): arg is AmountObjectMPT {
const keys = Object.keys(arg).sort()
return (
keys.length === 2 &&
keys[0] === 'mpt_issuance_id' &&
keys[1] === 'value'
+ && typeof arg.value === 'string'
+ && typeof arg.mpt_issuance_id === 'string'
)
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
function isAmountObjectMPT(arg): arg is AmountObjectMPT { | |
const keys = Object.keys(arg).sort() | |
return ( | |
keys.length === 2 && keys[0] === 'mpt_issuance_id' && keys[1] === 'value' | |
) | |
} | |
function isAmountObjectMPT(arg: any): arg is AmountObjectMPT { | |
const keys = Object.keys(arg).sort() | |
return ( | |
keys.length === 2 && | |
keys[0] === 'mpt_issuance_id' && | |
keys[1] === 'value' && | |
typeof arg.value === 'string' && | |
typeof arg.mpt_issuance_id === 'string' | |
) | |
} |
/** | ||
* Validate MPT.value amount | ||
* | ||
* @param decimal BigNumber object representing MPT.value | ||
* @returns void, but will throw if invalid amount | ||
*/ | ||
private static assertMptIsValid(amount: string): void { | ||
if (amount.indexOf('.') !== -1) { | ||
throw new Error(`${amount.toString()} is an illegal amount`) | ||
} | ||
|
||
const decimal = new BigNumber(amount) | ||
if (!decimal.isZero()) { | ||
if (decimal < BigNumber(0)) { | ||
throw new Error(`${amount.toString()} is an illegal amount`) | ||
} | ||
|
||
if (Number(BigInt(amount) & BigInt(mptMask)) != 0) { | ||
throw new Error(`${amount.toString()} is an illegal amount`) | ||
} | ||
} | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct the BigNumber comparison and fix parameter inconsistencies in assertMptIsValid
There are several issues in the assertMptIsValid
method:
-
Incorrect parameter documentation: The
@param
description mentionsdecimal: BigNumber
, but the method parameter isamount: string
. -
Incorrect BigNumber comparison: The comparison
if (decimal < BigNumber(0))
is invalid. Usedecimal.isLessThan(0)
instead. -
Instantiation of
BigNumber(0)
: Should benew BigNumber(0)
. -
Variable naming inconsistency: The parameter is named
amount
, but within the method, it's referred to asdecimal
.
Consider applying the following changes:
- * @param decimal BigNumber object representing MPT.value
+ * @param amount String representing MPT.value
-private static assertMptIsValid(amount: string): void {
+private static assertMptIsValid(value: string): void {
- if (amount.indexOf('.') !== -1) {
+ if (value.indexOf('.') !== -1) {
throw new Error(`${value.toString()} is an illegal amount`)
}
- const decimal = new BigNumber(amount)
+ const decimal = new BigNumber(value)
if (!decimal.isZero()) {
- if (decimal < BigNumber(0)) {
+ if (decimal.isLessThan(0)) {
throw new Error(`${value.toString()} is an illegal amount`)
}
- if (Number(BigInt(amount) & BigInt(mptMask)) != 0) {
+ if ((BigInt(value) & mptMask) !== BigInt(0)) {
throw new Error(`${value.toString()} is an illegal amount`)
}
}
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
/** | |
* Validate MPT.value amount | |
* | |
* @param decimal BigNumber object representing MPT.value | |
* @returns void, but will throw if invalid amount | |
*/ | |
private static assertMptIsValid(amount: string): void { | |
if (amount.indexOf('.') !== -1) { | |
throw new Error(`${amount.toString()} is an illegal amount`) | |
} | |
const decimal = new BigNumber(amount) | |
if (!decimal.isZero()) { | |
if (decimal < BigNumber(0)) { | |
throw new Error(`${amount.toString()} is an illegal amount`) | |
} | |
if (Number(BigInt(amount) & BigInt(mptMask)) != 0) { | |
throw new Error(`${amount.toString()} is an illegal amount`) | |
} | |
} | |
} | |
/** | |
* Validate MPT.value amount | |
* | |
* @param amount String representing MPT.value | |
* @returns void, but will throw if invalid amount | |
*/ | |
private static assertMptIsValid(value: string): void { | |
if (value.indexOf('.') !== -1) { | |
throw new Error(`${value.toString()} is an illegal amount`) | |
} | |
const decimal = new BigNumber(value) | |
if (!decimal.isZero()) { | |
if (decimal.isLessThan(0)) { | |
throw new Error(`${value.toString()} is an illegal amount`) | |
} | |
if ((BigInt(value) & mptMask) !== BigInt(0)) { | |
throw new Error(`${value.toString()} is an illegal amount`) | |
} | |
} | |
} |
typeof input.value === 'string' && | ||
typeof input.mpt_issuance_id === 'string' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure property names follow camelCase convention
The property mpt_issuance_id
uses snake_case, which is inconsistent with the camelCase convention used elsewhere (e.g., issuer
, currency
, value
). For consistency, consider renaming mpt_issuance_id
to mptIssuanceId
.
Apply this diff:
- typeof input.mpt_issuance_id === 'string'
+ typeof input.mptIssuanceId === 'string'
Also, ensure that all references to mpt_issuance_id
in the codebase are updated accordingly.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
typeof input.value === 'string' && | |
typeof input.mpt_issuance_id === 'string' | |
typeof input.value === 'string' && | |
typeof input.mptIssuanceId === 'string' |
return ( | ||
typeof amount === 'string' || | ||
isIssuedCurrency(amount) || | ||
isMPTAmount(amount) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Complete the renaming of mpt_issuance_id
to mptIssuanceId
Multiple instances of mpt_issuance_id
were found across the codebase, indicating that the renaming to mptIssuanceId
is incomplete. Please update all remaining occurrences to ensure consistency and prevent potential issues.
packages/xrpl/src/models/methods/ledgerEntry.ts
packages/xrpl/src/models/transactions/common.ts
packages/xrpl/src/client/partialPayment.ts
packages/xrpl/src/models/common/index.ts
packages/xrpl/test/models/payment.test.ts
packages/xrpl/test/models/clawback.test.ts
packages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts
packages/xrpl/test/integration/transactions/payment.test.ts
packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts
packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts
packages/ripple-binary-codec/src/types/amount.ts
packages/ripple-binary-codec/test/binary-parser.test.ts
packages/ripple-binary-codec/test/amount.test.ts
🔗 Analysis chain
Update references in isAmount
after renaming the property
After renaming mpt_issuance_id
to mptIssuanceId
, ensure that the isMPTAmount
function and any usage align with this change.
Run the following script to find all occurrences of mpt_issuance_id
:
This will help identify any remaining instances that need to be updated.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Find all references to `mpt_issuance_id` in the codebase.
# Test: Search for the string `mpt_issuance_id`. Expect: No occurrences after renaming.
rg --type ts 'mpt_issuance_id'
Length of output: 3020
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (2)
packages/ripple-binary-codec/test/uint.test.ts (2)
99-116
: LGTM: Well-structured MPT issuance entry test dataThe test data for MPT issuance entry is comprehensive and well-structured. However, consider the following suggestions:
The
MPTokenMetadata
field contains encoded JSON data. For better readability and easier maintenance of tests, consider decoding this data and storing it as a separate constant. This would make it easier to update the metadata if needed.The
MaximumAmount
andOutstandingAmount
fields are stored as strings. Consider using BigInt for these large numbers to ensure precise handling in JavaScript.Would you like me to provide an example of how to decode the
MPTokenMetadata
and use BigInt for the amount fields?
182-188
: LGTM: Comprehensive test case for MPT data encoding and decodingThe new test case effectively verifies both encoding and decoding of MPT issuance and token entries. This ensures that the binary codec correctly handles the new MPT-related data structures.
Consider updating the test description to more accurately reflect its purpose:
-it('UInt64 is parsed as base 10 for MPT amounts', () => { +it('Correctly encodes and decodes MPT issuance and token entries', () => {This description better captures the full scope of what the test is verifying.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (3)
- packages/ripple-binary-codec/src/types/st-object.ts (3 hunks)
- packages/ripple-binary-codec/src/types/uint-64.ts (4 hunks)
- packages/ripple-binary-codec/test/uint.test.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/ripple-binary-codec/src/types/st-object.ts
🧰 Additional context used
🪛 Gitleaks
packages/ripple-binary-codec/test/uint.test.ts
123-123: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🔇 Additional comments (7)
packages/ripple-binary-codec/src/types/uint-64.ts (5)
5-5
: LGTM: New import and constant added.The new import and constant are appropriate for the changes made to the UInt64 class. The BASE10_REGEX will be useful for validating base 10 strings in the updated methods.
Also applies to: 8-8
Line range hint
1-134
: LGTM: Overall changes enhance UInt64 functionality.The modifications to the UInt64 class successfully introduce support for base 10 string representations while maintaining compatibility with the existing hexadecimal format. The changes are well-integrated into the existing code structure and consistent with the overall style of the file.
11-17
: 🛠️ Refactor suggestionConsider using a Set for field names in
useBase10
function.To enhance scalability and performance, especially if more fields are added in the future, consider using a
Set
to store field names. This approach simplifies the addition of new fields and improves lookup efficiency.Apply this refactor:
+const BASE10_FIELDS = new Set(['MaximumAmount', 'OutstandingAmount', 'MPTAmount']) -function useBase10(fieldName: string): boolean { - return ( - fieldName === 'MaximumAmount' || - fieldName === 'OutstandingAmount' || - fieldName === 'MPTAmount' - ) +function useBase10(fieldName: string): boolean { + return BASE10_FIELDS.has(fieldName) }
42-45
:⚠️ Potential issueRemove unnecessary type casting in base 10 to hex conversion.
The changes to handle both hexadecimal and base 10 string inputs are good. However, there's an unnecessary type casting after converting the base 10 string to hexadecimal.
Apply this fix:
- val = BigInt(val).toString(16) as T + val = BigInt(val).toString(16)Also applies to: 67-73
99-108
:⚠️ Potential issueRemove unused parameter
_definitions
intoJSON
method.The changes to return both hexadecimal and base 10 string representations are good. However, the
_definitions
parameter is not utilized within the method.Apply this change:
- toJSON( - _definitions: XrplDefinitionsBase = DEFAULT_DEFINITIONS, - fieldName: string = '', - ): string { + toJSON(fieldName: string = ''): string {packages/ripple-binary-codec/test/uint.test.ts (2)
2-2
: LGTM: Import statement updated correctlyThe
decode
function has been added to the import statement, which is necessary for the new test cases that verify both encoding and decoding of MPT-related data.
Line range hint
1-188
: Summary: Comprehensive MPT-related test additions with minor improvement suggestionsThe changes to this file significantly enhance the test coverage for Multi-Purpose Token (MPT) related functionality. The additions include well-structured test data for MPT issuance and token entries, along with appropriate test cases to verify encoding and decoding processes.
Key points:
- The
decode
function import has been correctly added.- Comprehensive test data for MPT issuance and token entries has been introduced.
- A new test case effectively verifies the encoding and decoding of MPT-related structures.
Suggestions for improvement:
- Consider decoding the
MPTokenMetadata
in the test data for better readability.- Use BigInt for large number fields like
MaximumAmount
andOutstandingAmount
.- Replace the
MPTokenIssuanceID
with a clearly marked test value.- Update the test case description to better reflect its purpose.
Overall, these changes provide robust testing for the new MPT functionality. After addressing the minor suggestions, this PR is ready for approval.
🧰 Tools
🪛 Gitleaks
123-123: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
const mptokenEntryJson = { | ||
Account: 'raDQsd1s8rqGjL476g59a9vVNi1rSwrC44', | ||
Flags: 0, | ||
LedgerEntryType: 'MPToken', | ||
MPTAmount: '100', | ||
MPTokenIssuanceID: '000002DF71CAE59C9B7E56587FFF74D4EA5830D9BE3CE0CC', | ||
OwnerNode: '0000000000000000', | ||
PreviousTxnID: | ||
'222EF3C7E82D8A44984A66E2B8E357CB536EC2547359CCF70E56E14BC4C284C8', | ||
PreviousTxnLgrSeq: 741, | ||
} | ||
|
||
const mptokenEntryBinary = | ||
'11007F220000000025000002E5340000000000000000301A000000000000006455222EF3C7E82D8A44984A66E2B8E357CB536EC2547359CCF70E56E14BC4C284C881143930DB9A74C26D96CB58ADFFD7E8BB78BCFE62340115000002DF71CAE59C9B7E56587FFF74D4EA5830D9BE3CE0CC' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM: Well-structured MPT token entry test data
The test data for MPT token entry is well-structured and appropriate. However, there's a potential security concern:
The MPTokenIssuanceID
field contains a value that resembles a generic API key or sensitive identifier. While this is likely just test data, it's good practice to use clearly identifiable mock data to prevent any confusion or potential security risks.
Consider replacing the MPTokenIssuanceID
value with a clearly marked test value, such as:
- MPTokenIssuanceID: '000002DF71CAE59C9B7E56587FFF74D4EA5830D9BE3CE0CC',
+ MPTokenIssuanceID: 'TEST_MPT_ISSUANCE_ID_000002DF71CAE59C9B7E56587FFF74D',
This change should also be reflected in the mptokenEntryBinary
constant to maintain consistency between the JSON and binary representations.
Committable suggestion was skipped due to low confidence.
🧰 Tools
🪛 Gitleaks
123-123: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (9)
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (2)
13-41
: LGTM: Valid scenarios are well-covered.The test case effectively covers basic valid scenarios for MPTokenIssuanceSet, including required fields, optional fields, and the case without flags.
Consider adding more test cases for comprehensive coverage, as suggested in the previous review:
- Validate with invalid Account address format.
- Validate with invalid MPTokenIssuanceID format.
- Test with invalid MPTokenHolder address format (when present).
- Verify behavior with unexpected additional fields.
- Test with edge cases for flag values (e.g., maximum allowed value, negative values).
- Validate with all possible individual flags to ensure they don't conflict with themselves.
These additional test cases would provide more thorough coverage and help catch potential edge cases in the validation logic.
🧰 Tools
🪛 Gitleaks
26-26: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
37-37: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
56-72
: LGTM: Proper validation of conflicting flags.This test case effectively verifies that the validation throws an error when conflicting flags (tfMPTLock and tfMPTUnlock) are set. The use of bitwise operations and ESLint rule management is appropriate.
For improved clarity, consider adding a comment explaining why these specific flags are conflicting. For example:
// tfMPTLock and tfMPTUnlock are mutually exclusive flags const conflictingFlags = MPTokenIssuanceSetFlags.tfMPTLock | MPTokenIssuanceSetFlags.tfMPTUnlock;This would help other developers understand the test case's purpose more quickly.
packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (2)
9-44
: LGTM: Well-documented MPTokenIssuanceCreateFlags enum.The
MPTokenIssuanceCreateFlags
enum is comprehensive and well-documented, covering various aspects of MP Token behavior.Consider adding a brief comment above the enum to explain what MP stands for (Multi-Party) for better clarity:
/** * Transaction Flags for an MPTokenIssuanceCreate (Multi-Party Token Issuance Create) Transaction. * * @category Transaction Flags */ export enum MPTokenIssuanceCreateFlags { // ... existing code }
61-102
: LGTM: MPTokenIssuanceCreate interface is comprehensive and well-documented.The
MPTokenIssuanceCreate
interface is well-structured, with clear documentation for each property. The types are appropriate for their intended use, and theFlags
property allows for both number and interface types, providing good flexibility.Consider adding a note about the recommended way to handle the
MaximumAmount
string to prevent potential issues with JavaScript's number limitations:/** * Specifies the maximum asset amount of this token that should ever be issued. * It is a non-negative integer that can store a range of up to 63 bits. If not set, the max * amount will default to the largest unsigned 63-bit integer (0x7FFFFFFFFFFFFFFF or 9223372036854775807) * * Note: Use BigInt when working with this value to avoid potential issues with JavaScript's number limitations. * * Example: * ``` * MaximumAmount: '9223372036854775807' * ``` */ MaximumAmount?: stringpackages/xrpl/test/integration/transactions/payment.test.ts (1)
183-195
: LGTM with suggestions: Final account objects check and assertion.The final account objects check and assertion on OutstandingAmount are correct. However, there are two areas for improvement:
- Consider adding a null check for
account_objects
before accessing its first element.- The
@ts-expect-error
comment is masking a type issue. It's better to properly type theaccount_objects
or use a type assertion if the type is known.Here's a suggested refactor to address these issues:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: testContext.wallet.classicAddress, type: 'mpt_issuance', }) if (accountObjectsResponse.result.account_objects && accountObjectsResponse.result.account_objects.length > 0) { const mptIssuance = accountObjectsResponse.result.account_objects[0] as { OutstandingAmount: string } assert.equal( mptIssuance.OutstandingAmount, '100', 'OutstandingAmount should be 100' ) } else { assert.fail('Expected at least one MPT issuance object') }This refactor adds a null check for
account_objects
, uses a type assertion instead of@ts-expect-error
, and improves the assertion message.packages/xrpl/test/integration/transactions/clawback.test.ts (2)
124-146
: LGTM with suggestion: MPToken creation and retrieval.The logic for creating an MPToken and retrieving its issuance ID is sound. However, consider adding a null check for
mpt_issuance_id
to handle potential edge cases more safely.Consider replacing:
const mptID = meta.mpt_issuance_idwith:
const mptID = meta.mpt_issuance_id if (!mptID) { throw new Error('Failed to retrieve mpt_issuance_id') }This ensures that the test fails explicitly if the
mpt_issuance_id
is not present in the metadata.
121-207
: Overall assessment: Good addition with room for improvement.The new MPToken Clawback test case is a valuable addition to the test suite, covering the essential steps of the process. However, there are some recurring issues that should be addressed:
- Type mismatches: Update type definitions or use consistent type assertions to resolve
@ts-expect-error
comments.- Null checks: Add proper null checks when accessing properties of API responses.
- Error handling: Implement checks to ensure each step (e.g., MPToken authorization) is successful before proceeding.
- Calculation precision: Use BigInt for large number calculations to prevent potential precision issues.
Addressing these points will significantly improve the robustness and reliability of the test case.
Consider creating helper functions for common operations like ledger entry verification and MPToken operations. This would reduce code duplication and make the tests more maintainable. For example:
function verifyMPTAmount(response: LedgerEntryResponse, expectedAmount: string) { assert.exists(response.result, 'Ledger entry result should exist') assert.exists(response.result.node, 'Ledger entry node should exist') assert.equal( (response.result.node as any).MPTAmount, expectedAmount, `MPTAmount should be ${expectedAmount}` ) }This function could then be used in both verification steps, making the test more concise and easier to maintain.
packages/xrpl/src/client/partialPayment.ts (1)
40-51
: LGTM: MPTAmount comparison logic addedThe new conditional block correctly handles MPTAmount comparisons, including checking the
mpt_issuance_id
and value. It also properly handles mixed type comparisons by returning false when only one amount is an MPTAmount.Consider combining the two separate checks for
isMPTAmount
to reduce code duplication:if (isMPTAmount(amt1) || isMPTAmount(amt2)) { if (isMPTAmount(amt1) && isMPTAmount(amt2)) { const aValue = new BigNumber(amt1.value) const bValue = new BigNumber(amt2.value) return amt1.mpt_issuance_id === amt2.mpt_issuance_id && aValue.isEqualTo(bValue) } return false }This slight refactor maintains the same logic while reducing the number of
isMPTAmount
checks.packages/xrpl/src/models/transactions/transaction.ts (1)
Missing Unit Tests for New MPT-related Transactions
The new MPT-related transaction files have been successfully added to the codebase. However, the corresponding unit test files are missing in
packages/xrpl/test/models/transactions
. It's essential to implement these tests to ensure the reliability and correctness of the new transaction functionalities.
- Create the
packages/xrpl/test/models/transactions
directory if it doesn't exist.- Add
.test.ts
files for each of the following transactions:
MPTokenAuthorize
MPTokenIssuanceCreate
MPTokenIssuanceDestroy
MPTokenIssuanceSet
Implementing these tests will help maintain the integrity of the codebase and prevent potential issues related to the newly introduced transactions.
🔗 Analysis chain
Line range hint
30-341
: Overall assessment: MPT support successfully integrated.The changes in this file successfully integrate support for new Multi-Party Token (MPT) related transactions. The additions are consistent across imports, type definitions, and validation logic, following the established patterns in the codebase. These changes enhance the transaction processing capabilities of the system without disrupting existing functionality.
However, to ensure comprehensive coverage:
- Verify that the imported MPT-related modules exist and are correctly implemented.
- Confirm that unit tests have been added or updated for these new transaction types.
Run the following script to check for the existence of the new MPT-related files and potential test files:
This script will help verify the existence of the necessary files and potential test files for the new MPT-related transactions.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for the existence of new MPT-related files and potential test files echo "Checking for MPT-related files:" for file in MPTokenAuthorize MPTokenIssuanceCreate MPTokenIssuanceDestroy MPTokenIssuanceSet; do if fd -t f "${file}.ts" packages/xrpl/src/models/transactions; then echo "✅ ${file}.ts found" else echo "❌ ${file}.ts not found" fi done echo -e "\nChecking for potential test files:" for file in MPTokenAuthorize MPTokenIssuanceCreate MPTokenIssuanceDestroy MPTokenIssuanceSet; do if fd -t f "${file}.test.ts" packages/xrpl/test/models/transactions; then echo "✅ ${file}.test.ts found" else echo "❌ ${file}.test.ts not found" fi doneLength of output: 2904
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (14)
- packages/xrpl/src/client/partialPayment.ts (2 hunks)
- packages/xrpl/src/models/ledger/index.ts (2 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (1 hunks)
- packages/xrpl/src/models/transactions/metadata.ts (3 hunks)
- packages/xrpl/src/models/transactions/transaction.ts (3 hunks)
- packages/xrpl/src/models/utils/flags.ts (2 hunks)
- packages/xrpl/test/integration/transactions/clawback.test.ts (2 hunks)
- packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts (1 hunks)
- packages/xrpl/test/integration/transactions/payment.test.ts (2 hunks)
- packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
- packages/xrpl/src/models/ledger/index.ts
- packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts
- packages/xrpl/src/models/transactions/metadata.ts
- packages/xrpl/src/models/utils/flags.ts
- packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts
- packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts
- packages/xrpl/test/integration/transactions/mptokenIssuanceSet.test.ts
🧰 Additional context used
🪛 Biome
packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts
[error] 72-72: Can't assign accountObjectsResponse because it's a constant
This is where the variable is defined as constant
Unsafe fix: Replace const with let if you assign it to a new value.
(lint/correctness/noConstAssign)
🪛 Gitleaks
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
26-26: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
37-37: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🔇 Additional comments (26)
packages/xrpl/test/integration/transactions/mptokenIssuanceDestroy.test.ts (4)
1-17
: LGTM: Imports and constant definition are appropriate.The necessary modules and types are imported correctly. The TIMEOUT constant is well-defined and helps prevent long-running tests.
19-25
: LGTM: Test setup and teardown are well-structured.The use of beforeEach and afterEach hooks ensures a clean test environment for each test case. This is crucial for integration tests to prevent interference between test runs.
1-85
: Summary: Well-structured test with minor improvement opportunities.This integration test for MPTokenIssuanceDestroy is comprehensive and covers the full lifecycle of an MPToken issuance. The test structure, including setup and teardown, is well-implemented. The suggested improvements around error handling, variable declarations, and assertion messages will further enhance the test's robustness and clarity.
Overall, good job on implementing this crucial test for the new MPToken functionality!
🧰 Tools
🪛 Biome
[error] 72-72: Can't assign accountObjectsResponse because it's a constant
This is where the variable is defined as constant
Unsafe fix: Replace const with let if you assign it to a new value.
(lint/correctness/noConstAssign)
27-84
: 🛠️ Refactor suggestion
⚠️ Potential issueOverall good test structure, but some improvements needed.
The test case effectively covers the lifecycle of an MPToken issuance. However, there are a few areas that could be enhanced:
- Error handling: Consider adding checks for potential errors in API responses.
- Constant reassignment: There's an attempt to reassign a const variable on line 72.
- Assertion messages: Some assertion messages could be more descriptive.
To address these issues:
- Add error checks after API calls. For example:
const txResponse = await testContext.client.request({ command: 'tx', transaction: txHash, }) assert.isNotNull(txResponse.result, 'Transaction response should not be null')
- Change the
const
declaration tolet
foraccountObjectsResponse
:-const accountObjectsResponse = await testContext.client.request({ +let accountObjectsResponse = await testContext.client.request({
- Enhance assertion messages:
-'Should be exactly one issuance on the ledger', +'Should be exactly one MPToken issuance on the ledger after creation',-'Should be zero issuance on the ledger', +'Should be zero MPToken issuances on the ledger after destruction',Consider extracting the account_objects request into a separate function for reusability:
async function getAccountObjects(client, account, type) { return client.request({ command: 'account_objects', account, type, }) }This would make the test more readable and reduce duplication.
To ensure the MPTokenIssuanceDestroy transaction is correctly implemented, we should verify its usage across the codebase:
This script will help us identify any potential issues or incomplete implementations related to MPTokenIssuanceDestroy across the project.
🧰 Tools
🪛 Biome
[error] 72-72: Can't assign accountObjectsResponse because it's a constant
This is where the variable is defined as constant
Unsafe fix: Replace const with let if you assign it to a new value.
(lint/correctness/noConstAssign)
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (3)
43-54
: LGTM: Proper validation of missing required field.This test case correctly verifies that the validation throws an error when the required MPTokenIssuanceID field is missing. The error message is specific and helpful for debugging.
1-73
: Overall, the test suite is well-structured and covers key scenarios.The MPTokenIssuanceSet test file provides good coverage of basic valid and invalid scenarios. The test cases are clear and use appropriate assertions.
To further enhance this test suite:
- Consider adding more edge cases and invalid input scenarios as suggested earlier.
- Add a brief comment explaining the conflicting flags in the last test case.
These improvements will make the test suite more comprehensive and easier to understand for other developers.
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
26-26: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
37-37: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
1-5
: LGTM: Imports and constants are appropriate.The imports and constant definition look good. They provide the necessary tools and values for the test cases.
Regarding the Gitleaks warning about a potential API key:
This should help determine if the TOKEN_ID is indeed just a test constant and not an actual API key.
✅ Verification successful
Verified: TOKEN_ID is used exclusively in test files and is not an API key.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify if TOKEN_ID is used elsewhere in the codebase rg --type typescript "000004C463C52827307480341125DA0577DEFC38405B0E3E"Length of output: 106
Script:
#!/bin/bash # Verify if TOKEN_ID is used elsewhere in the codebase rg --type ts "000004C463C52827307480341125DA0577DEFC38405B0E3E"Length of output: 907
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (3)
1-7
: LGTM: Imports and constants are well-defined.The imports are appropriate for the functionality being implemented, and the
SANITY_CHECK
regex constant is correctly defined for validating numeric strings.
46-59
: LGTM: MPTokenIssuanceCreateFlagsInterface is well-defined.The
MPTokenIssuanceCreateFlagsInterface
correctly extendsGlobalFlags
and provides optional boolean properties for each flag defined in theMPTokenIssuanceCreateFlags
enum. This interface enhances type safety when working with MP Token issuance flags in transactions.
104-106
: LGTM: MPTokenIssuanceCreateMetadata interface is correctly defined.The
MPTokenIssuanceCreateMetadata
interface appropriately extendsTransactionMetadataBase
and adds an optionalmpt_issuance_id
property of type string. This structure is suitable for representing the metadata of an MP Token issuance transaction.packages/xrpl/test/integration/transactions/payment.test.ts (5)
3-9
: LGTM: New imports for MPT functionality.The new imports (MPTokenIssuanceCreate, MPTokenAuthorize, TransactionMetadata) are correctly added and necessary for the new MPT Payment test case.
112-115
: LGTM: New test case for MPT Payment validation.The new test case "Validate MPT Payment" is properly structured and uses the consistent TIMEOUT constant.
115-126
: LGTM: Wallet generation and MPTokenIssuanceCreate transaction.The code correctly generates a new wallet and creates an MPTokenIssuanceCreate transaction. The transaction is properly executed using the testTransaction helper function.
171-181
: LGTM with suggestion: Payment transaction with MPT.The Payment transaction is correctly structured for MPT and executed properly. However, consider adding a null check for
mptID
before using it in the Amount field.To ensure
mptID
is always defined before using it in the Payment transaction, you can add a check:#!/bin/bash # Description: Verify that mptID is checked before use in Payment transaction # Test: Search for Payment transaction creation with MPT rg --type typescript -A 10 'TransactionType: .Payment.,' # Expected: Should find code that checks if mptID is defined before using it in the Amount field
151-169
: LGTM with suggestion: MPTokenAuthorize transaction and verification.The MPTokenAuthorize transaction is correctly created and executed, with appropriate verification of MPToken ownership. However, consider adding a null check for
mptID
before using it in the MPTokenIssuanceID field.To ensure
mptID
is always defined before using it in MPTokenAuthorize, you can add a check:✅ Verification successful
Verified: MPTokenAuthorize transaction usage is safe.
All instances of
MPTokenAuthorize
correctly utilizemptID
within test files where its validity is ensured. There are no occurrences in the production code that lack necessary null checks.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that mptID is checked before use in MPTokenAuthorize # Test: Search for MPTokenAuthorize transaction creation rg --type typescript -A 5 "MPTokenAuthorize = {" # Expected: Should find code that checks if mptID is defined before using it in MPTokenIssuanceIDLength of output: 93
Script:
#!/bin/bash # Description: Verify that mptID is checked before use in MPTokenAuthorize # Search for MPTokenAuthorize transaction creation in TypeScript files rg --glob '*.ts' -A 10 'MPTokenAuthorize\s*=\s*{' # Expected: The found code should include a check to ensure mptID is defined before using it in MPTokenIssuanceIDLength of output: 163
Script:
#!/bin/bash # Description: Verify that mptID is checked before use in MPTokenAuthorize # Search for MPTokenAuthorize transaction creation in TypeScript files with corrected regex rg --glob '*.ts' -A 10 'MPTokenAuthorize\s*=\s*\{' # Expected: The found code should include a check to ensure mptID is defined before using it in MPTokenIssuanceIDLength of output: 7103
packages/xrpl/test/integration/transactions/clawback.test.ts (4)
9-13
: LGTM: New imports for MPToken functionality.The added imports are necessary for the new MPToken test case and correctly sourced from the main package.
121-123
: LGTM: New test case for MPToken.The new test case is well-named and consistent with the existing structure, using the same TIMEOUT constant.
181-190
: LGTM: Clawback transaction structure.The Clawback transaction is well-structured with the correct fields:
- TransactionType is set to 'Clawback'
- Account is set to the issuer's address
- Amount specifies the MPT issuance ID and a partial clawback value
- MPTokenHolder is correctly set to wallet2's address
The use of a partial clawback amount (500) is appropriate for testing this scenario.
148-163
: Verify MPToken authorization and payment amount.The MPToken authorization and payment steps are logically structured. However, there are two points to consider:
There's no check to ensure the MPTokenAuthorize transaction was successful before proceeding with the payment.
The payment amount is set to the maximum 64-bit integer value, which might be intentional for testing but could also be an oversight.
Consider adding a check for the success of the MPTokenAuthorize transaction:
const authResult = await testTransaction(testContext.client, holderAuthTx, wallet2) assert.equal(authResult.result.meta.TransactionResult, 'tesSUCCESS', 'MPToken authorization failed')
- Verify if using the maximum 64-bit integer value for the payment amount is intentional:
If this is a common pattern in your tests, please disregard this point. Otherwise, consider using a more typical test value.
✅ Verification successful
MPToken authorization and payment amount verified.
The use of the maximum 64-bit integer value for the payment amount is consistently applied across multiple test files, indicating it's intentional for testing purposes.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for similar large integer values in test files rg --type typescript '9223372036854775807' packages/xrpl/testLength of output: 96
Script:
#!/bin/bash # Corrected search for similar large integer values in TypeScript test files rg --type ts '9223372036854775807' packages/xrpl/testLength of output: 650
packages/xrpl/src/client/partialPayment.ts (4)
9-15
: LGTM: Import statements updated appropriatelyThe new imports for
IssuedCurrency
,MPTAmount
, andisMPTAmount
are correctly added to support the changes in theamountsEqual
function. The inclusion ofAPIVersion
andDEFAULT_API_VERSION
is also appropriate for potential usage in the file.Also applies to: 22-22
28-31
: LGTM: Function signature updated to support MPTAmountThe
amountsEqual
function signature has been appropriately updated to accept bothAmount
andMPTAmount
types. This change enhances the function's flexibility and aligns with the introduction of multi-party token support.
57-58
: LGTM: Type assertions added for IssuedCurrency comparisonThe type assertions
(amt1 as IssuedCurrency)
and(amt2 as IssuedCurrency)
have been correctly added when accessing thecurrency
andissuer
properties. This change maintains type safety while allowing the function to handle bothAmount
andMPTAmount
types.
Line range hint
1-214
: Summary: MPTAmount support added to amountsEqual functionThe changes in this file successfully introduce support for MPTAmount in the
amountsEqual
function. The modifications are well-implemented and maintain backwards compatibility with existing Amount types. The code is clean, and the logic is sound.To ensure that these changes don't introduce any regressions, please run the following verification script:
This script will help identify any other parts of the codebase that might need to be updated to accommodate the new
amountsEqual
function signature, as well as any related test files that might need adjustment.packages/xrpl/src/models/transactions/transaction.ts (3)
30-42
: LGTM: New MPT-related imports added correctly.The new import statements for MPT-related modules are well-structured and follow the existing pattern in the file. They include both the transaction types and their corresponding validation functions, maintaining consistency with other imports.
131-134
: LGTM: SubmittableTransaction type updated with new MPT transactions.The SubmittableTransaction type has been correctly updated to include the new MPT-related transaction types. The additions are well-placed in alphabetical order, maintaining the existing structure of the type definition.
326-341
: LGTM: Validate function updated to handle new MPT transactions.The validate function has been correctly updated with new case statements for the MPT-related transactions. Each case appropriately calls its corresponding validation function, and the additions are placed in alphabetical order, maintaining consistency with the existing structure.
/** | ||
* Verify the form and type of an MPTokenIssuanceCreate at runtime. | ||
* | ||
* @param tx - An MPTokenIssuanceCreate Transaction. | ||
* @throws When the MPTokenIssuanceCreate is Malformed. | ||
*/ | ||
export function validateMPTokenIssuanceCreate( | ||
tx: Record<string, unknown>, | ||
): void { | ||
validateBaseTransaction(tx) | ||
|
||
if (typeof tx.MPTokenMetadata === 'string' && tx.MPTokenMetadata === '') { | ||
throw new ValidationError( | ||
'MPTokenIssuanceCreate: MPTokenMetadata must not be empty string', | ||
) | ||
} | ||
|
||
if (typeof tx.MPTokenMetadata === 'string' && !isHex(tx.MPTokenMetadata)) { | ||
throw new ValidationError( | ||
'MPTokenIssuanceCreate: MPTokenMetadata must be in hex format', | ||
) | ||
} | ||
|
||
if (typeof tx.MaximumAmount === 'string') { | ||
if (!SANITY_CHECK.exec(tx.MaximumAmount)) { | ||
throw new ValidationError('MPTokenIssuanceCreate: Invalid MaximumAmount') | ||
} else if ( | ||
BigInt(tx.MaximumAmount) > BigInt(`9223372036854775807`) || | ||
BigInt(tx.MaximumAmount) < BigInt(`0`) | ||
) { | ||
throw new ValidationError( | ||
'MPTokenIssuanceCreate: MaximumAmount out of range', | ||
) | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enhance validation in validateMPTokenIssuanceCreate function.
While the current implementation covers basic validation, there are several areas where it can be improved:
- Add validation for
AssetScale
andTransferFee
as mentioned in the past review comments. - Enhance
MaximumAmount
validation to handle potential BigInt conversion errors. - Update
MPTokenMetadata
validation to handle null values.
Here's a suggested implementation with these improvements:
export function validateMPTokenIssuanceCreate(
tx: Record<string, unknown>,
): void {
validateBaseTransaction(tx)
if (tx.MPTokenMetadata !== null) {
if (typeof tx.MPTokenMetadata !== 'string') {
throw new ValidationError(
'MPTokenIssuanceCreate: MPTokenMetadata must be a string or null',
)
}
if (tx.MPTokenMetadata === '') {
throw new ValidationError(
'MPTokenIssuanceCreate: MPTokenMetadata must not be empty string',
)
}
if (!isHex(tx.MPTokenMetadata)) {
throw new ValidationError(
'MPTokenIssuanceCreate: MPTokenMetadata must be in hex format',
)
}
}
if (typeof tx.AssetScale !== 'undefined') {
if (typeof tx.AssetScale !== 'number' || !Number.isInteger(tx.AssetScale) || tx.AssetScale < 0) {
throw new ValidationError('MPTokenIssuanceCreate: Invalid AssetScale')
}
}
if (typeof tx.TransferFee !== 'undefined') {
if (typeof tx.TransferFee !== 'number' || tx.TransferFee < 0 || tx.TransferFee > 50000) {
throw new ValidationError('MPTokenIssuanceCreate: Invalid TransferFee')
}
const flags = tx.Flags ?? 0
const canTransferFlag = typeof flags === 'number'
? (flags & MPTokenIssuanceCreateFlags.tfMPTCanTransfer) !== 0
: flags.tfMPTCanTransfer === true
if (!canTransferFlag) {
throw new ValidationError('MPTokenIssuanceCreate: TransferFee must not be present if tfMPTCanTransfer flag is not set')
}
}
if (typeof tx.MaximumAmount === 'string') {
if (!SANITY_CHECK.exec(tx.MaximumAmount)) {
throw new ValidationError('MPTokenIssuanceCreate: Invalid MaximumAmount')
}
try {
const amount = BigInt(tx.MaximumAmount)
if (amount > BigInt('9223372036854775807') || amount < BigInt('0')) {
throw new ValidationError(
'MPTokenIssuanceCreate: MaximumAmount out of range',
)
}
} catch (error) {
throw new ValidationError('MPTokenIssuanceCreate: Invalid MaximumAmount')
}
}
}
This implementation addresses the mentioned issues and provides more robust validation for the MPTokenIssuanceCreate
transaction.
const txHash = mptCreateRes.result.tx_json.hash | ||
|
||
const txResponse = await testContext.client.request({ | ||
command: 'tx', | ||
transaction: txHash, | ||
}) | ||
|
||
const meta = txResponse.result | ||
.meta as TransactionMetadata<MPTokenIssuanceCreate> | ||
|
||
const mptID = meta.mpt_issuance_id | ||
|
||
let accountObjectsResponse = await testContext.client.request({ | ||
command: 'account_objects', | ||
account: testContext.wallet.classicAddress, | ||
type: 'mpt_issuance', | ||
}) | ||
assert.lengthOf( | ||
accountObjectsResponse.result.account_objects, | ||
1, | ||
'Should be exactly one issuance on the ledger', | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Potential Issue: mptID
is used without null checks.
The code utilizes mptID!
to assert that mptID
is non-null. However, there are no prior checks to ensure that mptID
is defined. This could lead to runtime errors if mptID
is ever undefined
or null
.
Recommendation:
- Add a null or undefined check for
mptID
before using it with the non-null assertion operator.
For example:
if (mptID) {
const holderAuthTx: MPTokenAuthorize = {
TransactionType: 'MPTokenAuthorize',
Account: wallet2.classicAddress,
MPTokenIssuanceID: mptID,
};
await testTransaction(testContext.client, holderAuthTx, wallet2);
} else {
// Handle the case where mptID is undefined or null
throw new Error('mptID is undefined.');
}
🔗 Analysis chain
LGTM with suggestion: Transaction metadata retrieval and account objects check.
The code correctly retrieves the transaction metadata and checks the account objects. However, consider adding a null check for mptID
before using it with the non-null assertion operator (!).
To ensure mptID
is always defined, you can add a check:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that mptID is always defined in the MPTokenIssuanceCreate metadata
# Test: Search for MPTokenIssuanceCreate metadata handling
rg --type typescript -A 10 "meta as TransactionMetadata<MPTokenIssuanceCreate>"
# Expected: Should find code that checks if mptID is defined before using it
Length of output: 116
Script:
#!/bin/bash
# Description: Verify that mptID is always defined in the MPTokenIssuanceCreate metadata
# Test: Search for MPTokenIssuanceCreate metadata handling and check for null checks on mptID in .ts files
rg "meta as TransactionMetadata<MPTokenIssuanceCreate>" -A 10 --glob "*.ts"
Length of output: 5652
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (3)
packages/xrpl/src/client/partialPayment.ts (3)
28-33
: LGTM: ESLint comments and function signature updated correctly.The ESLint comments are necessary due to the increased complexity of the function. The
amountsEqual
function signature is correctly updated to includeMPTAmount
.Consider adding a TODO comment to revisit and potentially refactor this function in the future to reduce complexity:
// TODO: Consider refactoring this function to reduce complexity function amountsEqual( amt1: Amount | MPTAmount, amt2: Amount | MPTAmount, ): boolean {
43-55
: LGTM: MPT comparison logic implemented correctly.The new logic for comparing MPT amounts is well-implemented. The use of BigNumber ensures precise numerical comparisons, which is crucial for financial calculations.
Consider a minor optimization to reduce redundant type checking:
if (isMPTAmount(amt1) || isMPTAmount(amt2)) { if (isMPTAmount(amt1) && isMPTAmount(amt2)) { const aValue = new BigNumber(amt1.value) const bValue = new BigNumber(amt2.value) return amt1.mpt_issuance_id === amt2.mpt_issuance_id && aValue.isEqualTo(bValue) } return false }This change combines the MPT-related checks, potentially improving readability and slightly reducing the number of type checks performed.
57-63
: LGTM: Issued currency comparison logic updated correctly.The logic for comparing issued currencies (IOUs) is correctly implemented, using BigNumber for precise value comparison.
Consider improving type safety by using type guards instead of type assertions:
function isIssuedCurrency(amount: Amount | MPTAmount): amount is IssuedCurrency { return typeof amount === 'object' && 'currency' in amount && 'issuer' in amount; } // In the comparison logic: if (isIssuedCurrency(amt1) && isIssuedCurrency(amt2)) { const aValue = new BigNumber(amt1.value) const bValue = new BigNumber(amt2.value) return ( amt1.currency === amt2.currency && amt1.issuer === amt2.issuer && aValue.isEqualTo(bValue) ) }This approach would eliminate the need for type assertions and improve overall type safety.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (5)
- packages/xrpl/src/client/partialPayment.ts (2 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (1 hunks)
- packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenIssuanceCreate.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts
- packages/xrpl/test/integration/transactions/mptokenIssuanceCreate.test.ts
- packages/xrpl/test/models/MPTokenIssuanceCreate.test.ts
🧰 Additional context used
🔇 Additional comments (7)
packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (4)
1-12
: LGTM: Imports are appropriate and concise.The imports are well-organized and relevant to the functionality being implemented in this file.
14-28
: LGTM: MPTokenIssuanceSetFlags enum is well-defined.The enum clearly defines the flags for locking and unlocking MPTs, with appropriate documentation.
30-39
: LGTM: MPTokenIssuanceSetFlagsInterface is well-structured.The interface correctly extends GlobalFlags and defines the specific flags for MPTokenIssuanceSet as optional boolean properties.
41-57
: LGTM: MPTokenIssuanceSet interface is comprehensive and well-documented.The interface correctly extends BaseTransaction and includes all necessary fields for an MPTokenIssuanceSet transaction. The flexibility in the Flags field is a good design choice.
packages/xrpl/src/client/partialPayment.ts (3)
9-15
: LGTM: Import statements updated correctly.The new imports for
IssuedCurrency
,MPTAmount
,DEFAULT_API_VERSION
, andisMPTAmount
are correctly added and necessary for the changes in theamountsEqual
function.Also applies to: 22-22
67-68
: LGTM: ESLint rules correctly re-enabled.The ESLint enable comments are correctly placed to re-enable the previously disabled rules after the complex comparison logic.
Line range hint
1-214
: Overall assessment: Changes are well-implemented with room for minor improvements.The updates to the
amountsEqual
function to support MPT (Multi-Party Token) amounts are well-implemented and necessary. The changes include proper type handling, precise numerical comparisons using BigNumber, and logical structuring of the comparison cases.Key points:
- Import statements are correctly updated to include necessary types and functions.
- The function signature is appropriately modified to accept MPT amounts.
- Comparison logic for different amount types (XRP, MPT, Issued Currency) is correctly implemented.
Suggestions for improvement:
- Consider adding a TODO for future refactoring to reduce complexity.
- Optimize the MPT comparison logic to reduce redundant type checking.
- Improve type safety in the issued currency comparison by using type guards instead of type assertions.
These changes significantly enhance the capability of the
amountsEqual
function to handle various amount types, which is crucial for correct partial payment processing in XRPL transactions.
/** | ||
* Verify the form and type of an MPTokenIssuanceSet at runtime. | ||
* | ||
* @param tx - An MPTokenIssuanceSet Transaction. | ||
* @throws When the MPTokenIssuanceSet is Malformed. | ||
*/ | ||
export function validateMPTokenIssuanceSet(tx: Record<string, unknown>): void { | ||
validateBaseTransaction(tx) | ||
validateRequiredField(tx, 'MPTokenIssuanceID', isString) | ||
validateOptionalField(tx, 'MPTokenHolder', isAccount) | ||
|
||
/* eslint-disable no-bitwise -- We need bitwise operations for flag checks here */ | ||
if (typeof tx.Flags === 'number') { | ||
const flags = tx.Flags | ||
if ( | ||
BigInt(flags) & BigInt(MPTokenIssuanceSetFlags.tfMPTLock) && | ||
BigInt(flags) & BigInt(MPTokenIssuanceSetFlags.tfMPTUnlock) | ||
) { | ||
throw new ValidationError('MPTokenIssuanceSet: flag conflict') | ||
} | ||
} else { | ||
throw new Error('tx.Flags is not a number') | ||
} | ||
/* eslint-enable no-bitwise -- Re-enable bitwise rule after this block */ | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Improve flag validation in validateMPTokenIssuanceSet function.
While the function correctly validates the basic structure of the transaction, there are some issues with flag handling:
- The function only handles number-type flags, ignoring the possibility of MPTokenIssuanceSetFlagsInterface type flags.
- The error message for non-number flags is not specific to MPTokenIssuanceSet.
Consider implementing the following improvements:
- Handle both number and MPTokenIssuanceSetFlagsInterface type flags.
- Provide a more specific error message for invalid flag types.
Here's a suggested implementation:
export function validateMPTokenIssuanceSet(tx: Record<string, unknown>): void {
validateBaseTransaction(tx)
validateRequiredField(tx, 'MPTokenIssuanceID', isString)
validateOptionalField(tx, 'MPTokenHolder', isAccount)
let flags: number
if (typeof tx.Flags === 'number') {
flags = tx.Flags
} else if (typeof tx.Flags === 'object' && tx.Flags !== null) {
flags = 0
const flagInterface = tx.Flags as MPTokenIssuanceSetFlagsInterface
if (flagInterface.tfMPTLock) {
flags |= MPTokenIssuanceSetFlags.tfMPTLock
}
if (flagInterface.tfMPTUnlock) {
flags |= MPTokenIssuanceSetFlags.tfMPTUnlock
}
} else if (tx.Flags !== undefined) {
throw new ValidationError('MPTokenIssuanceSet: Invalid Flags type')
}
if (flags !== undefined) {
if (
(flags & MPTokenIssuanceSetFlags.tfMPTLock) !== 0 &&
(flags & MPTokenIssuanceSetFlags.tfMPTUnlock) !== 0
) {
throw new ValidationError('MPTokenIssuanceSet: flag conflict')
}
}
}
This implementation handles both number and object flags, provides a specific error for invalid flag types, and uses bitwise operations without the need for BigInt conversions.
* rename * update definition.json
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 15
🧹 Outside diff range and nitpick comments (14)
packages/xrpl/src/models/ledger/MPToken.ts (1)
5-11
: Add JSDoc documentation and consider type improvements.The interface structure looks correct, but could benefit from the following improvements:
Add JSDoc documentation explaining:
- The purpose of the MPToken interface
- The meaning and format of MPTokenIssuanceID
- The valid values for Flags
- When OwnerNode is required/optional
Consider using a more specific type for Flags instead of number
Here's a suggested improvement:
+/** + * Represents a Multi-Party Token (MPT) ledger entry in the XRP Ledger. + * @see https://xrpl.org/mpt.html + */ export interface MPToken extends BaseLedgerEntry, HasPreviousTxnID { LedgerEntryType: 'MPToken' + /** Unique identifier for the MPT issuance */ MPTokenIssuanceID: string + /** The amount and token information for this MPT */ MPTAmount?: MPTAmount - Flags: number + /** Bit-map of boolean flags. See MPTokenFlags for possible values */ + Flags: MPTokenFlags + /** Unique identifier for tracking ownership */ OwnerNode?: string } +/** + * Flags that can be set on an MPToken ledger entry + */ +export enum MPTokenFlags { + // Add specific flag values here +}packages/xrpl/src/models/ledger/MPTokenIssuance.ts (2)
11-11
: Document MPTokenMetadata format requirementsThe
MPTokenMetadata
property should include documentation specifying the expected format and any size limitations.Add JSDoc comment to clarify the requirements:
- MPTokenMetadata?: string + /** + * URI or hex-encoded data for token metadata + * Must be either: + * 1. A valid URI (max 256 bytes) + * 2. Hex-encoded data (max 256 bytes) + */ + MPTokenMetadata?: string
5-5
: Document Flags field valuesThe
Flags
property should include documentation of valid flag values and their meanings for MPTokenIssuance.Add JSDoc comment to document the flags:
- Flags: number + /** + * Bit-map of boolean flags for MPTokenIssuance + * @remarks + * - 0x00000001: lsfBurnable + * - 0x00000002: lsfTransferable + * (Add other relevant flags) + */ + Flags: numberpackages/xrpl/test/models/MPTokenAuthorize.test.ts (1)
7-11
: Enhance documentation with more details about MPTokenAuthorize.Consider expanding the documentation to include:
- Purpose and use cases of MPTokenAuthorize transactions
- Description of required and optional fields
- Explanation of available flags and their effects
Example enhancement:
/** * MPTokenAuthorize Transaction Verification Testing. * * Tests validation logic for MPTokenAuthorize transactions, which are used to: * - Authorize/unauthorize token transfers * - Manage token holder permissions * * Required fields: * - TransactionType: Must be 'MPTokenAuthorize' * - Account: Address initiating the authorization * - MPTokenIssuanceID: Unique identifier of the token * * Optional fields: * - Holder: Address being authorized/unauthorized * - Flags: Transaction flags (e.g., tfMPTUnauthorize) */packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (2)
19-19
: Consider removingas any
type assertions.Type assertions using
as any
can mask potential type-related issues. Consider creating proper type interfaces for the test objects or using partial types.- } as any + } as Partial<MPTokenIssuanceSet>Also applies to: 28-28, 38-38
56-72
: Consider testing additional flag combinations.While the current test verifies the basic conflict between lock and unlock flags, consider adding tests for:
- All possible valid flag combinations
- Edge cases with invalid flag values
- Multiple flags set simultaneously
Would you like me to provide examples of additional flag combination test cases?
packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (1)
40-45
: Add assertions for MPTokenIssuanceCreate responseThe test should verify the success status and other relevant fields of the MPTokenIssuanceCreate transaction response.
const mptCreateRes = await testTransaction( testContext.client, createTx, testContext.wallet, ) + assert.equal(mptCreateRes.result.engine_result, 'tesSUCCESS', 'MPTokenIssuanceCreate should succeed') + assert.exists(mptCreateRes.result.tx_json.hash, 'Transaction should have a hash')packages/xrpl/test/models/clawback.test.ts (3)
82-94
: LGTM! Consider adding edge case tests.The test case effectively validates the happy path for MPT Clawback transactions. The test data is well-structured and includes the essential fields: mpt_issuance_id, value, Account, and Holder.
Consider adding tests for edge cases such as:
- Maximum/minimum values for the 'value' field
- Various formats of mpt_issuance_id
114-129
: LGTM! Consider renaming the test for clarity.The test correctly validates that the Holder field is required for MPT transactions. However, the test name "throws w/ invalid Holder" could be more specific.
Consider renaming the test to "throws w/ missing Holder field" to better reflect the actual test scenario.
81-148
: Consider adding a test suite description for MPT-specific tests.The new test cases effectively cover MPT-related scenarios, but the test organization could be improved.
Consider:
- Adding a nested
describe
block for MPT-specific tests to better organize and document these scenarios- Adding JSDoc comments to explain the business rules being tested, especially the restrictions around Holder field usage
packages/xrpl/test/integration/transactions/clawback.test.ts (2)
159-160
: Document the significance of the maximum value.The value '9223372036854775807' appears to be the maximum value for a 64-bit signed integer (Int64). Consider adding a constant with a descriptive name and a comment explaining why this specific value is used in the test.
+// Maximum value for Int64, used to test edge cases in MPToken amounts +const MAX_MPT_AMOUNT = '9223372036854775807' const paymentTx: Payment = { TransactionType: 'Payment', Account: testContext.wallet.classicAddress, - Amount: { mpt_issuance_id: mptID!, value: '9223372036854775807' }, + Amount: { mpt_issuance_id: mptID!, value: MAX_MPT_AMOUNT }, Destination: wallet2.classicAddress, }
121-207
: Consider adding negative test cases.The test suite would benefit from additional test cases that verify error conditions:
- Attempting clawback without proper authorization
- Attempting clawback with invalid amounts
- Attempting clawback from non-issuer accounts
Would you like me to help generate these additional test cases?
packages/xrpl/src/models/transactions/clawback.ts (2)
25-26
: Clarify the documentation for theAmount
fieldThe current wording can be refined for better clarity. Consider rephrasing to improve readability.
Proposed change:
/** - * The amount of currency or MPT to clawback, and it must be non-XRP. The nested field - * names MUST be lower-case. If the amount is IOU, the `issuer` field MUST be the holder's address, - * whom to be clawed back. + * The amount of currency or MPT to claw back; it must be non-XRP. The nested field + * names MUST be lower-case. If the amount is an IOU, the `issuer` field MUST be the holder's address + * from whom the tokens are to be clawed back. */
31-33
: Enhance the description of theHolder
fieldFor improved understanding, consider rewording the documentation to clearly specify the role of the
Holder
field.Proposed change:
/** - * Indicates the AccountID that the issuer wants to clawback. This field is only valid for clawing back - * MPTs. + * The AccountID of the holder whose MPT tokens are being clawed back. This field is only valid for + * clawing back MPTs. */
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (10)
- packages/xrpl/src/models/ledger/MPToken.ts (1 hunks)
- packages/xrpl/src/models/ledger/MPTokenIssuance.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenAuthorize.ts (1 hunks)
- packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (1 hunks)
- packages/xrpl/src/models/transactions/clawback.ts (3 hunks)
- packages/xrpl/test/integration/transactions/clawback.test.ts (2 hunks)
- packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenAuthorize.test.ts (1 hunks)
- packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (1 hunks)
- packages/xrpl/test/models/clawback.test.ts (1 hunks)
🧰 Additional context used
🪛 Gitleaks
packages/xrpl/test/models/MPTokenAuthorize.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
packages/xrpl/test/models/MPTokenIssuanceSet.test.ts
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🔇 Additional comments (21)
packages/xrpl/src/models/ledger/MPToken.ts (2)
1-3
: LGTM! Import statements are well-structured.The imports are correctly organized and include all necessary types for the MPToken interface.
5-11
: Verify required fields for XRPL ledger entries.Let's verify that all required fields for XRPL ledger entries are included through the inheritance chain.
✅ Verification successful
Based on the shell script results, I can now generate the final response:
Required fields for MPToken ledger entry are properly defined
The MPToken ledger entry inherits from BaseLedgerEntry which provides the required
index
field. The MPToken interface itself correctly defines the required fields:
LedgerEntryType: 'MPToken'
- Required to identify entry typeMPTokenIssuanceID: string
- Required to link to parent issuanceFlags: number
- Required for token state flagsThe optional fields are also properly marked with
?
:
MPTAmount?: MPTAmount
OwnerNode?: string
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for BaseLedgerEntry definition to verify required fields ast-grep --pattern 'interface BaseLedgerEntry { $$$ }' # Search for any other MPToken-related interfaces or types rg -g '*.ts' -A 5 'MPToken'Length of output: 77337
packages/xrpl/src/models/ledger/MPTokenIssuance.ts (1)
8-9
: ** Use BigNumber for amount fields**As noted in the previous review, the
MaximumAmount
andOutstandingAmount
properties should useBigNumber.Value
instead of string for consistency and precision.packages/xrpl/test/models/MPTokenIssuanceSet.test.ts (2)
1-6
: LGTM! Imports and test constants are well-structured.The imports are appropriate for the test context, and the test constant is properly defined.
🧰 Tools
🪛 Gitleaks
5-5: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
13-41
: Expand test coverage for edge cases.The previous review comment about adding more test cases for comprehensive coverage is still valid. Consider implementing the suggested test cases for better coverage.
packages/xrpl/test/integration/transactions/mptokenAuthorize.test.ts (4)
24-27
: LGTM!The test setup and teardown are well-structured and follow best practices.
58-62
: Specify 'mpt_issuance' type consistentlyFor consistency with other queries and to ensure correct object type filtering:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: testContext.wallet.classicAddress, - type: 'mpt_issuance', + type: 'mptoken', })
106-109
: Add type filter to account_objects queryFor consistency and to ensure we're specifically checking for MPToken objects:
accountObjectsResponse = await testContext.client.request({ command: 'account_objects', account: wallet2.classicAddress, + type: 'mptoken', })
1-119
: Verify consistency with other transaction test patternsLet's verify if the test structure aligns with other transaction test files in the codebase.
✅ Verification successful
Based on the output, I can now generate the final response since I have enough information to verify the test patterns. The search results show that the test structure in
mptokenAuthorize.test.ts
follows the consistent pattern used across all transaction test files in the codebase, including:Test structure aligns with transaction test patterns
- Uses standard
describe
/beforeEach
/afterEach
setup withtestContext
- Follows the same timeout pattern with
TIMEOUT
constant- Implements proper transaction testing flow with
testTransaction
helper- Validates results using
account_objects
checks- Maintains consistent assertion patterns using
assert.lengthOf
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for similar test patterns in other transaction test files echo "Searching for similar test patterns..." rg -l "TransactionType.*MPToken" "packages/xrpl/test/integration/transactions" echo "Checking test structure in other transaction files..." ast-grep --pattern 'describe($_, function () { $$$ beforeEach(async () => { $$$ }) afterEach(async () => $$$) $$$ })' "packages/xrpl/test/integration/transactions"Length of output: 222441
packages/xrpl/test/models/clawback.test.ts (2)
96-112
: LGTM! Good validation of account separation rule.The test effectively verifies that the Account and Holder fields cannot be the same, which is an important business rule for MPT clawback operations.
131-148
: LGTM! Verify this restriction in the documentation.The test correctly validates that the Holder field cannot be used with currency-based transactions. This appears to be an important business rule.
Let's verify this restriction is documented:
✅ Verification successful
The restriction is correctly implemented and documented in code
The validation rule is properly implemented in the
validateClawback
function in the codebase:if (isIssuedCurrency(tx.Amount) && tx.Holder) { throw new ValidationError('Clawback: cannot have Holder for currency') }The code also includes clear documentation in the interface:
/** * Indicates the AccountID that the issuer wants to clawback. This field is only valid for clawing back * MPTs. */ Holder?: stringThe test case correctly verifies this important business rule, and the implementation matches the documented behavior that the Holder field is only valid for MPT (Managed Payment Token) clawbacks, not for currency clawbacks.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for documentation about Holder field restrictions rg -i "holder.*currency|currency.*holder" --type mdLength of output: 53
Script:
#!/bin/bash # Let's first check the documentation files for any mentions of Clawback and Holder rg -i "clawback.*holder|holder.*clawback" --type md # Also search for Clawback validation rules or restrictions ast-grep --pattern 'validate($account: $_) { $$$ }' # Let's also check for any comments or documentation in the validation code rg -l "clawback" --type ts | xargs catLength of output: 27852
packages/xrpl/test/integration/transactions/clawback.test.ts (1)
9-13
: LGTM: New imports are properly organized and necessary.The added imports are well-organized and essential for implementing the MPToken test case.
packages/xrpl/src/models/transactions/MPTokenAuthorize.ts (5)
1-10
: Imports are correctly organized and comprehensiveAll necessary modules and types are imported from
'./common'
, ensuring that the code has access to all required functionalities and type validations.
12-27
: Well-documentedMPTokenAuthorizeFlags
enumThe
MPTokenAuthorizeFlags
enum is properly declared with clear and detailed documentation. This enhances code readability and helps developers understand the purpose and usage of each flag.
29-37
: Correct extension ofGlobalFlags
inMPTokenAuthorizeFlagsInterface
The
MPTokenAuthorizeFlagsInterface
appropriately extendsGlobalFlags
and includes the optionaltfMPTUnauthorize
boolean flag. This design promotes consistency and reusability across different transaction flag interfaces.
39-55
: Accurate and comprehensiveMPTokenAuthorize
interface definitionThe
MPTokenAuthorize
interface correctly extendsBaseTransaction
and includes all necessary fields with appropriate types and documentation. The optionalHolder
field allows flexibility in specifying individual token holders, and theFlags
field is properly typed to accept either a number or the flags interface.
57-67
: Effective validation invalidateMPTokenAuthorize
functionThe
validateMPTokenAuthorize
function ensures that required fields are present and correctly typed, and that optional fields are validated when provided. This promotes data integrity and helps prevent malformed transactions from being processed.packages/xrpl/src/models/transactions/MPTokenIssuanceSet.ts (4)
1-13
: Imports are correctly includedThe necessary modules and utilities are properly imported.
14-28
: Well-defined 'MPTokenIssuanceSetFlags' enumThe transaction flags are appropriately defined with clear documentation.
30-39
: Accurate 'MPTokenIssuanceSetFlagsInterface' structureThe flags interface extends
GlobalFlags
and includes optional boolean flag properties.
41-57
: Proper definition of 'MPTokenIssuanceSet' interfaceAll required and optional fields are correctly specified, and the
Flags
field correctly accepts either a number or a flags interface.
AssetScale?: number | ||
MaximumAmount?: string | ||
OutstandingAmount: string | ||
TransferFee?: number |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add validation for TransferFee range
The TransferFee
property should have validation to ensure it's within acceptable bounds (typically 0-50000 for 0% to 50% in XRPL).
Consider adding a type constraint or documentation to specify the valid range:
- TransferFee?: number
+ /** Transfer fee in basis points (0-50000, representing 0% to 50%) */
+ TransferFee?: number & { _brand: 'TransferFeeInBasisPoints' }
Committable suggestion was skipped due to low confidence.
LedgerEntryType: 'MPTokenIssuance' | ||
Flags: number | ||
Issuer: string | ||
AssetScale?: number |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Add validation for AssetScale to prevent unreasonable decimal places
Based on the codebase analysis, while AssetScale
represents decimal places and defaults to 0 if not supplied, there's currently no validation to prevent unreasonable values. Since this affects monetary calculations, I recommend:
- Add validation in
MPTokenIssuanceCreate.ts
to ensureAssetScale
is:- Non-negative (>= 0)
- Within a reasonable upper bound (e.g., <= 18, which is common in financial systems)
🔗 Analysis chain
Validate AssetScale range
The AssetScale
property should have validation to ensure it's within a reasonable range for decimal places.
Let's check how AssetScale is used in other parts of the codebase:
Let me search for any validation logic or constraints related to AssetScale in the codebase:
Let me check if there are any type definitions or interfaces that might define constraints for AssetScale:
Let me check the documentation or comments related to AssetScale:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for AssetScale usage and validation patterns
rg -A 5 "AssetScale" packages/xrpl/src
Length of output: 1189
Script:
#!/bin/bash
# Search for validation patterns or constraints related to AssetScale
ast-grep --pattern 'if ($_ > $_ || $_ < $_) { $$$ }' packages/xrpl/src/models/transactions/MPTokenIssuanceCreate.ts
rg -B2 -A2 "validate.*AssetScale|AssetScale.*validate" packages/xrpl/src
Length of output: 971
Script:
#!/bin/bash
# Search for type definitions and interfaces related to AssetScale
ast-grep --pattern 'interface $_ { $$$ AssetScale $$$ }'
ast-grep --pattern 'type $_ = { $$$ AssetScale $$$ }'
Length of output: 114
Script:
#!/bin/bash
# Search for documentation or comments about AssetScale
rg -B3 -A3 "AssetScale" packages/xrpl/src --type ts --multiline
Length of output: 1419
let validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
} as any |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve type safety by removing 'as any' assertions.
Instead of using type assertions, create proper types for the test cases:
import { MPTokenAuthorize } from '../../src'
const validMPTokenAuthorize: Partial<MPTokenAuthorize> = {
TransactionType: 'MPTokenAuthorize',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
MPTokenIssuanceID: TOKEN_ID,
}
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove duplicate test case.
This test case is identical to the previous one (lines 31-39) and can be removed.
it(`verifies valid MPTokenAuthorize`, function () { | ||
let validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
Holder: 'rajgkBmMxmz161r8bWYH7CQAFZP5bA9oSG', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
|
||
validMPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', | ||
MPTokenIssuanceID: TOKEN_ID, | ||
Holder: 'rajgkBmMxmz161r8bWYH7CQAFZP5bA9oSG', | ||
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize, | ||
} as any | ||
|
||
assert.doesNotThrow(() => validate(validMPTokenAuthorize)) | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Expand test coverage with additional scenarios.
The test suite would benefit from additional test cases:
it('verifies valid MPTokenAuthorize with multiple flags', function () {
const validMPTokenAuthorize = {
TransactionType: 'MPTokenAuthorize',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
MPTokenIssuanceID: TOKEN_ID,
Flags: MPTokenAuthorizeFlags.tfMPTUnauthorize | MPTokenAuthorizeFlags.tfMPTDisallowIncomingTransfer,
}
assert.doesNotThrow(() => validate(validMPTokenAuthorize))
})
it('handles edge cases gracefully', function () {
// Test with maximum length MPTokenIssuanceID
const maxLengthID = 'F'.repeat(64)
const validMaxLength = {
TransactionType: 'MPTokenAuthorize',
Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm',
MPTokenIssuanceID: maxLengthID,
}
assert.doesNotThrow(() => validate(validMaxLength))
})
const meta = txResponse.result | ||
.meta as TransactionMetadata<MPTokenIssuanceCreate> | ||
|
||
const mptID = meta.mpt_issuance_id | ||
|
||
const holderAuthTx: MPTokenAuthorize = { | ||
TransactionType: 'MPTokenAuthorize', | ||
Account: wallet2.classicAddress, | ||
MPTokenIssuanceID: mptID!, | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add proper null checking for MPT issuance ID.
The code uses the non-null assertion operator (!
) multiple times when accessing mptID
. Consider adding explicit null checks to handle potential errors gracefully.
const meta = txResponse.result
.meta as TransactionMetadata<MPTokenIssuanceCreate>
const mptID = meta.mpt_issuance_id
+if (!mptID) {
+ throw new Error('Failed to obtain MPT issuance ID from transaction metadata')
+}
const holderAuthTx: MPTokenAuthorize = {
TransactionType: 'MPTokenAuthorize',
Account: wallet2.classicAddress,
- MPTokenIssuanceID: mptID!,
+ MPTokenIssuanceID: mptID,
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const meta = txResponse.result | |
.meta as TransactionMetadata<MPTokenIssuanceCreate> | |
const mptID = meta.mpt_issuance_id | |
const holderAuthTx: MPTokenAuthorize = { | |
TransactionType: 'MPTokenAuthorize', | |
Account: wallet2.classicAddress, | |
MPTokenIssuanceID: mptID!, | |
} | |
const meta = txResponse.result | |
.meta as TransactionMetadata<MPTokenIssuanceCreate> | |
const mptID = meta.mpt_issuance_id | |
if (!mptID) { | |
throw new Error('Failed to obtain MPT issuance ID from transaction metadata') | |
} | |
const holderAuthTx: MPTokenAuthorize = { | |
TransactionType: 'MPTokenAuthorize', | |
Account: wallet2.classicAddress, | |
MPTokenIssuanceID: mptID, | |
} |
ledgerEntryResponse = await testContext.client.request({ | ||
command: 'ledger_entry', | ||
mptoken: { | ||
mpt_issuance_id: mptID!, | ||
account: wallet2.classicAddress, | ||
}, | ||
}) | ||
|
||
assert.equal( | ||
// @ts-expect-error: Known issue with unknown object type | ||
ledgerEntryResponse.result.node.MPTAmount, | ||
'9223372036854775307', | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance final verification with calculated expected value.
The final verification uses a hardcoded value. Consider calculating the expected value to make the test more maintainable and clear.
+const clawbackAmount = '500'
+const expectedFinalAmount = (BigInt(MAX_MPT_AMOUNT) - BigInt(clawbackAmount)).toString()
+
ledgerEntryResponse = await testContext.client.request({
command: 'ledger_entry',
mptoken: {
mpt_issuance_id: mptID!,
account: wallet2.classicAddress,
},
})
+const node = ledgerEntryResponse.result.node as MPTokenLedgerEntry
assert.equal(
- // @ts-expect-error: Known issue with unknown object type
- ledgerEntryResponse.result.node.MPTAmount,
- '9223372036854775307',
+ node.MPTAmount,
+ expectedFinalAmount,
+ `Final MPToken amount should be initial amount minus clawback amount`
)
Committable suggestion was skipped due to low confidence.
if (isMPTAmount(tx.Amount) && tx.Account === tx.Holder) { | ||
throw new ValidationError('Clawback: invalid holder Account') | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Differentiate error messages for clearer validation feedback
The error message 'Clawback: invalid holder Account'
is used in multiple validation checks. To aid in troubleshooting, consider making the error messages more specific.
Proposed change:
if (isMPTAmount(tx.Amount) && tx.Account === tx.Holder) {
- throw new ValidationError('Clawback: invalid holder Account')
+ throw new ValidationError('Clawback: Account cannot be the same as Holder for MPT')
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (isMPTAmount(tx.Amount) && tx.Account === tx.Holder) { | |
throw new ValidationError('Clawback: invalid holder Account') | |
} | |
if (isMPTAmount(tx.Amount) && tx.Account === tx.Holder) { | |
throw new ValidationError('Clawback: Account cannot be the same as Holder for MPT') | |
} |
if (isMPTAmount(tx.Amount) && !tx.Holder) { | ||
throw new ValidationError('Clawback: missing Holder') | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Differentiate error messages for clearer validation feedback
Adjust the error message to specify the missing Holder
field in the context of MPTs.
Proposed change:
if (isMPTAmount(tx.Amount) && !tx.Holder) {
- throw new ValidationError('Clawback: missing Holder')
+ throw new ValidationError('Clawback: missing Holder for MPT')
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (isMPTAmount(tx.Amount) && !tx.Holder) { | |
throw new ValidationError('Clawback: missing Holder') | |
} | |
if (isMPTAmount(tx.Amount) && !tx.Holder) { | |
throw new ValidationError('Clawback: missing Holder for MPT') | |
} |
if (isIssuedCurrency(tx.Amount) && tx.Holder) { | ||
throw new ValidationError('Clawback: cannot have Holder for currency') | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Differentiate error messages for clearer validation feedback
Similarly, update the error message for the Issued Currency validation to be more specific.
Proposed change:
if (isIssuedCurrency(tx.Amount) && tx.Holder) {
- throw new ValidationError('Clawback: cannot have Holder for currency')
+ throw new ValidationError('Clawback: Holder field is not applicable for Issued Currency')
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (isIssuedCurrency(tx.Amount) && tx.Holder) { | |
throw new ValidationError('Clawback: cannot have Holder for currency') | |
} | |
if (isIssuedCurrency(tx.Amount) && tx.Holder) { | |
throw new ValidationError('Clawback: Holder field is not applicable for Issued Currency') | |
} |
High Level Overview of Change
Context of Change
Type of Change
Did you update HISTORY.md?
Test Plan