Lock a payment schedule
A customer owes a supplier on several dates. Lock each payment with its own lock: one maturity, one deposit and one fee per date. The code below quotes every row, locks every quote, and can be retried or run again without locking any row twice.
1. A batch id, and one key per row
// Your own id for this schedule. Save it with the rows before the first call: every
// Idempotency-Key derives from it, so a rerun sends the same keys.
const batchId = "acme-suppliers-2027-q1";
const rows = [
{ maturity: "2027-01-29T09:00:00Z", usdcNotional: "25000000000" }, // 25,000 USDC
{ maturity: "2027-02-26T09:00:00Z", usdcNotional: "25000000000" },
{ maturity: "2027-03-31T09:00:00Z", usdcNotional: "40000000000" }, // 40,000 USDC
];
// One key per row, step and round. A retry, or a rerun after a crash, sends the same key and
// gets the first answer back (for 24 hours), so no row is ever quoted or locked twice.
const key = (row: number, step: "quote" | "lock", round: number) =>
`${batchId}:row-${row}:${step}:${round}`;
Every POST takes an Idempotency-Key. Replaying a key with the same body returns the first response, refusals included; with a different body it fails with IDEMPOTENCY_KEY_REUSED. That is why the lock key carries the round: a requote is a new quote, so its lock is a new request.
2. Check the limits first
const limits = await certa.limits.get({ customerId });
for (const r of rows) {
if (BigInt(r.usdcNotional) > BigInt(limits.remaining)) {
throw new Error(`${r.maturity}: ${r.usdcNotional} is over the ${limits.remaining} left.`);
}
}
One lock can be at most $100,000, and one customer can have at most $250,000 in active locks. The second limit counts the locks you are creating, so a long schedule can pass this check and still meet LIMIT_EXCEEDED partway through: that row fails and the rest go on (step 5). Each lock also takes its deposit (5%) and fee (0.3%) when it is created, so the wallet needs all of them at once.
3. Skip rows that are already locked
// Keep each lock id with its row as soon as you have it. Keys last 24 hours, so a rerun after
// that also checks the API for a lock already made for the row's date.
const locked = new Map<number, Lock>();
for (const [i, r] of rows.entries()) {
const { data } = await certa.locks.list({
customerId,
maturityFrom: r.maturity,
maturityTo: r.maturity,
});
let lock = data.find((l) => ["pending", "active", "settled"].includes(l.status));
if (lock?.status === "pending") lock = await certa.locks.waitFor(lock.id, ["active", "expired"]);
if (lock && lock.status !== "expired") locked.set(i, lock);
}
4. Quote all, then lock all, within 30 seconds
const terms = (q: Quote) =>
`${q.maturity}: ${q.usdcNotional} USDC for ${q.receiveAmount} EURC at ${q.rate}, ` +
`fee ${q.fee}, deposit ${q.deposit} (minor units), counterparty Certa (testnet)`;
const failed = new Map<number, string>();
let todo = rows.map((_, i) => i).filter((i) => !locked.has(i));
for (let round = 0; round < 3 && todo.length > 0; round++) {
// 1. Quote every row still to do, all at once.
const quoted = await Promise.allSettled(
todo.map((i) =>
certa.quotes.create(
{
pair: "USDC/EURC",
side: "sell_base",
usdcNotional: rows[i]!.usdcNotional,
maturity: rows[i]!.maturity,
customerId,
},
{ idempotencyKey: key(i, "quote", round) },
),
),
);
// 2. Lock every quote at once, well inside the 30 seconds each is firm for.
const attempts = await Promise.allSettled(
todo.map(async (i, n) => {
const q = quoted[n]!;
if (q.status === "rejected") throw q.reason;
console.log(terms(q.value));
const lock = await certa.locks.create(
{ quoteId: q.value.id, execution: "managed" },
{ idempotencyKey: key(i, "lock", round) },
);
return certa.locks.waitFor(lock.id, ["active", "expired"]);
}),
);
// 3. Keep what locked; requote what expired; stop on anything else.
const next: number[] = [];
attempts.forEach((a, n) => {
const i = todo[n]!;
if (a.status === "fulfilled" && a.value.status === "active") locked.set(i, a.value);
else if (a.status === "fulfilled")
next.push(i); // the lock expired: nothing was taken
else if (a.reason instanceof CertaError && a.reason.code === "QUOTE_EXPIRED") next.push(i);
else failed.set(i, a.reason instanceof CertaError ? a.reason.code : String(a.reason));
});
todo = next;
}
for (const i of todo) failed.set(i, "QUOTE_EXPIRED");
Each quote is firm for 30 seconds, so the code quotes every row first, then locks them all at once. A row whose quote expired (QUOTE_EXPIRED) or whose lock did not land in time (status expired; nothing is taken) is quoted again in the next round, with new keys. Quotes are limited to 30 a minute per key: split a longer schedule. With execution: "unsigned" in live mode, the customer's wallet must send every lock's transactions before its quote's expiresAt.
5. Handle partial failure
for (const [i, lock] of locked) console.log(`Row ${i} locked: ${lock.id}`);
for (const [i, code] of failed) console.log(`Row ${i} (${rows[i]!.maturity}) not locked: ${code}`);
Locked rows stay locked. For the others, the error code says what to do:
| Code | What to do |
|---|---|
| LIMIT_EXCEEDED | Lock a smaller amount, or wait until earlier locks settle |
| KYB_REQUIRED | Finish the customer's KYB, then run the schedule again: locked rows are skipped |
| INSUFFICIENT_LIQUIDITY | Retry later, or split the row into smaller locks |
| TENOR_OUT_OF_RANGE | The date is under 1 hour or over 365 days away: move it |
If the schedule must be all or nothing, exit the rows that did lock (see Exit a lock early). That has a cost, so ask the customer first.