# Contracts in another system

Let your ERP, a Laravel shop or another Worker answer offers, stock, tax and order handoff, over HTTP or a Service Binding.

Every contract of OrbCart, [`offers`](/integrations), [`inventory`](/integrations/inventory),
[`tax`](/integrations/tax) and `deliverOrder`, is a function. It does not have to live in the
Worker of OrbCart. Attach an HTTP endpoint or another Worker instead, and OrbCart calls it with the
same arguments, the same time budget and the same rules for a wrong answer.

```ts title="src/worker.ts"
import { defineCommerce, http, service } from "@orbcart/runtime";

export default defineCommerce({
  channels,
  offers: service("PRICES"), // another Worker, through a Service Binding
  inventory: {
    check: http((vars) => vars.get("SHOP_URL") + "/commerce/stock"),
    reserve: http((vars) => vars.get("SHOP_URL") + "/commerce/reserve"),
    release: http((vars) => vars.get("SHOP_URL") + "/commerce/release"),
    commit: http((vars) => vars.get("SHOP_URL") + "/commerce/commit"),
  },
  deliverOrder: http("https://middleware.nordgrat.de/edge/orders", { timeoutMs: 20_000 }),
});
```

An HTTP address follows the [rules of event endpoints](/integrations/events#receive-events-over-http):
`https` on port 443, a name instead of an IP address, nothing private. A contract takes no `types`
and no `previews`, which belong to events. A preview environment calls an HTTP contract like every
other, so read its address from the deployment's variables if it should call something else.

## The call

Each call is a `POST` with `Content-Type: application/json`. The body names the arguments of the
contract and carries the `context`, as you know it from the function:

| Contract            | Service Binding path | Body                           |
| ------------------- | -------------------- | ------------------------------ |
| `offers`            | `/offers`            | `lines`, `context`             |
| `tax`               | `/tax`               | `draft`, `context`             |
| `deliverOrder`      | `/deliver-order`     | `order`, `context`             |
| `inventory.check`   | `/inventory/check`   | `references`, `context`        |
| `inventory.reserve` | `/inventory/reserve` | `hold`, `context`              |
| `inventory.release` | `/inventory/release` | `holdId`, `context`            |
| `inventory.commit`  | `/inventory/commit`  | `holdId`, `orderId`, `context` |

`context` is what a function gets, without the `signal`: `channel`, `environment`, `requestId` and
the fields of the contract, such as `currency` and `purpose` for `offers`. An HTTP endpoint is called
at exactly the address you gave. Answer with a `2xx` and the JSON the contract describes, which is the
value its function returns. An empty body is `{}`. Anything else, a redirect included, counts as
unreachable, and a call that changes something is then repeated with the same key.

Every call carries two headers:

* `Orbcart-Request-Id`: the request, for finding it in the diagnosis. A repeat has a new one.
* `Idempotency-Key`, on the calls that change something (`deliverOrder`, `inventory.reserve`,
  `release` and `commit`): the Order's or the hold's ID, the same in every repeat. Be idempotent on it, and scope it by endpoint: `reserve`, `release` and
  `commit` of one hold carry the same key, so a handler that stores only the key would answer a
  `commit` with the stored answer of the `reserve`.

## Verify an HTTP call

An HTTP call is signed with the environment's key, like an [event](/integrations/events#verify-a-delivery).
Check it in the endpoint:

```ts title="middleware/orders.ts"
import { verifyRequest } from "@orbcart/admin";

export async function handle(request: Request): Promise<Response> {
  const { body, idempotencyKey } = await verifyRequest(request, {
    url: "https://commerce.nordgrat.de",
  });
  const { order } = body as { order: { id: string } };

  const reference = await erp.createSalesOrder(order, { idempotencyKey });
  return Response.json({ reference });
}
```

`verifyRequest` throws a `RequestVerificationError` with a `code` when the call is not what the
environment signed; answer those with a 4xx. A signature made for an event never passes here, and a
contract's never passes `verifyEvent`. A Service Binding is not signed: only your own account can
reach it.

To try your endpoint against the real thing, `@orbcart/runtime/testing` builds the signed request:

```ts
import { signedContractCall } from "@orbcart/runtime/testing";

const request = await signedContractCall(
  env,
  "deliverOrder",
  "https://middleware.nordgrat.de/edge/orders",
  { order },
);
```

The signature covers `@method`, `@authority`, `@path`, `@query`, `content-type`, `content-digest` and
`orbcart-request-id`, and `idempotency-key` where the call carries one, with `tag="orbcart-contract"`.
For another language, any library for [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421) verifies it
against the keys at `/.well-known/jwks.json`.