Snippets

Reusable Code Patterns

← Back to Building and Integrating Custom RPC Handlers


Complete Handler Template

Use this as a starting point:

//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2024 Ripple Labs Inc.
*/
//==============================================================================

#include <xrpld/app/main/Application.h>
#include <xrpld/rpc/Context.h>
#include <xrpld/rpc/detail/RPCHelpers.h>
#include <xrpl/protocol/ErrorCodes.h>
#include <xrpl/protocol/jss.h>

namespace ripple {

Json::Value doGetAccountBalance(RPC::JsonContext& context)
{
    Json::Value result;

    // TODO: Implement your handler here

    return result;
}

} // namespace ripple

Snippet 1: Parameter Validation


Snippet 2: Ledger Lookup


Snippet 3: Read Account Object


Snippet 4: Extract Account Fields


Snippet 5: Calculate Reserves


Snippet 6: Build Response


Snippet 7: Complete Minimal Handler

Here's a complete minimal implementation:


Snippet 8: Handler Registration

Add to src/xrpld/rpc/handlers/Handlers.cpp:


Snippet 9: Test Case Template


Snippet 10: Error Handling Pattern


Snippet 11: Optional Parameter Handling


Snippet 12: Trust Line Iteration (Bonus)

For the optional enhancement:


Snippet 13: Pagination Support (Bonus)


Snippet 14: Logging for Debugging


Snippet 15: Validation Helper Function

Create a helper to reduce repetition:


How to Use These Snippets

  1. Start with the template (Snippet 0)

  2. Add validation (Snippet 1)

  3. Get the ledger (Snippet 2)

  4. Read account data (Snippets 3-4)

  5. Calculate reserves (Snippet 5)

  6. Build response (Snippet 6)

  7. Register handler (Snippet 8)

  8. Write tests (Snippet 9)

Or use the complete minimal handler (Snippet 7) and build from there!


Important Notes

⚠️ These snippets are educational examples

  • Always validate your own code

  • Add proper error handling

  • Follow Rippled's style guide

  • Write comprehensive tests

Best Practices

  • Read existing handlers for reference

  • Use helper functions from RPCHelpers.h

  • Keep code readable and maintainable

  • Document complex logic


← Back to Workshop

Last updated