Transport for the Modern Treasury API: Basic auth with the
organization id and API key, the Idempotency-Key header, JSON
bodies with unset fields dropped, bracket-style query strings
(metadata[key]=value, id[]=a), header-cursor pagination
(per_page, after_cursor, X-After-Cursor), and errors parsed
into HttpError with account and routing numbers redacted.
No retries. Nothing here retries a request. Modern Treasury keeps the result of a successful POST or PATCH for 24 hours under its idempotency key, so after a transport failure it is safe to resend the same call with the same key; a different key would make a second payment.
Per-call credentials. Every function that calls the API takes an
optional trailing opts Map, resolved by resolve: opts first,
then context, then defaults. Nothing from opts is written to ctx,
and per-call credentials are masked in call records. organization-id
and api-key go together; either one present but blank or null is an
Err, never a fallback to context. Requests only go to Modern
Treasury's own host; there is no per-call URL.
Context Vars
modern-treasury.organization.idmodern-treasury.api.keymodern-treasury.environment
Values
MAX_PAGES
MAX_PAGES: Int 1000
SENSITIVE_KEYS
SENSITIVE_KEYS: Vec [
"account_number",
"routing_number",
"account_number_safe",
"iban",
"taxpayer_identifier",
"id_number",
"date_of_birth",
"individual_identification_number",
"plaid_processor_token",
"secret",
"webhook_key"
]
USER_AGENT
USER_AGENT: Str "hot-dev-modern-treasury/0.1.0"
Functions
auth-header
fn (organization-id: Str, api-key: Str): Str
Basic base64("{organization-id}:{api-key}"). Exposed for testing.
Example
::modern-treasury::api/auth-header(
::hot::ctx/get("modern-treasury.organization.id"),
::hot::ctx/get("modern-treasury.api.key")
)
blank-credential
fn (opts: Map, names: Vec): Str?
The first of names that opts has but with a blank or null value,
else null. Such a key is an Err, never a fallback to context: a tenant
whose key is missing must not run on the project's credentials. Exposed
for testing.
Example
::modern-treasury::api/blank-credential({organization-id: "org_a", api-key: ""}, ["organization-id", "api-key"]) // "api-key"
::modern-treasury::api/blank-credential({}, ["organization-id", "api-key"]) // null
build-request
fn (method: Str, url: Str, body: Any, headers: Map, authorization: Str): ::hot::http/HttpRequest
Build (without sending) the HttpRequest for a call. url is the
full URL with any query string. A non-empty Map body is compacted
and sent as JSON with Content-Type: application/json; otherwise no
body is sent. headers are merged last. Exposed for testing.
Example
req ::modern-treasury::api/build-request("post", "https://app.moderntreasury.com/api/ledgers", {name: "Main", description: null}, {}, "Basic <credentials>")
req.method // "POST"
req.body // "{\"name\":\"Main\"}"
call
fn (method: Str, path: Str): Any
fn (method: Str, path: Str, params: Map): Any
fn (method: Str, path: Str, params: Map, opts: Map): Any
Call a Modern Treasury endpoint by path (e.g. /api/ping) and return
the decoded JSON body (null for 204), or an Err. params become the
query string for GET and DELETE and the JSON body otherwise; null
values are omitted. opts takes organization-id, api-key,
environment and idempotency-key (see resolve). The call is made
exactly once.
Example
::modern-treasury::api/call("GET", "/api/ping") // => {ping: "pong"}
collect-all
fn (path: Str): Vec
fn (path: Str, params: Map): Vec
fn (path: Str, params: Map, limit: Int): Vec
fn (path: Str, params: Map, limit: Int, opts: Map): Vec
Every object from a list endpoint, following cursors: up to limit
objects (default 1000; 0 means all, stopping after MAX_PAGES
pages), fetched 100 per page. An Err on any page is returned as is.
Example
orders ::modern-treasury::api/collect-all("/api/payment_orders", {status: "needs_approval"})
collect-pages
fn (fetch: Fn, params: Map, limit: Int, acc: Vec, pages: Int): Vec
Follow after_cursor from params, concatenating items, until
limit items (0 means no limit), the last page, or MAX_PAGES pages.
fetch takes the params for one page and returns it. An Err from any
page is returned as is. Exposed for testing; collect-all uses it.
Example
fetch (params) { {items: [{id: "a"}, {id: "b"}], after_cursor: null} }
::modern-treasury::api/collect-pages(fetch, {per_page: 100}, 1, [], 0) // [{id: "a"}]
compact
fn (value: Any): Any
Drop null values recursively (nested maps and the maps inside vectors),
so unset optionals are omitted rather than sent as JSON null. false,
0 and "" are kept. Exposed for testing.
Example
::modern-treasury::api/compact({a: 1, b: null, c: [{d: null, e: false}]}) // {a: 1, c: [{e: false}]}
create
fn (path: Str, params: Map, required: Vec, opts: Map, operation: Str): Map
POST a create request after checking the required fields. The
idempotency key is optional here.
Example
party ::modern-treasury::api/create("/api/counterparties", {name: "Acme"}, ["name"], {}, "create-counterparty")
party.id
current-environment
fn (): Str
The configured modern-treasury.environment, normalized; "production"
when unset (the safe assumption: simulations stay locked) and an Err for
an invalid value.
Example
env ::modern-treasury::api/current-environment()
eq(env, "sandbox")
environment-of
fn (opts: Map): Str
The environment a call with opts would use: its environment, else
modern-treasury.environment ("production" when unset). An Err for an
invalid value.
Example
::modern-treasury::api/environment-of({environment: "Sandbox"}) // "sandbox"
error-message
fn (status: Int, body: Any): Str
The readable message line for a (redacted) error body:
modern-treasury: HTTP {status} {code} ({parameter}): {message}, or a
body excerpt when the body isn't a Modern Treasury error. Exposed for
testing.
Example
::modern-treasury::api/error-message(422, {errors: {code: "parameter_invalid", parameter: "amount", message: "Amount must be greater than 0"}})
// "modern-treasury: HTTP 422 parameter_invalid (amount): Amount must be greater than 0"
::modern-treasury::api/error-message(502, "Bad Gateway") // "modern-treasury: HTTP 502: Bad Gateway"
header
fn (headers: Any, name: Str): Str?
A header value by name, ignoring case; null when absent. Exposed for testing.
Example
::modern-treasury::api/header({X-Per-Page: "25"}, "x-per-page") // "25"
::modern-treasury::api/header({}, "x-per-page") // null
is-error-code
fn (error: Result, code: Str): Bool
True when error (an HttpError, or a Result.Err holding one) has
this Modern Treasury error code, e.g. "resource_not_found".
Example
e err({status: 404, code: "resource_not_found"})
::modern-treasury::api/is-error-code(e, "resource_not_found") // true
::modern-treasury::api/is-error-code(e, "conflict") // false
list-page
fn (path: Str, params: Map): Map
fn (path: Str, params: Map, opts: Map): Map
GET one page of a list endpoint: {items, after_cursor, per_page}.
params are the endpoint's filters plus per_page (1-100, default
25) and after_cursor (the previous page's after_cursor).
Example
page ::modern-treasury::api/list-page("/api/counterparties", {per_page: 50})
more ::modern-treasury::api/list-page("/api/counterparties", ::modern-treasury::api/next-page-params({per_page: 50}, page))
missing-fields
fn (params: Map, fields: Vec): Vec
The names in fields that are null or absent in params. Exposed for
testing.
Example
::modern-treasury::api/missing-fields({name: "Acme", email: null}, ["name", "email", "phone"]) // ["email", "phone"]
move-money
fn (path: Str, params: Map, required: Vec, opts: Map, operation: Str): Map
POST a money-movement request: check the idempotency key and the
required fields, then send it once. Any failed check is an Err and
nothing is sent. Payment orders, reversals and returns are built on it.
Example
// The call behind create-payment-order
order ::modern-treasury::api/move-money("/api/payment_orders", {
type: "ach",
direction: "credit",
amount: 10000,
originating_account_id: "0f8e3719-3dfd-4613-9bbf-c0333781b59f",
receiving_account_id: "5acec2ef-987b-4260-aa97-b719eeb0a8d5"
}, ["type", "direction", "amount", "originating_account_id"], {idempotency-key: "invoice-42-payout"}, "create-payment-order")
order.status
next-page-params
fn (params: Map, page: Any): Map?
The params for the page after page: the original filters plus
after_cursor, or null on the last page (no cursor, or no items).
Example
::modern-treasury::api/next-page-params({per_page: 2}, {items: [{id: "a"}, {id: "b"}], after_cursor: "b"})
// {per_page: 2, after_cursor: "b"}
normalize-environment
fn (environment: Str): Str
"sandbox" or "production" for a configured value (case and
whitespace ignored); an Err for anything else. Exposed for testing.
Example
::modern-treasury::api/normalize-environment(" Sandbox ") // "sandbox"
is-err(::modern-treasury::api/normalize-environment("staging")) // true
option-headers
fn (opts: Map): Map
The headers opts adds: Idempotency-Key when opts has an
idempotency-key. Exposed for testing.
Example
::modern-treasury::api/option-headers({idempotency-key: "invoice-42-payout"}) // {Idempotency-Key: "invoice-42-payout"}
::modern-treasury::api/option-headers({}) // {}
page-from-response
fn (response: ::hot::http/HttpResponse): Map
A list page from a raw response: {items, after_cursor, per_page}. List
bodies are bare JSON arrays; the next cursor is the X-After-Cursor
header (null on the last page). Exposed for testing.
Example
response ::hot::http/HttpResponse({
status: 200,
headers: {X-After-Cursor: "b", X-Per-Page: "2"},
body: [{id: "a"}, {id: "b"}]
})
::modern-treasury::api/page-from-response(response)
// {items: [{id: "a"}, {id: "b"}], after_cursor: "b", per_page: 2}
parse-int
fn (value: Any): Int?
An Int from an Int or a decimal-digit Str; null for anything else. Never errs on bad input. Exposed for testing.
Example
::modern-treasury::api/parse-int("42") // 42
::modern-treasury::api/parse-int("soon") // null
ping
fn (): Map
fn (opts: Map): Map
GET /api/ping: {ping: "pong"} when the credentials work.
Example
result ::modern-treasury::api/ping()
result.ping
// Check one tenant's credentials
::modern-treasury::api/ping({
organization-id: ::hot::ctx/get("tenant-a.modern-treasury.organization.id"),
api-key: ::hot::ctx/get("tenant-a.modern-treasury.api.key")
})
query-pairs
fn (params: Map, prefix: Str): Vec<Str>
Flatten query params the way Modern Treasury reads them (Rails
brackets): nested maps become metadata[key]=value and
balances[as_of_date]=..., vectors repeat with []
({id: ["a", "b"]} gives id[]=a&id[]=b), and null values are
dropped. Keys and values are percent-encoded. Exposed for testing.
Example
::modern-treasury::api/query-pairs({metadata: {key: "v"}, id: ["a", "b"], skip: null}, "")
// ["metadata%5Bkey%5D=v", "id%5B%5D=a", "id%5B%5D=b"]
query-string
fn (params: Map): Str
?a=1&b=2 from params (see query-pairs), or "" when nothing
remains.
Example
::modern-treasury::api/query-string({per_page: 2}) // "?per_page=2"
::modern-treasury::api/query-string({per_page: null}) // ""
redact
fn (value: Any): Any
Remove sensitive data from a decoded body: values under SENSITIVE_KEYS
become "[redacted]", and long digit runs in other strings are masked
by redact-text. Applied to every HttpError. Exposed for testing.
Example
::modern-treasury::api/redact({account_number: "123456789", note: "ref 1234567890"})
// {account_number: "[redacted]", note: "ref ****7890"}
redact-text
fn (text: Str): Str
Mask every run of 8 or more digits in text down to its last four
("acct 123456789" becomes "acct ****6789"), so an account or routing
number echoed in an error message is never kept whole. Exposed for
testing.
Example
::modern-treasury::api/redact-text("acct 123456789") // "acct ****6789"
request
fn (method: Str, path: Str, params: Map, opts: Map): ::hot::http/HttpResponse
Send one request and return the raw 2xx HttpResponse (headers
included), or an Err: HttpError for non-2xx, or the transport error.
call and list-page are built on it. The request is sent exactly
once.
Example
response ::modern-treasury::api/request("GET", "/api/counterparties", {per_page: 1}, {})
::modern-treasury::api/header(response.headers, "x-after-cursor")
require-fields
fn (params: Map, fields: Vec, operation: Str): Map
params when every name in fields is set, otherwise an Err listing
the missing names (never their values). Exposed for testing.
Example
::modern-treasury::api/require-fields({name: "Acme"}, ["name"], "create-counterparty") // {name: "Acme"}
is-err(::modern-treasury::api/require-fields({}, ["name"], "create-counterparty")) // true
require-idempotency-key
fn (opts: Map, operation: Str): Map
opts when it carries a non-empty idempotency-key, otherwise an Err.
Every money-movement function checks this before sending anything.
Example
::modern-treasury::api/require-idempotency-key({idempotency-key: "invoice-42-payout"}, "create-payment-order")
// {idempotency-key: "invoice-42-payout"}
is-err(::modern-treasury::api/require-idempotency-key({}, "create-payment-order")) // true
require-sandbox
fn (environment: Str, operation: Str): Bool
true when environment is "sandbox", otherwise an Err naming
operation. Exposed for testing.
Example
::modern-treasury::api/require-sandbox("sandbox", "create-incoming-payment-detail") // true
is-err(::modern-treasury::api/require-sandbox("production", "create-incoming-payment-detail")) // true
resolve
fn (opts: Map): Map
The settings for one call: {organization-id, api-key, authorization, environment, idempotency-key}. Each comes from opts
first, then context (modern-treasury.organization.id,
modern-treasury.api.key, modern-treasury.environment), then the
default. Never writes to context, and marks per-call credentials so
they are masked in call records.
organization-id and api-key in opts go together: one without the
other is an Err, because the pair is one Basic auth credential. Also
errs when either is in opts but blank or null (that never falls back
to context), when no credentials are available, and when the
environment is invalid.
Example
settings ::modern-treasury::api/resolve({organization-id: "org_b", api-key: "key_b"})
settings.authorization // => "Basic b3JnX2I6a2V5X2I="
response-body
fn (body: Any): Any
Normalize a 2xx body: empty text (204 No Content) becomes null. Exposed for testing.
Example
::modern-treasury::api/response-body("") // null
::modern-treasury::api/response-body({id: "a"}) // {id: "a"}
seg
fn (id: Any): Str
Percent-encode one path segment (an id), so an id from user input can't change which endpoint is called.
Example
::modern-treasury::api/seg("a/b") // "a%2Fb"
Types
HttpError
HttpError type {
status: Int,
headers: Map,
body: Any,
message: Str,
code: Str?,
detail: Str?,
parameter: Str?,
retry_after: Int?
}
A non-2xx Modern Treasury response. Modern Treasury's error body is
{errors: {code, message, parameter}}; its fields are lifted:
status: the HTTP statuscode: e.g."parameter_invalid","parameter_missing","resource_not_found","invalid_key","conflict","too_many_requests"detail: Modern Treasury'serrors.messageparameter: the offending parameter, when there is oneretry_after: seconds from a numericRetry-Afterheadermessage: one readable line, e.g."modern-treasury: HTTP 422 parameter_invalid (amount): Amount must be greater than 0"
body is the decoded error body with account and routing numbers
redacted (see redact), so an HttpError is safe to log.