BorrouPartner APISandboxDraft

Draft documentation for partners integrating against the sandbox. It can change before /v1 is published; the contract, openapi.yaml, is the reference.

Overview / Guides / Build

Integration guide for coding agents

v0.2 draftThe rules an integration must keep, idempotency, retries, webhooks, the lifecycle, common mistakes and a checklist. Written for engineers and coding agents alike.

You are a coding agent integrating a partner's backend with Borrou. Read this before you write code. It states the rules that are not obvious from the contract alone, the mistakes that break an integration, and a checklist to run before you call the integration done. The other documents: Sandbox quick-start (a runnable walk-through), Channel flow, call by call (the channel flow end to end: your KYC evidence, payouts to your settlement account, click-wrap, webhooks and the feed, repayment), Error codes (every error code), The sandbox (the simulators), Versioning (what may change), snippets/ (TypeScript, Python, Java) and bruno/ (the quick-start collection).

1. What the integration is

Borrou lends USDT against BTC collateral to the partner's users. The partner originates and informs: it applies for its users, starts their KYC, creates the loan once TFG has approved the borrower, issues the contract, shows the borrower what Borrou gives it (a signing link, a deposit address, an acceptance text), and follows the loan by webhook and by reading. TFG approves and moves: every payout and every return of collateral is approved by two different people at TFG, then instructed to the custodian, which executes it. The API never does either.

Where the money goes is fixed by TFG for your partner, never by a request:

  • Your settlement account at the custodian, if TFG has registered one for you (two TFG people, as for any change to your configuration). Every payout and every return of collateral of your loans goes there, and you credit the borrower in your app.
  • Otherwise, the borrower's own wallet at the custodian, which Borrou asks the custodian to open when TFG approves the borrower.

A loan shows which by kind only, on its payout (GET .../disbursement) and its release (GET .../release): destination.kind is PARTNER_SETTLEMENT_ACCOUNT or BORROWER_CUSTODIAN_WALLET. Neither the account's nor the wallet's reference is ever returned.

