Integration guide for coding agents
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
- 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 adestinationfield, at any depth, is refused with422 destination_not_accepted. Do not add such a field "for later", and never build a UI field for a payout address. - 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.
- 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 readsEXECUTEDwith itstx_hash(loan.disbursed). Requests you make (an increase, a surplus return, a cancellation after a deposit) start something TFG decides. - Borrower personal fields are write-only. The
borrower.full_name,borrower.emailandborrower.countryyou send inPOST /v1/applicationsare 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 inexternal_reference,borrower.reference(which is returned, on the borrower'sreferences),partner_session_ref, webhook URLs or anything else that is not a personal field: they are stored and shown as they are. - 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. - 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. - Branch on
error.code, never onmessage. - Verify every webhook before you act on it (section 8).
3. Base URL and environments
| Base URL | Credentials | Data | |
|---|---|---|---|
| Sandbox | https://api.borrou.capital | client_id starting bpc_test_ | Synthetic only; simulated custodian and providers |
| Live | Announced by TFG | client_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_tokenfrom 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.
scopein 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_into know when to renew, and renew on401 invalid_token. Borrou rotates the keys that sign them without an outage; after an emergency rotation a token can be refused beforeexpires_in, and the same renewal covers it.
5. Scopes
| Scope | Operations |
|---|---|
quotes:read | GET /v1/quote, GET /v1/products, GET /v1/products/{code}, GET /v1/prices/btc-usd |
applications:read | GET /v1/applications, GET /v1/applications/{id}, GET /v1/clients, GET /v1/clients/{id} |
applications:write | POST /v1/applications, POST /v1/applications/{id}/cancel |
loans:read | GET /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:write | POST /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:manage | GET /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:write | POST /v1/applications/{id}/kyc-handoff |
collateral:read | GET /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:read | GET /v1/loans/{reference}/repayment-instructions, GET /v1/loans/{reference}/repayments |
statements:read | GET /v1/loans/{reference}/statements, GET /v1/loans/{reference}/statements/{period} |
increases:read | GET /v1/loans/{reference}/upper-limit, GET /v1/loans/{reference}/increase-requests, GET /v1/loans/{reference}/increase-requests/{id} |
increases:write | POST /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:read | GET /v1/loans/{reference}/surplus-return-requests, GET /v1/loans/{reference}/surplus-return-requests/{id} |
surplus:write | POST /v1/loans/{reference}/surplus-return-requests, POST /v1/loans/{reference}/surplus-return-requests/{id}/cancel |
events:read | GET /v1/events |
sandbox:simulate | GET /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
429or a5xx, 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
PROVIDERKYC hand-off's link is handed over once: its replay is409 kyc_link_not_replayablewithout 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: waitRetry-Afterseconds;5xx:500 internal_errorsaved nothing;503 price_unavailableand503 provider_unavailablecarryRetry-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:
- 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.
- Parse
Borrou-Signature: t=<unix seconds>,v1=<hex>. Borrou signs with one secret today, but there may be more than onev1entry (as there would be while a signing secret rotates); accept if any one matches. - Reject a
tmore than 300 seconds from your clock, in either direction. - 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 eachv1in constant time (timingSafeEqual,hmac.compare_digest,MessageDigest.isEqual). - Only then parse the JSON. De-duplicate on the event's
id(the same value asBorrou-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
positionof the last event you processed. Poll withafter=<that position>(andtypes=if you only need some), page withnext_cursorwhilehas_moreis true, then store the new last position.after=0reads 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
idunchanged. - 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>is400 invalid_request.
10. Pagination
| Endpoint | Order | Cursor parameter | Cursor value |
|---|---|---|---|
GET /v1/applications, /v1/clients | Newest first | starting_after | An id |
GET /v1/loans | Newest first | starting_after | A loan reference |
GET /v1/events | Publication order | after | A 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 status | next_action.code | by | What your integration does |
|---|---|---|---|
LOAN_CREATED | ISSUE_CONTRACT | PARTNER | POST /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_SENT | BORROWER_SIGNS_CONTRACT | BORROWER | Keep 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_READY | BORROWER_SENDS_COLLATERAL | BORROWER | Verify address_attestation, then show GET .../collateral/deposit-address (address and its verification_code, amount still missing, qr_payload) |
SIGNED_WALLET_READY | CUSTODIAN_CONFIRMS_DEPOSIT | CUSTODIAN | Show the deposit as confirming; wait for collateral.deposit_released |
SIGNED_WALLET_READY | TFG_REVIEWS_DEPOSIT | TFG | A short or late deposit waits for TFG's go/no-go; tell the borrower to wait, or to send the rest |
COLLATERAL_DEPOSITED | TFG_REQUESTS_BORROWER_WALLET | TFG | Wait: the borrower's custodian wallet is not active yet |
COLLATERAL_DEPOSITED | TFG_APPROVES_PAYOUT | TFG | Wait: two TFG people approve the payout |
COLLATERAL_DEPOSITED | TFG_SENDS_PAYOUT_INSTRUCTION | TFG | Wait |
COLLATERAL_DEPOSITED | CUSTODIAN_EXECUTES_PAYOUT | CUSTODIAN | Wait for loan.disbursed and loan.activated |
ACTIVE | NONE | NONE | Service the loan: balance, interest, statements, coverage events |
ACTIVE | BORROWER_TOPS_UP_COLLATERAL | BORROWER | A margin call is open: show the top-up asked for and GET .../collateral/top-up-address, before the deadline |
ACTIVE | BORROWER_REPAYS_BY_MATURITY | BORROWER | A bullet loan: show what it owes (GET .../repayment-instructions) and its matures_at; principal and interest are repaid together, by then |
ACTIVE, repaid_in_full | TFG_RETURNS_COLLATERAL, TFG_SENDS_RETURN_INSTRUCTION, CUSTODIAN_EXECUTES_RETURN | TFG, CUSTODIAN | Repaid 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, REJECTED | TFG_RETURNS_COLLATERAL, TFG_SENDS_RETURN_INSTRUCTION, CUSTODIAN_EXECUTES_RETURN | TFG, CUSTODIAN | Collateral 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, LIQUIDATED | NONE | NONE | Nothing 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_evidenceonPOST /v1/applications).
13. Sandbox and live
| Sandbox | Live | |
|---|---|---|
| Host | https://api.borrou.capital | Announced by TFG |
| Credential | bpc_test_… / bps_test_… | bpc_live_… / bps_live_… |
Simulators (/v1/sandbox) | Available with sandbox:simulate | 403 sandbox_only |
| The borrower's KYC, signature and deposit | Simulated on request | The borrower, at the providers and with their own BTC |
| The payout's two approvals | Simulated 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 custodian | Two TFG people |
| A repayment, and the collateral's return after it | POST /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 codes | Read back with GET /v1/sandbox/increase-requests/{id}/code, or for a click-wrap contract GET /v1/sandbox/loans/{reference}/contract/acceptance-code | Only in the borrower's email |
| Deposit, top-up and repayment addresses | Synthetic: never send real assets | Real; a deposit or top-up address is served only with Borrou's signature on it (Verifying an address) |
| BTC price | Your 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 thewhsec_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
409in a loop, or retrying422s. - 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_inandscope. - Treating
amount_usdtas a float, or comparing an LTV against a threshold instead of the collateralisation in basis points. - Expecting a live loan to become
ACTIVEafter the deposit without TFG's approval of the payout, or callingadvancein 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_attestationwith the key fromGET /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_sha256over anything but the text exactly as Borrou gave it; sending an IP address or an email aspartner_session_ref. - Logging the
Authorizationheader, 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).
- 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.
- One access token is reused until a minute before it expires; concurrent callers share one renewal; a
401 invalid_tokenrenews once and then stops. - Every
POSTandDELETEcarries an Idempotency-Key stored with the intent before the first attempt; a retry after a forced timeout sends the same key and getsIdempotent-Replayed: true; a new request never carries an old key. - Retries happen only on no answer,
429and5xx, honourRetry-After, back off with jitter and stop; a409is surfaced to the right handler, not retried. - No request body anywhere contains an address or destination field;
POST /v1/loanssends onlyapplication_id,collateral_sender,usdt_networkand, optionally,quote_token. - Money is parsed and stored as decimals; thresholds are compared as collateralisation in basis points.
- 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 therequest_idis logged. - The webhook endpoint verifies the raw body with the tested function, rejects stale and unsigned deliveries, answers
2xxwithin a few seconds, processes asynchronously and de-duplicates on the eventid. The tests insnippets/pass against the fixture. - A reconciliation job reads
GET /v1/eventsfrom the last stored position and converges to the same state as the webhooks after a simulated outage of the endpoint. - Lists are read page by page with
next_cursoruntilhas_moreis false. - The flow is driven by
next_actionand events: it issues the contract onISSUE_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 everyTFGandCUSTODIANstep without polling a simulator, and handles cancellation and its collateral return. - Unknown fields, enumeration values and event types are tolerated and logged.
- No personal data is sent outside the borrower's personal fields, and none is expected back.
- Sandbox-only code (
/v1/sandbox, the code read-back) cannot run against live. - 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.