2. Rules you must not break

  1. Never send an address or a destination. Payouts and collateral returns go only where TFG has set for your partner (section 1): your settlement account at the custodian, or the borrower's own wallet there. A body with any field whose name contains address, or a destination field, at any depth, is refused with 422 destination_not_accepted. Do not add such a field "for later", and never build a UI field for a payout address.
  2. Never try to set the collateral or the principal of a loan. The principal is the application's; the collateral is quoted by Borrou from the product at the checked price, to the satoshi.
  3. Never treat a step as done because you asked for it. A loan is active when Borrou says ACTIVE (loan.activated); a payout is paid when it reads EXECUTED with its tx_hash (loan.disbursed). Requests you make (an increase, a surplus return, a cancellation after a deposit) start something TFG decides.
  4. Borrower personal fields are write-only. The borrower.full_name, borrower.email and borrower.country you send in POST /v1/applications are never returned and never appear in events. Keep your own record of your users; never expect Borrou to give it back. Never put personal data in external_reference, borrower.reference (which is returned, on the borrower's references), partner_session_ref, webhook URLs or anything else that is not a personal field: they are stored and shown as they are.
  5. Never log or commit secrets. The client_secret, access tokens, webhook signing secrets and one-time codes stay in memory or your secret manager. Never write them to logs, error reports, test fixtures or source control.
  6. Money is a decimal string. USDT has up to 6 decimals, BTC 8, USD 2. Parse it into a decimal type, never a binary float. Rates and ladder levels are integer basis points (13500 = 135%). Coverage thresholds are collateralisation, compared exactly; the LTV beside each is for display.
  7. Branch on error.code, never on message.
  8. Verify every webhook before you act on it (section 8).

3. Base URL and environments

Base URLCredentialsData
Sandboxhttps://api.borrou.capitalclient_id starting bpc_test_Synthetic only; simulated custodian and providers
LiveAnnounced by TFGclient_id starting bpc_live_Real

A sandbox credential is refused on live and a live one on the sandbox (invalid_client). Make the base URL and the credential configuration, never constants, and never let a sandbox credential and a live base URL meet. Every path is under /v1.

4. Authentication

OAuth 2.0 client credentials. POST /v1/oauth/token with HTTP Basic (the client_id and client_secret, each form-encoded, then base64), body grant_type=client_credentials, as application/x-www-form-urlencoded. The answer has access_token, expires_in (600 seconds by default; Borrou may set it anywhere from 60 to 3,600 seconds) and scope. Send Authorization: Bearer <access_token> on every other request.

  • Cache the token and renew it a minute before it expires. Renew it once per process at a time (a single in-flight renewal), not once per request: tokens issued per credential are rate-limited.
  • On 401 invalid_token from a resource call, drop the cached token, get a new one and retry once. If the new token is refused too, stop: the credential was revoked, or the partner's access changed. Contact TFG.
  • A rotation keeps the previous secret, and the tokens obtained with it, valid for an overlap (24 hours by default). Switch to the new secret within it. A rotation without overlap, after a leak, ends both at once.
  • scope in the token request is optional; leave it out to get every scope the credential holds.
  • Access tokens are opaque, like quote tokens. Never parse, verify or store their contents, and never depend on their length, format or claims: use expires_in to know when to renew, and renew on 401 invalid_token. Borrou rotates the keys that sign them without an outage; after an emergency rotation a token can be refused before expires_in, and the same renewal covers it.

5. Scopes

ScopeOperations
quotes:readGET /v1/quote, GET /v1/products, GET /v1/products/{code}, GET /v1/prices/btc-usd
applications:readGET /v1/applications, GET /v1/applications/{id}, GET /v1/clients, GET /v1/clients/{id}
applications:writePOST /v1/applications, POST /v1/applications/{id}/cancel
loans:readGET /v1/loans, GET /v1/loans/{reference}, GET /v1/loans/{reference}/balance, GET /v1/loans/{reference}/coverage, GET /v1/loans/{reference}/interest-periods, GET /v1/loans/{reference}/schedule, GET /v1/loans/{reference}/margin-calls, GET /v1/loans/{reference}/amendments, GET /v1/loans/{reference}/liquidation, GET /v1/loans/{reference}/contract, GET /v1/loans/{reference}/disbursement
loans:writePOST /v1/loans, POST /v1/loans/{reference}/repayments, POST /v1/loans/{reference}/collateral/announcements, POST /v1/loans/{reference}/contract, POST /v1/loans/{reference}/contract/acceptance-code, POST /v1/loans/{reference}/contract/accept, POST /v1/loans/{reference}/contract/resend, POST /v1/loans/{reference}/cancel
webhooks:manageGET /v1/webhooks/subscriptions, POST /v1/webhooks/subscriptions, DELETE /v1/webhooks/subscriptions/{id}, GET /v1/webhooks/subscriptions/{id}/signing-secret, GET /v1/webhooks/health, GET /v1/webhooks/deliveries, POST /v1/webhooks/deliveries/{id}/replay
kyc:writePOST /v1/applications/{id}/kyc-handoff
collateral:readGET /v1/loans/{reference}/collateral, GET /v1/loans/{reference}/collateral/deposit-address, GET /v1/loans/{reference}/collateral/top-up-address, GET /v1/loans/{reference}/release
repayments:readGET /v1/loans/{reference}/repayment-instructions, GET /v1/loans/{reference}/repayments
statements:readGET /v1/loans/{reference}/statements, GET /v1/loans/{reference}/statements/{period}
increases:readGET /v1/loans/{reference}/upper-limit, GET /v1/loans/{reference}/increase-requests, GET /v1/loans/{reference}/increase-requests/{id}
increases:writePOST /v1/loans/{reference}/increase-requests, POST /v1/loans/{reference}/increase-requests/{id}/acceptance, POST /v1/loans/{reference}/increase-requests/{id}/cancel, POST /v1/loans/{reference}/increase-requests/{id}/resend-code
surplus:readGET /v1/loans/{reference}/surplus-return-requests, GET /v1/loans/{reference}/surplus-return-requests/{id}
surplus:writePOST /v1/loans/{reference}/surplus-return-requests, POST /v1/loans/{reference}/surplus-return-requests/{id}/cancel
events:readGET /v1/events
sandbox:simulateGET /v1/sandbox/increase-requests/{id}/code, GET /v1/sandbox/loans/{reference}/contract/acceptance-code, POST /v1/sandbox/applications/{id}/kyc, POST /v1/sandbox/loans/{reference}/sign, POST /v1/sandbox/loans/{reference}/deposit, POST /v1/sandbox/loans/{reference}/advance, POST /v1/sandbox/loans/{reference}/repayment, POST /v1/sandbox/prices

A missing scope is 403 insufficient_scope, naming the scope. Ask TFG for it; do not work around it.

6. Idempotency

Every POST and DELETE except the token request needs an Idempotency-Key header: 1 to 255 visible ASCII characters, unique per partner. Use a UUID.

  • One key per request, for all of its attempts. Generate the key when you decide to make the request, store it with the intent (in the same database row or job as the action it performs, before you send), and send the same key on every retry of that request, after a timeout, a dropped connection, a 429 or a 5xx, including after a restart of your own process.
  • A new request gets a new key. Never send a key again with a different body or path: that is 422 idempotency_key_mismatch, and nothing is written.
  • The same key with the same request returns the stored answer with Idempotent-Replayed: true. A concurrent retry with the same key waits for the first one and replays its answer.
  • Some refusals are stored under the key and replay as they are; others are not stored, so the same key works once the situation changes. Error codes says which, per code. A request whose body you change (another amount, another one-time code) is a new request with a new key.
  • Keys are kept at least 24 hours. Do not depend on a replay after that.
  • The PROVIDER KYC hand-off's link is handed over once: its replay is 409 kyc_link_not_replayable without the link. For a fresh link, send a new hand-off with a new key.

7. Retries

Retry automatically only these, with the same Idempotency-Key:

  • no answer: a timeout or a dropped connection (the write may or may not have happened, which is what the key resolves);
  • 429 rate_limited: wait Retry-After seconds;
  • 5xx: 500 internal_error saved nothing; 503 price_unavailable and 503 provider_unavailable carry Retry-After.

Back off exponentially with jitter when there is no Retry-After (up to 0.5 s, 1 s, 2 s, … capped at 30 s), stop after a few attempts (five is plenty), and when Retry-After is longer than you can wait in the request, hand the work to a scheduled job that retries later with the same key.

A 409 is not a transient error. Every 409 Borrou returns is a conflict with the state of a loan, an application or a request (application_not_approved, loan_not_cancellable, increase_in_progress, …). Retrying it unchanged gets the same answer, and a stored one replays as it was. Retry a 409 only if it carries Retry-After (none does today); otherwise read the code in Error codes and act on it: wait for the event that changes the state, or stop. 4xx other than 429 are never retried as they are. 503 repayment_address_not_configured is not transient either: send no funds and contact TFG.

8. Webhooks

Subscribe with POST /v1/webhooks/subscriptions (an https URL on the default port, 443, with no user name or password, whose host is a public DNS name resolving only to public addresses, checked again before every delivery; and the event types you want; at most ten active subscriptions). The check runs in the connection's own DNS lookup, so Borrou connects only to an address that passed it. Read the subscription's signing secret once with GET /v1/webhooks/subscriptions/{id}/signing-secret and store it in your secret manager.

Every delivery is a POST with the event as JSON and these headers: Borrou-Signature, Borrou-Event-Id, Borrou-Event-Type, Borrou-Delivery-Id, Borrou-Delivery-Attempt.

Verify before anything else:

  1. Read the raw body bytes exactly as received. Do not parse and re-serialise the JSON first: any change of a byte breaks the signature.
  2. Parse Borrou-Signature: t=<unix seconds>,v1=<hex>. Borrou signs with one secret today, but there may be more than one v1 entry (as there would be while a signing secret rotates); accept if any one matches.
  3. Reject a t more than 300 seconds from your clock, in either direction.
  4. Compute HMAC-SHA256 of <t>. followed by the raw body, keyed with the whole signing secret string (whsec_…, used as UTF-8 text, not hex-decoded), and compare it with each v1 in constant time (timingSafeEqual, hmac.compare_digest, MessageDigest.isEqual).
  5. Only then parse the JSON. De-duplicate on the event's id (the same value as Borrou-Event-Id): delivery is at least once.

snippets/*/ has a tested implementation in each language (webhooks.ts, borrou_webhooks.py, BorrouWebhooks.java).

Then answer quickly: return a 2xx within a few seconds and do the work asynchronously. Any other answer, or none, is retried after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and 24 h, then the delivery is marked FAILED. A delay on Borrou's side (last_error signing_unavailable) uses none of those attempts. Deliveries are not ordered: a retry comes after later events, and your risk events (loan.margin_call_*, loan.liquidation_*, loan.coverage_warning) are sent before anything else waiting for you, however much older. Order events by occurred_at, or by their position in the feed (section 9), and never assume an event arrives after the one before it. Each event carries identifiers, statuses and amounts only.

9. The events feed is your reconciliation source

GET /v1/events returns the same events as the webhooks, with the same ids and data, in the order Borrou published them, each with its position (scope events:read). Webhooks are for speed; the feed is the record.

  • The cursor is the position. Store the position of the last event you processed. Poll with after=<that position> (and types= if you only need some), page with next_cursor while has_more is true, then store the new last position. after=0 reads the whole feed again, in the same order.
  • Positions only grow, and an event is never published behind a position you have already read, so polling from your last position misses nothing; no overlap or hold-back is needed. Positions are not consecutive: the gaps are other partners' events and the types you did not ask for. Two events of one change have neighbouring positions.
  • An event appears in the feed once Borrou has published it, usually within a minute, at the same moment its webhooks are queued. If Borrou could not publish an event, it retries, then sets it aside for TFG to replay; a replayed event appears after everything published meanwhile, with its id unchanged.
  • Process every event idempotently, keyed on its id, whether it came by webhook, by the feed or by both.
  • After an outage of your endpoint, read the feed from your last position instead of replaying deliveries one by one (replays are capped at 100 an hour).
  • An event id is not a cursor: after=<an id> is 400 invalid_request.

10. Pagination

EndpointOrderCursor parameterCursor value
GET /v1/applications, /v1/clientsNewest firststarting_afterAn id
GET /v1/loansNewest firststarting_afterA loan reference
GET /v1/eventsPublication orderafterA position (an integer)

Each page is { "data": [...], "has_more": bool, "next_cursor": ... }: next_cursor is a string (or null) for the lists and an integer position (or null) for events. Pass next_cursor back as the cursor while has_more is true; limit is 1 to 100 (20 by default, 50 for events). A list cursor that is not one of your own records, or an events cursor that is not a position, is 400 invalid_request. The other lists (increase and surplus-return requests, subscriptions, deliveries) are not paginated: they return the newest, up to limit.

11. The loan lifecycle and next_action

Before the loan, the application: SUBMITTED → (your KYC hand-off; the borrower at the KYC provider) → IN_REVIEW (TFG) → APPROVED or REJECTED; also CANCELLED (yours) and LOAN_CREATED. One email is one borrower: a returning borrower keeps their approval.

GET /v1/loans/{reference} carries next_action: { code, by }: what has to happen for the loan to move, and who does it. Only ISSUE_CONTRACT is yours. Drive your integration from it, and from the events, never from timers.

Loan statusnext_action.codebyWhat your integration does
LOAN_CREATEDISSUE_CONTRACTPARTNERPOST /v1/loans/{reference}/contract; open signing_link.url for the borrower, or, on a product whose signature_mode is CLICKWRAP_OTP, show acceptance.text.text exactly as given
CONTRACT_SENTBORROWER_SIGNS_CONTRACTBORROWERKeep the signing link in front of the borrower (contract/resend sends a reminder, capped); or, for a click-wrap contract, ask for a one-time code (contract/acceptance-code) and relay the borrower's acceptance with it (contract/accept). Wait for contract.signed
SIGNED_WALLET_READYBORROWER_SENDS_COLLATERALBORROWERVerify address_attestation, then show GET .../collateral/deposit-address (address and its verification_code, amount still missing, qr_payload)
SIGNED_WALLET_READYCUSTODIAN_CONFIRMS_DEPOSITCUSTODIANShow the deposit as confirming; wait for collateral.deposit_released
SIGNED_WALLET_READYTFG_REVIEWS_DEPOSITTFGA short or late deposit waits for TFG's go/no-go; tell the borrower to wait, or to send the rest
COLLATERAL_DEPOSITEDTFG_REQUESTS_BORROWER_WALLETTFGWait: the borrower's custodian wallet is not active yet
COLLATERAL_DEPOSITEDTFG_APPROVES_PAYOUTTFGWait: two TFG people approve the payout
COLLATERAL_DEPOSITEDTFG_SENDS_PAYOUT_INSTRUCTIONTFGWait
COLLATERAL_DEPOSITEDCUSTODIAN_EXECUTES_PAYOUTCUSTODIANWait for loan.disbursed and loan.activated
ACTIVENONENONEService the loan: balance, interest, statements, coverage events
ACTIVEBORROWER_TOPS_UP_COLLATERALBORROWERA margin call is open: show the top-up asked for and GET .../collateral/top-up-address, before the deadline
ACTIVEBORROWER_REPAYS_BY_MATURITYBORROWERA bullet loan: show what it owes (GET .../repayment-instructions) and its matures_at; principal and interest are repaid together, by then
ACTIVE, repaid_in_fullTFG_RETURNS_COLLATERAL, TFG_SENDS_RETURN_INSTRUCTION, CUSTODIAN_EXECUTES_RETURNTFG, CUSTODIANRepaid in full: the collateral goes back, to your settlement account or the borrower's custodian wallet (section 1), once two TFG people approve; wait for loan.collateral_released and loan.closed
CANCELLED, REJECTEDTFG_RETURNS_COLLATERAL, TFG_SENDS_RETURN_INSTRUCTION, CUSTODIAN_EXECUTES_RETURNTFG, CUSTODIANCollateral already deposited goes back, to your settlement account or the borrower's custodian wallet (section 1), once two TFG people approve; wait
CANCELLED, REJECTED, CLOSED, LIQUIDATEDNONENONENothing more happens

Before activation you may cancel (POST /v1/loans/{reference}/cancel, with a coded reason), until TFG has entered the payout. Above the upper limit an increase may be offered: you request it, Borrou emails the borrower a one-time code and the terms, your app shows the borrower the exact acceptance_text and relays their click with the code (.../acceptance), and two TFG people approve the payout. A surplus return is the borrower's request only, never promoted, never together with an increase. Treat next_action codes, statuses and event types you do not know as described in Versioning: log them and wait for the next change.

12. What the API never does

  • No approvals. No API call approves a payout, a return, a KYC file, a deposit go/no-go or anything else TFG decides, and none counts as one of the two approvals a movement needs.
  • No fund movements. No API call moves USDT or BTC, instructs the custodian or sells collateral. Repayments are recorded by TFG, with two approvals.
  • No payout or return addresses. The destination is your settlement account or the borrower's custodian wallet, as TFG has set for your partner (section 1); any address or destination field is destination_not_accepted.
  • No personal data out. Borrower personal fields are write-only, and responses and events carry identifiers, statuses and amounts only: no names, emails, addresses of people, approvers or custody references.
  • No identity documents in. KYC runs at Borrou's KYC provider through the hand-off link, or under your own KYC if TFG has approved you for reliance. A partner TFG has set to send its own KYC evidence (proposed, may change) sends references to what its checks established, never a document (kyc_evidence on POST /v1/applications).

13. Sandbox and live

SandboxLive
Hosthttps://api.borrou.capitalAnnounced by TFG
Credentialbpc_test_… / bps_test_…bpc_live_… / bps_live_…
Simulators (/v1/sandbox)Available with sandbox:simulate403 sandbox_only
The borrower's KYC, signature and depositSimulated on requestThe borrower, at the providers and with their own BTC
The payout's two approvalsSimulated on Borrou's sandbox: advance enters and approves the payout as the sandbox's two simulated TFG users, through the same two-person checks, then plays the custodianTwo TFG people
A repayment, and the collateral's return after itPOST /v1/sandbox/loans/{reference}/repayment plays the borrower's transfer and its entry and confirmation by the two simulated TFG users; advance then plays the return (proposed, may change)TFG (two people each)
One-time codesRead back with GET /v1/sandbox/increase-requests/{id}/code, or for a click-wrap contract GET /v1/sandbox/loans/{reference}/contract/acceptance-codeOnly in the borrower's email
Deposit, top-up and repayment addressesSynthetic: never send real assetsReal; a deposit or top-up address is served only with Borrou's signature on it (Verifying an address)
BTC priceYour own simulated feed (POST /v1/sandbox/prices)The checked market price

Everything else, the checks, the records, the events and the error codes, is the same. Never call a /v1/sandbox path from code that can run against live.

14. Common mistakes

  • Parsing the webhook body to JSON and re-serialising it before verifying the signature.
  • Comparing signatures with ==, or hex-decoding the whsec_ secret before using it as the key.
  • Generating a new Idempotency-Key on each retry (duplicates), or using one key for many requests (idempotency_key_mismatch).
  • Retrying every 409 in a loop, or retrying 422s.
  • Asking for a new access token on every request, or on several threads at once; decoding the token to read its expiry or scopes instead of using expires_in and scope.
  • Treating amount_usdt as a float, or comparing an LTV against a threshold instead of the collateralisation in basis points.
  • Expecting a live loan to become ACTIVE after the deposit without TFG's approval of the payout, or calling advance in a loop in the sandbox instead of reading the loan.
  • Showing the borrower a deposit address from anywhere but GET .../collateral/deposit-address (or the top-up address), or caching it across loans: every loan has its own.
  • Showing a collateral address before verifying its address_attestation with the key from GET /v1/address-keys (Verifying an address), or showing a null attestation as verified.
  • Sending an address "just in case", or building a UI field for a payout address.
  • Reading personal data back from Borrou (it is never returned), or putting it in references.
  • Assuming webhooks arrive in order, exactly once, or at all: reconcile from the events feed.
  • Failing on an unknown field, enumeration value, error code or event type.
  • Changing the acceptance text before showing it, or computing text_sha256 over anything but the text exactly as Borrou gave it; sending an IP address or an email as partner_session_ref.
  • Logging the Authorization header, the client secret, the signing secret or a one-time code.

15. Checklist before you call the integration done

Run each in the sandbox, and keep the evidence (a test, a log line without secrets, a request id).

  1. The base URL and the credential come from configuration and the secret from a secret manager; none is in source control, a log or a test fixture.
  2. One access token is reused until a minute before it expires; concurrent callers share one renewal; a 401 invalid_token renews once and then stops.
  3. Every POST and DELETE carries an Idempotency-Key stored with the intent before the first attempt; a retry after a forced timeout sends the same key and gets Idempotent-Replayed: true; a new request never carries an old key.
  4. Retries happen only on no answer, 429 and 5xx, honour Retry-After, back off with jitter and stop; a 409 is surfaced to the right handler, not retried.
  5. No request body anywhere contains an address or destination field; POST /v1/loans sends only application_id, collateral_sender, usdt_network and, optionally, quote_token.
  6. Money is parsed and stored as decimals; thresholds are compared as collateralisation in basis points.
  7. Errors are handled by error.code, every code in Error codes your flows can meet has a handler, an unknown code falls back on the HTTP status, and the request_id is logged.
  8. The webhook endpoint verifies the raw body with the tested function, rejects stale and unsigned deliveries, answers 2xx within a few seconds, processes asynchronously and de-duplicates on the event id. The tests in snippets/ pass against the fixture.
  9. A reconciliation job reads GET /v1/events from the last stored position and converges to the same state as the webhooks after a simulated outage of the endpoint.
  10. Lists are read page by page with next_cursor until has_more is false.
  11. The flow is driven by next_action and events: it issues the contract on ISSUE_CONTRACT, shows the signing link or the acceptance text, shows the deposit address only from its endpoint and only once its signature verifies, with its verification code beside it, waits on every TFG and CUSTODIAN step without polling a simulator, and handles cancellation and its collateral return.
  12. Unknown fields, enumeration values and event types are tolerated and logged.
  13. No personal data is sent outside the borrower's personal fields, and none is expected back.
  14. Sandbox-only code (/v1/sandbox, the code read-back) cannot run against live.
  15. The quick-start collection runs green against the sandbox with your credential, through the payout (simulated on Borrou's sandbox), servicing and the upper limit.