Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirSwap extends PostProcessEvent
/** * Voting round — validate the trade is well-formed and both sides can cover * their leg. A thrown string is the revert reason. */
public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
try {
switch (this.transactions.$entry) {
case "swap":
return resolve(await this.voteSwap());
case "fill":
return resolve(await this.voteFill());
case "match":
return resolve(await this.voteMatch());
case "cancel":
return resolve(await this.voteCancel());
case "proposeOrder":
return resolve(await this.voteProposeOrder());
case "voidOrder":
return resolve(await this.voteVoidOrder());
case "approveOrder":
return resolve(await this.voteApproveOrder());
case "release":
return resolve(await this.voteRelease());
default:
return reject("Unknown entry point");
}
} catch (e) {
return reject(typeof e === "string" ? e : (e as Error)?.message ?? "Swap vote failed");
}
});
}/** Commit — move both legs atomically. */
public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
try {
switch (this.transactions.$entry) {
case "swap":
return resolve(await this.commitSwap());
case "fill":
return resolve(await this.commitFill());
case "match":
return resolve(await this.commitMatch());
case "cancel":
return resolve(await this.commitCancel());
case "proposeOrder":
return resolve(await this.commitProposeOrder());
case "voidOrder":
return resolve(await this.commitVoidOrder());
case "approveOrder":
return resolve(await this.commitApproveOrder());
case "release":
return resolve(await this.commitRelease());
default:
return reject("Unknown entry point");
}
} catch (e) {
return reject(typeof e === "string" ? e : (e as Error)?.message ?? "Swap commit failed");
}
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
}/** * `swap` vote: both `$i.maker` and `$i.taker` are inputs, so both sign. * Refuses a missing side, a self-trade, a non-positive amount, a read-only * key on either side, an AFX / treasury identity or a key whose policy * refuses its give-leg (assertSwapAllowed), and a side whose balance does * not cover what it gives. */
private async voteSwap(): Promise<boolean> {
const makerInput = this.transactions.$i.maker;
const takerInput = this.transactions.$i.taker;
if (!makerInput || !takerInput) {
throw "Swap needs both a maker and a taker input";
}
this.makerLeg = this.readLeg(makerInput, "maker");
this.takerLeg = this.readLeg(takerInput, "taker");
// No self-trade: a swap between an identity and itself is meaningless and
// would let a single signer move its own partitions under a trade label.
if (this.makerLeg.stream === this.takerLeg.stream) {
throw "Self-trade rejected: maker and taker are the same identity";
}
// Both legs must move a positive amount.
if (!this.makerLeg.amount.gt(0)) throw "Maker amount must be greater than 0";
if (!this.takerLeg.amount.gt(0)) throw "Taker amount must be greater than 0";
this.maker = this.getActivityStreams(makerInput);
this.taker = this.getActivityStreams(takerInput);
// A read-only key (customer-service tier) may never move funds — mirror the
// stake-9000 guard the transfer contract applies to its owner input.
if (this.isReadOnlyKey(this.maker)) {
throw "Maker key is read-only and cannot swap";
}
if (this.isReadOnlyKey(this.taker)) {
throw "Taker key is read-only and cannot swap";
}
this.makerState = this.maker.getState();
this.takerState = this.taker.getState();
// Authorization parity with the transfer contract: the swap must not become
// a second, unguarded way to drain a protected identity. Fail closed for
// AFX-bound or treasury (M-of-N) identities — v1 has no propose/confirm path.
// Both parties are $i inputs, so both tx-sign — the governing key is the
// tx signer (this.sigs), resolved via swapSigningKeyHash.
this.assertSwapAllowed(
this.maker,
this.makerState,
"Maker",
this.swapSigningKeyHash(this.maker),
this.makerLeg.network,
this.makerLeg.token,
this.makerLeg.amount,
this.makerLeg.amount,
false,
);
this.assertSwapAllowed(
this.taker,
this.takerState,
"Taker",
this.swapSigningKeyHash(this.taker),
this.takerLeg.network,
this.takerLeg.token,
this.takerLeg.amount,
this.takerLeg.amount,
false,
);
// Each side must hold what it GIVES, in that side's give-partition.
const makerBalance = this.l2Get(this.makerState, this.makerLeg.network, this.makerLeg.token);
if (makerBalance.lt(this.makerLeg.amount)) {
throw `Maker balance too low: ${makerBalance} < ${this.makerLeg.amount}`;
}
const takerBalance = this.l2Get(this.takerState, this.takerLeg.network, this.takerLeg.token);
if (takerBalance.lt(this.takerLeg.amount)) {
throw `Taker balance too low: ${takerBalance} < ${this.takerLeg.amount}`;
}
return true;
}/** * `swap` commit: moves the maker's leg to the taker and the taker's leg to * the maker in one write per side, bumps each governed key's spend * counter, emits `l2-swap` (entry "swap") and returns both `layer2`s. No * fee. */
private async commitSwap(): Promise<any> {
// v1 is intentionally FEE-FREE, unlike the transfer contract which charges a
// fee on chargeable-token transfers. Which side pays a swap fee is an open
// design question ("Fee leg" in docs/exchange-swap-design.md).
//
// maker's asset -> taker. Read each balance fresh so a leg that happens to
// share a partition (same network+token on both sides) still nets correctly.
const makerGive = this.l2Get(this.makerState, this.makerLeg.network, this.makerLeg.token);
this.l2Set(this.makerState, this.makerLeg.network, this.makerLeg.token, makerGive.sub(this.makerLeg.amount));
const takerRecv = this.l2Get(this.takerState, this.makerLeg.network, this.makerLeg.token);
this.l2Set(this.takerState, this.makerLeg.network, this.makerLeg.token, takerRecv.add(this.makerLeg.amount));
// taker's asset -> maker.
const takerGive = this.l2Get(this.takerState, this.takerLeg.network, this.takerLeg.token);
this.l2Set(this.takerState, this.takerLeg.network, this.takerLeg.token, takerGive.sub(this.takerLeg.amount));
const makerRecv = this.l2Get(this.makerState, this.takerLeg.network, this.takerLeg.token);
this.l2Set(this.makerState, this.takerLeg.network, this.takerLeg.token, makerRecv.add(this.takerLeg.amount));
// Increment each governed party's per-asset spend counter for its give-leg,
// onto its own state so it rides the setState below (unified-keys Task 4).
this.bumpSwapUsage(this.makerState, this.swapSigningKeyHash(this.maker), this.makerLeg.network, this.makerLeg.token, this.makerLeg.amount);
this.bumpSwapUsage(this.takerState, this.swapSigningKeyHash(this.taker), this.takerLeg.network, this.takerLeg.token, this.takerLeg.amount);
// Stage both streams' new state — this is what commits the mutation. Both
// are inputs, so both are writable; there is no partial-write path.
this.maker.setState(this.makerState);
this.taker.setState(this.takerState);
// Emit for minigate's SSE listener to record the swap in the scanner's
// history, mirroring the 'l2-transfer' event the transfer contract emits.
// NOT yet consumed: adding the 'l2-swap' case to minigate + /api/ingest is
// build-order step 4 (docs/exchange-swap-design.md). Emitting ahead of the
// consumer is intentional and harmless (the transfer contract does the same
// with its own not-yet-consumed events).
this.event.emit("l2-swap", {
umid: this.umid,
// Which commit path emitted this — the settlement-lineage provenance the
// scanner shows. A co-sign swap has no resting order, so no orderHash.
entry: "swap",
maker: this.maker.getId(),
taker: this.taker.getId(),
makerGive: {
network: this.makerLeg.network,
token: this.makerLeg.token,
amount: this.makerLeg.amount.toString(),
},
takerGive: {
network: this.takerLeg.network,
token: this.takerLeg.token,
amount: this.takerLeg.amount.toString(),
},
when: this.cDate,
});
this.returnToRemote([
{ id: this.maker.getId(), partitions: this.makerState.layer2 },
{ id: this.taker.getId(), partitions: this.takerState.layer2 },
]);
return true;
}/** * `fill` vote. Refuses: a missing maker, taker, order or signature; an * order not naming the carried maker; a self-trade; non-positive legs; an * expired order (`order.expire` against cDate); a read-only taker key; an * invalid maker signature or one for another deployment; a terminal * marker or nothing left to fill; a taker leg outside the order's want * partition, above the remaining want, or not dividing the order evenly; * a maker-rate give below the taker's `minReceive`; either side failing * assertSwapAllowed; and a balance that does not cover this fill. */
private async voteFill(): Promise<boolean> {
const makerOut = this.transactions.$o ? this.transactions.$o.maker : undefined;
const takerInput = this.transactions.$i ? this.transactions.$i.taker : undefined;
// 1. Both parties, and the signed order, must be present.
if (!makerOut || !takerInput) {
throw "Fill needs a maker ($o) and a taker ($i)";
}
const order = makerOut.order;
const sig = makerOut.sig;
if (!order || !sig) {
throw "Fill is missing the maker's signed order or signature";
}
// 2. The order must name the carried maker, and a maker cannot fill itself.
if (order.maker !== makerOut.$stream) {
throw "Order maker does not match the carried maker stream";
}
if (order.maker === takerInput.$stream) {
throw "Self-trade rejected: maker and taker are the same identity";
}
// Parse the order's two asset legs (raw amounts, partition keys used as-is).
this.orderGive = this.parseAsset(order.give, "Order give");
this.orderWant = this.parseAsset(order.want, "Order want");
if (!this.orderGive.amount.gt(0)) throw "Order give amount must be greater than 0";
if (!this.orderWant.amount.gt(0)) throw "Order want amount must be greater than 0";
// 3. The ORDER's own expiry (distinct from the tx's $expire, which the ledger
// enforces). order.expire is ms since epoch; reject a fill past it.
// Consensus clock ONLY — this.cDate is the ledger's per-tx timestamp, equal
// on every node. No `?? Date.now()` fallback: a per-node wall clock would
// diverge and break consensus. If cDate were ever absent, new Date(undefined)
// is NaN and the expiry check below fails closed identically on all nodes.
const nowMs = new Date(this.cDate).getTime();
const expire = Number(order.expire);
if (!(expire > nowMs)) {
throw "Order has expired";
}
this.orderMaker = this.getActivityStreams(makerOut);
this.orderTaker = this.getActivityStreams(takerInput);
// 7 (taker half). A read-only (customer-service tier) key may never move
// funds. The maker's read-only keys are excluded by the verify loop below.
if (this.isReadOnlyKey(this.orderTaker)) {
throw "Taker key is read-only and cannot fill";
}
// 4. Verify the maker's order signature against its stream authorities (see
// verifyOrderSig — the same loop match uses for both of its orders).
// Capture the verifying authority's key hash: the carried maker does NOT
// tx-sign, so this off-ledger order signer is its governing key for the
// give-leg policy below (unified-keys Task 4). null = no authority verified.
this.orderMakerKeyHash = this.verifyOrderSig(this.orderMaker, order, sig);
if (this.orderMakerKeyHash === null) {
throw "Maker order signature invalid";
}
// 4a. The order's signing key must be live NOW (not expired) and resolve to
// a hash. A resting order is signed off-ledger, so the engine never
// checks this key's expiry; without this, a leaked expired agent key
// could still sign orders that fill settles. Same rule as Markets.
if (this.orderMakerKeyHash === ORDER_SIGNER_UNRESOLVED || !this.liveAuthority(this.orderMaker, this.orderMakerKeyHash)) {
throw "Maker order signing key is expired or unknown";
}
// 4b. Domain separation (Low-1): the maker signed this order for THIS
// deployment. Reject a signature replayed against another namespace or a
// different Swap contract (see verifyOrderDomain).
if (!this.verifyOrderDomain(order)) {
throw "Maker order not signed for this deployment (domain mismatch)";
}
this.orderMakerState = this.orderMaker.getState();
this.orderTakerState = this.orderTaker.getState();
// 7 (both). AFX/treasury refuse + off-ledger/policy enforcement is applied
// below, once this fill's give-legs (fillGive/fillWant) are known — the
// spend-policy check needs the amount actually moved, not the whole order.
// 5. Consume/cancel marker: cumulative fill progress, keyed on the maker's
// own state. A TERMINAL marker (cancelled, done, or a legacy pre-partial
// full-fill) blocks any further fill; a non-terminal partial marker
// carries its progress forward so the remainder can still be filled.
this.orderHash = this.ActiveCrypto.Hash.getHash(JSON.stringify(order), "sha256");
const marker = this.readMarker(
this.orderMakerState.orders ? this.orderMakerState.orders[this.orderHash] : undefined,
);
if (marker.terminal) {
throw "Order already filled or cancelled";
}
this.priorFilledWant = marker.filledWant;
this.priorFilledGive = marker.filledGive;
const remainingWant = this.orderWant.amount.sub(marker.filledWant);
if (!remainingWant.gt(0)) {
throw "Order already filled or cancelled";
}
// 6. PARTIAL FILL: the taker's leg is the portion of order.want it takes now
// (fillWant), in the order's want partition. It must be positive and no
// more than the remaining want. The maker's give is pro-rata at the
// order's OWN signed rate: fillGive = give * fillWant / want. That
// division MUST be exact — a fill that would leave a fractional smallest
// unit is rejected. Exact division means the partial gives sum back to
// `give` with zero dust, and the arithmetic is pure BigInt so every node
// computes the identical fillGive (no Date.now()/float nondeterminism).
const takerLeg = this.readLeg(takerInput, "taker");
if (
takerLeg.network !== this.orderWant.network ||
takerLeg.token !== this.orderWant.token
) {
throw "Taker fill must be in the order's want partition";
}
this.fillWant = takerLeg.amount;
if (!this.fillWant.gt(0)) throw "Taker fill amount must be greater than 0";
if (this.fillWant.gt(remainingWant)) {
throw `Taker fill exceeds the order's remaining want: ${this.fillWant} > ${remainingWant}`;
}
const giveTimesFill = this.orderGive.amount.mul(this.fillWant);
if (!giveTimesFill.mod(this.orderWant.amount).eq(0)) {
throw "Taker fill must divide the order evenly (no fractional-unit dust)";
}
this.fillGive = giveTimesFill.div(this.orderWant.amount);
// 6b. TAKER LIMIT (crossing / best execution): a direct fill ALWAYS settles
// at the MAKER's signed rate (fillGive above) — the taker receives the
// maker-rate give for the want it spends, never a worse rate. A taker MAY
// carry `minReceive`: the minimum give-asset it will accept for this fill
// (its own limit price, in the order's give partition, smallest units). It
// mirrors the maker-price principle of match: settle at the maker's rate,
// and if that rate would give the taker LESS than its floor — the taker's
// bid is below the maker's ask, "worse than rate" — reject; otherwise fill
// at the maker rate and the taker KEEPS the improvement (the extra give it
// receives above its floor). This is the SAME single cross check match
// uses: fillGive >= minReceive ⇔ orderGive·fillWant >= orderWant·minReceive
// ⇔ the taker's bid crosses the maker's ask. Pure BigInt threshold — no
// division, no dust. Absent minReceive the fill is unconstrained beyond the
// maker rate, exactly as before: fully backward compatible (the SDK does
// not send it yet, so every existing fill behaves identically). Because the
// taker spends a FIXED want (fillWant), the improvement here is extra give
// RECEIVED (not want left unspent, as in match where fillX is fixed) — the
// taker still spends exactly fillWant, so commitFill is unchanged.
if (
takerInput.minReceive !== undefined &&
takerInput.minReceive !== null &&
takerInput.minReceive !== ""
) {
const rawMin = String(takerInput.minReceive);
if (!/^[0-9]+$/.test(rawMin)) {
throw "Taker minReceive must be a decimal integer in smallest units";
}
if (this.fillGive.lt(BN.from(rawMin))) {
throw `Taker fill below its limit: maker rate yields ${this.fillGive} < minReceive ${rawMin} (taker's bid is below the maker's ask)`;
}
}
// 7 (both). Fail closed for AFX/treasury identities, refuse an off-ledger
// key, and enforce the give-leg spending policy — the maker gives fillGive
// of its give-asset, the taker gives fillWant of the order's want-asset.
// The carried maker is governed by its OFF-LEDGER order signer
// (orderMakerKeyHash); the live taker tx-signs, so by this.sigs.
// An APPROVED maker order settles from its hold instead (assertHeldGive),
// because its approval already satisfied the thresholds and its period
// cap was counted in full at approval.
this.orderMakerApproved = this.approvedRecord(this.orderMakerState, this.orderHash);
if (this.orderMakerApproved) {
this.assertHeldGive(
this.orderMaker,
this.orderMakerState,
"Maker",
this.orderHash,
this.orderMakerApproved,
this.orderMakerKeyHash,
this.orderGive,
this.fillGive,
);
} else {
this.assertSwapAllowed(
this.orderMaker,
this.orderMakerState,
"Maker",
this.orderMakerKeyHash,
this.orderGive.network,
this.orderGive.token,
this.fillGive,
this.orderGive.amount,
true,
);
}
this.assertSwapAllowed(
this.orderTaker,
this.orderTakerState,
"Taker",
this.swapSigningKeyHash(this.orderTaker),
this.orderWant.network,
this.orderWant.token,
this.fillWant,
this.fillWant,
false,
);
// 8. Balances: the maker holds this fill's give (in its hold when the order
// is approved - checked in assertHeldGive), the taker holds its want.
if (!this.orderMakerApproved) {
const makerBalance = this.l2Get(this.orderMakerState, this.orderGive.network, this.orderGive.token);
if (makerBalance.lt(this.fillGive)) {
throw `Maker balance too low: ${makerBalance} < ${this.fillGive}`;
}
}
const takerBalance = this.l2Get(this.orderTakerState, this.orderWant.network, this.orderWant.token);
if (takerBalance.lt(this.fillWant)) {
throw `Taker balance too low: ${takerBalance} < ${this.fillWant}`;
}
this.orderObj = order;
return true;
}/** * `fill` commit: moves this fill's pro-rata give to the taker and its want * to the maker, updates the maker's marker (`filledWant`, `filledGive`, * `lastFill`, `done`), bumps both spend counters, emits `l2-swap` (entry * "fill", with `partial` and `remainingWant`) and returns both `layer2`s. */
private async commitFill(): Promise<any> {
// maker's give-asset -> taker (this fill's pro-rata give, not the whole
// order). Read each balance fresh so a leg that shares a partition still
// nets, same partition-safe logic as commitSwap. An approved order gives
// from its hold, not its balance.
this.debitGive(this.orderMakerState, this.orderHash, !!this.orderMakerApproved, this.orderGive, this.fillGive);
const takerRecv = this.l2Get(this.orderTakerState, this.orderGive.network, this.orderGive.token);
this.l2Set(this.orderTakerState, this.orderGive.network, this.orderGive.token, takerRecv.add(this.fillGive));
// taker's want-asset -> maker (this fill's want portion).
const takerGive = this.l2Get(this.orderTakerState, this.orderWant.network, this.orderWant.token);
this.l2Set(this.orderTakerState, this.orderWant.network, this.orderWant.token, takerGive.sub(this.fillWant));
const makerRecv = this.l2Get(this.orderMakerState, this.orderWant.network, this.orderWant.token);
this.l2Set(this.orderMakerState, this.orderWant.network, this.orderWant.token, makerRecv.add(this.fillWant));
// Accumulate this fill onto the maker's marker (keyed on the order hash, on
// the maker's own state). `done` when the cumulative want reaches order.want
// — by construction it lands exactly on it (fillWant <= remaining, and a
// final fill takes the exact remainder), never past. A done marker is
// terminal (readMarker): the order can no longer be filled or re-filled.
if (!this.orderMakerState.orders) this.orderMakerState.orders = {};
const newFilledWant = this.priorFilledWant.add(this.fillWant);
const newFilledGive = this.priorFilledGive.add(this.fillGive);
const done = !newFilledWant.lt(this.orderWant.amount);
this.orderMakerState.orders[this.orderHash] = {
...(this.orderMakerApproved ? { approved: this.orderMakerApproved } : {}),
filledWant: newFilledWant.toString(),
filledGive: newFilledGive.toString(),
lastFill: this.umid,
done,
};
// A done approved order returns whatever its hold still has to balance.
if (this.orderMakerApproved && done) this.releaseHold(this.orderMakerState, this.orderHash);
// Increment each governed party's per-asset spend counter for its give-leg
// (maker gives fillGive of orderGive; taker gives fillWant of orderWant),
// onto its own state so it rides the setState below (unified-keys Task 4).
// Not for an approved order: its whole maximum was counted at approval.
if (!this.orderMakerApproved) {
this.bumpSwapUsage(this.orderMakerState, this.orderMakerKeyHash, this.orderGive.network, this.orderGive.token, this.fillGive);
}
this.bumpSwapUsage(this.orderTakerState, this.swapSigningKeyHash(this.orderTaker), this.orderWant.network, this.orderWant.token, this.fillWant);
this.orderMaker.setState(this.orderMakerState);
this.orderTaker.setState(this.orderTakerState);
// Emit the SAME event a co-sign swap emits, so the scanner + notifications
// treat a fill exactly like a swap — but carry THIS fill's actual moved
// amounts (fillGive/fillWant), plus the partial-fill provenance the scanner
// shows: whether the order is now fully filled and how much want remains.
const remainingWant = this.orderWant.amount.sub(newFilledWant);
this.event.emit("l2-swap", {
umid: this.umid,
// Settlement-lineage provenance: a resting-order fill, and the maker's
// resting-order hash (the same consume marker written to state above).
entry: "fill",
orderHash: this.orderHash,
// A fill that does not complete the order is a partial fill; the remainder
// stays resting. The scanner labels these and shows the remaining want.
partial: !done,
remainingWant: remainingWant.toString(),
orderGive: this.orderGive.amount.toString(),
orderWant: this.orderWant.amount.toString(),
maker: this.orderObj.maker,
taker: this.orderTaker.getId(),
makerGive: {
network: this.orderGive.network,
token: this.orderGive.token,
amount: this.fillGive.toString(),
},
takerGive: {
network: this.orderWant.network,
token: this.orderWant.token,
amount: this.fillWant.toString(),
},
when: this.cDate,
});
this.returnToRemote([
{ id: this.orderMaker.getId(), partitions: this.orderMakerState.layer2 },
{ id: this.orderTaker.getId(), partitions: this.orderTakerState.layer2 },
]);
return true;
}/** * `match` vote. The contract does not restrict who the submitter is; funds * move only under the two verified order signatures. Refuses: a missing * submitter, party, order or signature; an order not naming its carried * party; a self-trade; non-positive legs; orders that are not opposite * assets or do not cross; an expired order; an invalid signature or one * for another deployment; a terminal marker or nothing left on either * side; a fill that does not divide evenly or exceeds a remaining side; * either party failing assertSwapAllowed; and a balance that does not * cover this match. */
private async voteMatch(): Promise<boolean> {
// The submitter ($i.submitter) only makes the tx valid (the ledger requires
// its signature). Nothing here reads a balance or fund-authority from it — it
// is neither debited nor credited, so it needs no read-only guard.
const submitter = this.transactions.$i ? this.transactions.$i.submitter : undefined;
const a = this.transactions.$o ? this.transactions.$o.a : undefined;
const b = this.transactions.$o ? this.transactions.$o.b : undefined;
// 1. The submitter and both carried parties (with their signed orders) present.
if (!submitter || !submitter.$stream) {
throw "Match needs a submitter ($i.submitter)";
}
if (!a || !b) {
throw "Match needs both parties ($o.a and $o.b)";
}
const orderA = a.order;
const sigA = a.sig;
const orderB = b.order;
const sigB = b.sig;
if (!orderA || !sigA) throw "Match is missing party A's signed order or signature";
if (!orderB || !sigB) throw "Match is missing party B's signed order or signature";
// 2. Each order must name its own carried party stream.
if (orderA.maker !== a.$stream) throw "Order A maker does not match the carried A stream";
if (orderB.maker !== b.$stream) throw "Order B maker does not match the carried B stream";
// 3. No self-trade.
if (a.$stream === b.$stream) {
throw "Self-trade rejected: both parties are the same identity";
}
// 4. Parse all four asset legs (raw amounts, partition keys used as-is).
const giveA = this.parseAsset(orderA.give, "Order A give");
const wantA = this.parseAsset(orderA.want, "Order A want");
const giveB = this.parseAsset(orderB.give, "Order B give");
const wantB = this.parseAsset(orderB.want, "Order B want");
if (!giveA.amount.gt(0)) throw "Order A give amount must be greater than 0";
if (!wantA.amount.gt(0)) throw "Order A want amount must be greater than 0";
if (!giveB.amount.gt(0)) throw "Order B give amount must be greater than 0";
if (!wantB.amount.gt(0)) throw "Order B want amount must be greater than 0";
// 5. Compatibility — ASSET mirror + CROSSING SPREAD (true limit orders;
// amounts may differ, partial matching fills the smaller side and the
// remainder stays resting):
// - A gives asset X and B wants asset X (same network+token);
// - A wants asset Y and B gives asset Y (same network+token);
// - and the two orders CROSS. A is the RESTING MAKER, B the incoming taker
// (the off-ledger matcher passes the resting maker as A). A's ask rate is
// wantA/giveA (Y per X); B (giving Y, wanting X) bids up to giveB/wantB
// (Y per X). B crosses A iff B's bid >= A's ask, i.e.
// wantA/giveA <= giveB/wantB ⇔ wantA·wantB <= giveA·giveB
// (cross-multiplied, exact integer, no float). Reject the strict-greater
// "not crossing" case (B's bid below A's ask). Equality still satisfies
// <=, so same-rate orders match exactly as before (no book migration).
//
// SETTLEMENT IS ALWAYS AT A's (THE MAKER's) RATE: fillY = fillX·wantA/giveA
// (computed below, UNCHANGED). Standard best execution — the incoming taker
// gets the price improvement. SAFETY INVARIANT: under the cross condition
// this is within BOTH parties' signed terms. A receives exactly its signed
// rate by construction. B pays fillY/fillX = wantA/giveA Y-per-X, and the
// cross condition is exactly wantA/giveA <= giveB/wantB, so B pays <= its
// signed max (keeps the surplus Y it did not spend). The single cross check
// is therefore ALSO B's limit guard.
const assetEq = (
x: { network: string; token: string },
y: { network: string; token: string },
): boolean => x.network === y.network && x.token === y.token;
if (!assetEq(giveA, wantB) || !assetEq(wantA, giveB)) {
throw "Orders do not match: assets are not opposite counterparts";
}
if (wantA.amount.mul(wantB.amount).gt(giveA.amount.mul(giveB.amount))) {
throw "Orders do not cross: the incoming taker's bid is below the resting maker's ask";
}
// 6. Neither order expired (order.expire is ms since epoch), for BOTH.
// Consensus clock ONLY — this.cDate is the ledger's per-tx timestamp, equal
// on every node. No `?? Date.now()` fallback: a per-node wall clock would
// diverge and break consensus. If cDate were ever absent, new Date(undefined)
// is NaN and the expiry check below fails closed identically on all nodes.
const nowMs = new Date(this.cDate).getTime();
if (!(Number(orderA.expire) > nowMs)) throw "Order A has expired";
if (!(Number(orderB.expire) > nowMs)) throw "Order B has expired";
this.matchA = this.getActivityStreams(a);
this.matchB = this.getActivityStreams(b);
// 7. Verify BOTH order signatures, each against its OWN party's authorities.
// Read-only maker keys are excluded inside verifyOrderSig, so there is no
// separate read-only guard here (and no live taker to guard either).
// Capture each verifying authority's key hash: neither party tx-signs, so
// these off-ledger order signers are their governing keys for the give-leg
// policy below (unified-keys Task 4). null = no authority verified.
this.matchKeyHashA = this.verifyOrderSig(this.matchA, orderA, sigA);
if (this.matchKeyHashA === null) {
throw "Order A signature invalid";
}
this.matchKeyHashB = this.verifyOrderSig(this.matchB, orderB, sigB);
if (this.matchKeyHashB === null) {
throw "Order B signature invalid";
}
// 7a. Each order's signing key must be live NOW (not expired) and resolve to
// a hash: off-ledger order signatures never reach the engine's expiry
// check, so this contract must refuse an expired key itself (as Markets).
if (this.matchKeyHashA === ORDER_SIGNER_UNRESOLVED || !this.liveAuthority(this.matchA, this.matchKeyHashA)) {
throw "Order A signing key is expired or unknown";
}
if (this.matchKeyHashB === ORDER_SIGNER_UNRESOLVED || !this.liveAuthority(this.matchB, this.matchKeyHashB)) {
throw "Order B signing key is expired or unknown";
}
// 7b. Domain separation (Low-1): both orders must be signed for THIS
// deployment (namespace + this Swap contract), else reject.
if (!this.verifyOrderDomain(orderA)) {
throw "Order A not signed for this deployment (domain mismatch)";
}
if (!this.verifyOrderDomain(orderB)) {
throw "Order B not signed for this deployment (domain mismatch)";
}
this.matchStateA = this.matchA.getState();
this.matchStateB = this.matchB.getState();
// 9. AFX/treasury refuse + off-ledger/policy enforcement is applied below,
// once this match's give-legs (fillX/fillY) are known — the spend-policy
// check needs the amount actually moved this match, not the whole order.
// 8. Consume markers → cumulative progress, keyed on each party's own state.
// A TERMINAL marker (done, cancelled, or a legacy full-fill) blocks the
// party; otherwise its partial progress carries forward (see readMarker).
this.matchHashA = this.ActiveCrypto.Hash.getHash(JSON.stringify(orderA), "sha256");
this.matchHashB = this.ActiveCrypto.Hash.getHash(JSON.stringify(orderB), "sha256");
const markerA = this.readMarker(this.matchStateA.orders ? this.matchStateA.orders[this.matchHashA] : undefined);
const markerB = this.readMarker(this.matchStateB.orders ? this.matchStateB.orders[this.matchHashB] : undefined);
if (markerA.terminal) throw "Order A already filled or cancelled";
if (markerB.terminal) throw "Order B already filled or cancelled";
this.matchPriorA = { filledWant: markerA.filledWant, filledGive: markerA.filledGive };
this.matchPriorB = { filledWant: markerB.filledWant, filledGive: markerB.filledGive };
// PARTIAL MATCH: fill the SMALLER open side, measured in asset X (what A
// gives / B wants). A's remaining give X = giveA - A.filledGive; B's
// remaining want X = wantB - B.filledWant. The counter-amount fillY moves at
// the agreed rate (Y per X = wantA/giveA) and MUST divide exactly — no
// fractional-unit dust, pure BigInt so every node computes the same fillY.
//
// The Y sides cap fillX too: A's remaining want Y = wantA - A.filledWant and
// B's remaining give Y = giveB - B.filledGive. Orders cross, so a party that
// took price improvement earlier (as an incoming B, it paid less than its
// own rate) has less Y left to want than its remaining X give buys at its
// own rate. fillX is therefore also capped at floor(minRemainY * giveA /
// wantA), the most X whose fillY fits both Y sides. When that cap does not
// bind, fillX is exactly the smaller X side as before.
const aRemainGiveX = giveA.amount.sub(markerA.filledGive);
const bRemainWantX = wantB.amount.sub(markerB.filledWant);
if (!aRemainGiveX.gt(0) || !bRemainWantX.gt(0)) {
throw "Order already fully filled or cancelled";
}
const aRemainWantY = wantA.amount.sub(markerA.filledWant);
const bRemainGiveY = giveB.amount.sub(markerB.filledGive);
const remainY = aRemainWantY.lt(bRemainGiveY) ? aRemainWantY : bRemainGiveY;
const capXFromY = remainY.gt(0) ? remainY.mul(giveA.amount).div(wantA.amount) : BN.from(0);
// No whole unit of X fits both Y sides (a marker run ahead of its order): refuse, never over-pay.
if (!capXFromY.gt(0)) throw "Match amount exceeds an order's remaining side";
let fillX = aRemainGiveX.lt(bRemainWantX) ? aRemainGiveX : bRemainWantX;
if (capXFromY.lt(fillX)) fillX = capXFromY;
const fillXTimesRate = fillX.mul(wantA.amount);
if (!fillXTimesRate.mod(giveA.amount).eq(0)) {
throw "Match amount must divide the order evenly (no fractional-unit dust)";
}
const fillY = fillXTimesRate.div(giveA.amount);
if (!fillX.gt(0) || !fillY.gt(0)) throw "Match amount resolves to zero";
// Defensive: never move more than either party's remaining Y side. Holds by
// the Y cap above; rejects rather than over-move if it ever does not.
if (fillY.gt(aRemainWantY) || fillY.gt(bRemainGiveY)) {
throw "Match amount exceeds an order's remaining side";
}
this.matchFillA = fillX; // A gives X this match
this.matchFillB = fillY; // B gives Y this match
// 9. Fail closed for AFX/treasury identities, refuse an off-ledger key, and
// enforce the give-leg spending policy on BOTH parties — A gives fillX of
// its give-asset X, B gives fillY of its give-asset Y. Both are carried
// resting orders that do NOT tx-sign, so each is governed by its
// OFF-LEDGER order signer (matchKeyHashA / matchKeyHashB). An APPROVED
// order settles from its hold instead (assertHeldGive), as in fill.
this.matchApprovedA = this.approvedRecord(this.matchStateA, this.matchHashA);
this.matchApprovedB = this.approvedRecord(this.matchStateB, this.matchHashB);
if (this.matchApprovedA) {
this.assertHeldGive(this.matchA, this.matchStateA, "Party A", this.matchHashA, this.matchApprovedA, this.matchKeyHashA, giveA, fillX);
} else {
this.assertSwapAllowed(
this.matchA,
this.matchStateA,
"Party A",
this.matchKeyHashA,
giveA.network,
giveA.token,
fillX,
giveA.amount,
true,
);
}
if (this.matchApprovedB) {
this.assertHeldGive(this.matchB, this.matchStateB, "Party B", this.matchHashB, this.matchApprovedB, this.matchKeyHashB, giveB, fillY);
} else {
this.assertSwapAllowed(
this.matchB,
this.matchStateB,
"Party B",
this.matchKeyHashB,
giveB.network,
giveB.token,
fillY,
giveB.amount,
true,
);
}
// 10. Balances: A holds THIS match's give (fillX of X); B holds fillY of Y.
// A held party's give was checked against its hold in assertHeldGive.
if (!this.matchApprovedA) {
const balA = this.l2Get(this.matchStateA, giveA.network, giveA.token);
if (balA.lt(fillX)) {
throw `Party A balance too low: ${balA} < ${fillX}`;
}
}
if (!this.matchApprovedB) {
const balB = this.l2Get(this.matchStateB, giveB.network, giveB.token);
if (balB.lt(fillY)) {
throw `Party B balance too low: ${balB} < ${fillY}`;
}
}
this.matchOrderA = orderA;
this.matchOrderB = orderB;
this.matchGiveA = giveA;
this.matchGiveB = giveB;
this.matchWantA = wantA;
this.matchWantB = wantB;
// The neutral submitter's stream — carried into the emitted event as the
// node that relayed this settlement (it neither gives nor receives funds).
this.matchSubmitter = submitter.$stream;
return true;
}/** * `match` commit: A gives `matchFillA` of asset X to B and B gives * `matchFillB` of asset Y to A, both markers are updated, both spend * counters bumped, `l2-swap` (entry "match", with `bookUpdate`) is emitted * and both `layer2`s are returned. */
private async commitMatch(): Promise<any> {
// party A gives THIS match's fillA of its give-asset X -> party B. Read each
// balance fresh so a leg sharing a partition still nets (as commitFill).
// An approved party gives from its hold, not its balance.
this.debitGive(this.matchStateA, this.matchHashA, !!this.matchApprovedA, this.matchGiveA, this.matchFillA);
const bRecv = this.l2Get(this.matchStateB, this.matchGiveA.network, this.matchGiveA.token);
this.l2Set(this.matchStateB, this.matchGiveA.network, this.matchGiveA.token, bRecv.add(this.matchFillA));
// party B gives THIS match's fillB of its give-asset Y -> party A.
this.debitGive(this.matchStateB, this.matchHashB, !!this.matchApprovedB, this.matchGiveB, this.matchFillB);
const aRecv = this.l2Get(this.matchStateA, this.matchGiveB.network, this.matchGiveB.token);
this.l2Set(this.matchStateA, this.matchGiveB.network, this.matchGiveB.token, aRecv.add(this.matchFillB));
// Accumulate progress onto BOTH parties' markers (each on its own state).
// A gives X (fillA) and receives Y (fillB): A.filledGive += fillA (X),
// A.filledWant += fillB (Y). B is the mirror: gives Y (fillB), receives X
// (fillA). done when a party's cumulative want reaches its order.want.
if (!this.matchStateA.orders) this.matchStateA.orders = {};
const aFilledGive = this.matchPriorA.filledGive.add(this.matchFillA);
const aFilledWant = this.matchPriorA.filledWant.add(this.matchFillB);
const aDone = !aFilledWant.lt(this.matchWantA.amount);
this.matchStateA.orders[this.matchHashA] = {
...(this.matchApprovedA ? { approved: this.matchApprovedA } : {}),
filledWant: aFilledWant.toString(),
filledGive: aFilledGive.toString(),
lastFill: this.umid,
done: aDone,
};
if (!this.matchStateB.orders) this.matchStateB.orders = {};
const bFilledGive = this.matchPriorB.filledGive.add(this.matchFillB);
const bFilledWant = this.matchPriorB.filledWant.add(this.matchFillA);
const bDone = !bFilledWant.lt(this.matchWantB.amount);
this.matchStateB.orders[this.matchHashB] = {
...(this.matchApprovedB ? { approved: this.matchApprovedB } : {}),
filledWant: bFilledWant.toString(),
filledGive: bFilledGive.toString(),
lastFill: this.umid,
done: bDone,
};
// A done approved order returns what is left in its hold to balance: for
// the incoming B side that is the price improvement it did not spend.
if (this.matchApprovedA && aDone) this.releaseHold(this.matchStateA, this.matchHashA);
if (this.matchApprovedB && bDone) this.releaseHold(this.matchStateB, this.matchHashB);
// Increment each governed party's per-asset spend counter for its give-leg
// (A gives matchFillA of matchGiveA; B gives matchFillB of matchGiveB), onto
// its own state so it rides the setState below (unified-keys Task 4).
// Not for an approved order: its whole maximum was counted at approval.
if (!this.matchApprovedA) {
this.bumpSwapUsage(this.matchStateA, this.matchKeyHashA, this.matchGiveA.network, this.matchGiveA.token, this.matchFillA);
}
if (!this.matchApprovedB) {
this.bumpSwapUsage(this.matchStateB, this.matchKeyHashB, this.matchGiveB.network, this.matchGiveB.token, this.matchFillB);
}
this.matchA.setState(this.matchStateA);
this.matchB.setState(this.matchStateB);
// Emit the SAME event a fill/swap emits, so a match shows as an Exchange and
// fires swap-settled: party A is the "maker", party B the "taker". Carries
// THIS match's actual moved amounts (fillA/fillB) + partial provenance: the
// match is partial unless BOTH orders are now fully filled, and remainingWant
// is party A's (the resting maker's) open want.
const partial = !(aDone && bDone);
this.event.emit("l2-swap", {
umid: this.umid,
// Settlement-lineage provenance: a matcher-settled match — both consume
// markers (the two resting-order hashes) and the neutral node that relayed it.
entry: "match",
orderHashes: { a: this.matchHashA, b: this.matchHashB },
submitter: this.matchSubmitter,
partial,
remainingWant: this.matchWantA.amount.sub(aFilledWant).toString(),
// Per-order fill state for the off-ledger matcher's book (not shown to the
// scanner): each order's cumulative filledWant and whether it is now done,
// so every gateway keeps its book current from this event alone.
bookUpdate: {
a: { orderHash: this.matchHashA, filledWant: aFilledWant.toString(), done: aDone },
b: { orderHash: this.matchHashB, filledWant: bFilledWant.toString(), done: bDone },
},
maker: this.matchOrderA.maker,
taker: this.matchOrderB.maker,
makerGive: {
network: this.matchGiveA.network,
token: this.matchGiveA.token,
amount: this.matchFillA.toString(),
},
takerGive: {
network: this.matchGiveB.network,
token: this.matchGiveB.token,
amount: this.matchFillB.toString(),
},
when: this.cDate,
});
this.returnToRemote([
{ id: this.matchA.getId(), partitions: this.matchStateA.layer2 },
{ id: this.matchB.getId(), partitions: this.matchStateB.layer2 },
]);
return true;
}/** * Domain separation (Low-1): an order's signed `domain` must name THIS * deployment — the namespace this transaction runs in and this Swap contract's * own id. `$contract` is the routing reference "<id>@<version>", so the bare id * is its leading 64 chars (the same trick other Varnir contracts use to read * their own id), matching the SDK's domain.contract. Rejecting a mismatch stops * a maker signature being replayed against another namespace or a different Swap * contract deployment. The domain is inside the signed bytes, so it cannot be * altered without breaking verifyOrderSig — this check binds it to reality. */
private verifyOrderDomain(order: any): boolean {
if (!order || !order.domain) return false;
const contractId = ("" + this.transactions.$contract).substring(0, 64);
return (
order.domain.namespace === this.transactions.$namespace &&
order.domain.contract === contractId
);
}/** * Verify a signed order against its signer's stream authorities, returning the * VERIFYING authority's key HASH so the caller can govern that order signer's * give-leg (unified-keys Task 4) — a resting-order signer does not tx-sign, so * this returned hash is its only governing-key handle. Only secp256k1 * authorities that are NOT read-only (label "read", or the stake-9000 * fail-safe for unlabeled legacy authorities) may authorise an order — a * read-only key must never be able to sign a trade. KeyPair.verify * JSON.stringifies the order internally, matching how the SDK signed it. First * key that verifies wins. Shared by fill (the maker's order) and match (both * parties' orders), so there is one implementation. * * Returns null when NO authority verifies (the caller reverts the order). The * accepted-type allow-list and every signature check are UNCHANGED — only the * return type changed. A signature that verifies against an authority carrying * no `hash` (only legacy / test-stub authorities — production authorities * always carry one) returns ORDER_SIGNER_UNRESOLVED so the caller's validity * gate still passes exactly as before while that give-leg stays ungoverned. */
private verifyOrderSig(activity: any, order: any, sig: any): string | null {
const authorities = activity.getAuthorities();
for (let i = 0; i < authorities.length; i++) {
const auth = authorities[i];
// Verify with the authority's OWN scheme via KeyPair(auth.type, ...). Accept
// only Varnir's three identity schemes — secp256k1 and the post-quantum
// falcon-512 / ml-dsa-65 (Activeledger 4.7 verifies all three in-contract).
// This used to be secp256k1-only, so a post-quantum maker's order signature
// never verified and fills/matches reverted — the exchange was unusable for
// PQ identities (now the onboarding default). Any other type (e.g. rsa) is
// NOT tried, so an unexpected key can never authorise a trade.
if (auth.type !== "secp256k1" && auth.type !== "falcon-512" && auth.type !== "ml-dsa-65") continue;
if ((auth.label ? String(auth.label).toLowerCase().trim() : null) === "read" || auth.stake >= READONLY_STAKE) continue;
try {
if (new this.ActiveCrypto.KeyPair(auth.type, auth.public).verify(order, sig)) {
// Surface the verifying key's hash as the order signer's governing key
// (Task 4); a hashless legacy/stub authority yields the ungoverned
// sentinel so the caller's validity gate is unchanged.
return typeof auth.hash === "string" && auth.hash.length
? auth.hash
: ORDER_SIGNER_UNRESOLVED;
}
} catch (_e) {
// A key that cannot verify this signature is simply not the signer.
}
}
return null;
}/**
* Read an order's consume marker into cumulative fill progress, tolerating
* every shape a marker can have — this is what makes partial fills backward
* compatible with markers already in ledger state:
* - undefined -> untouched (0 filled, not terminal)
* - { cancelled: true } -> terminal
* - { filled: umid } (LEGACY full fill, pre-partial, no accumulator fields)
* -> terminal
* - { filledWant, filledGive, done } -> partial accumulator; terminal iff done
* `terminal` means no further fill is allowed. Amounts are the cumulative want
* and give filled SO FAR (0 for legacy/cancelled — they carry no remainder to
* fill anyway, being terminal).
*/ private readMarker(marker: any): { filledWant: BN; filledGive: BN; terminal: boolean }/** `cancel` vote: refuses a missing maker or `orderHash`, and a read-only maker key. */
private async voteCancel(): Promise<boolean> {
const makerInput = this.transactions.$i ? this.transactions.$i.maker : undefined;
if (!makerInput || !makerInput.$stream) {
throw "Cancel needs a maker input";
}
if (!makerInput.orderHash) {
throw "Cancel is missing the orderHash";
}
this.orderMaker = this.getActivityStreams(makerInput);
if (this.isReadOnlyKey(this.orderMaker)) {
throw "Maker key is read-only and cannot cancel";
}
this.orderMakerState = this.orderMaker.getState();
this.orderHash = String(makerInput.orderHash);
return true;
}/** * `cancel` commit: marks the order `cancelled` on the maker's state, * keeping any partial-fill progress (and an approval); a terminal marker is * left as it is. What is left in an approved order's hold returns to * balance and `swap-order-released` is emitted. Returns the maker's * `layer2`. */
private async commitCancel(): Promise<any> {
if (!this.orderMakerState.orders) this.orderMakerState.orders = {};
const existing = this.orderMakerState.orders[this.orderHash];
const marker = this.readMarker(existing);
// A cancel must never overwrite a TERMINAL marker — a completed fill (legacy
// or done), or an already-cancelled order. But a PARTIALLY-filled order can
// still be cancelled: flag it cancelled while preserving how much already
// filled, so the filled portion stays on record and the remainder becomes
// unfillable. (An untouched order simply becomes a bare cancelled marker.)
if (!marker.terminal) {
this.orderMakerState.orders[this.orderHash] = {
...(existing ?? {}),
cancelled: true,
};
}
// An approved order's hold goes back to balance in the same commit: the
// remainder is the identity's own money, and cancelling only reduces risk,
// so any key that may cancel may release it (spec 5.7).
const hold = this.releaseHold(this.orderMakerState, this.orderHash);
this.orderMaker.setState(this.orderMakerState);
if (hold) this.emitReleased(this.orderMaker.getId(), this.orderHash, hold, "cancel");
this.returnToRemote([
{ id: this.orderMaker.getId(), partitions: this.orderMakerState.layer2 },
]);
return true;
}/** * `proposeOrder` vote. The order is validated as `fill` validates a resting * order (it names the proposing identity, positive legs, a live expiry, a * signature for this deployment) and, in addition, the order signature must * verify against the SAME key that signs this transaction: the proposal * records that key as `proposedBy`, and an approval must never sit on a * signature its proposer did not make. Refuses: a missing maker, order or * signature; an order naming another identity; non-positive or malformed * legs; an expired order, or one expiring more than MAXAPPROVEDORDERMS * after cDate; a read-only, off-ledger or verifier key; an invalid order * signature, one by another key, or one for another deployment; an AFX * identity; a give over the proposing key's `perTxMax` or outside its asset * allowlist (on the WHOLE give.amount); an order already filled, cancelled * or approved; an order that already has an unexpired proposal; and a * proposal past MAXLIVEORDERPROPOSALS / MAXLIVEORDERPROPOSALSPERKEY. A * recovered or frozen identity was refused at the top of vote(). * * Deliberately not checked here: the balance (5.5 - funds are held at * approval, so a draft cannot freeze them), `periodCap` (judged at approval * on the full give.amount, 5.9 item 6) and `coSignOver` / `requiresTreasury` * (those thresholds are what the approval satisfies). */
private async voteProposeOrder(): Promise<boolean> {
const makerInput = this.transactions.$i ? this.transactions.$i.maker : undefined;
if (!makerInput || !makerInput.$stream) {
throw "Order proposal needs a maker input";
}
const order = makerInput.order;
const sig = makerInput.sig;
if (!order || !sig) {
throw "Order proposal is missing the signed order or signature";
}
if (order.maker !== makerInput.$stream) {
throw "Order maker does not match the proposing identity";
}
this.orderGive = this.parseAsset(order.give, "Order give");
this.orderWant = this.parseAsset(order.want, "Order want");
if (!this.orderGive.amount.gt(0)) throw "Order give amount must be greater than 0";
if (!this.orderWant.amount.gt(0)) throw "Order want amount must be greater than 0";
// Consensus clock ONLY: new Date(this.cDate) reads the per-transaction
// timestamp every node shares. A missing cDate gives NaN, and both
// comparisons below then fail closed identically on every node.
const nowMs = new Date(this.cDate).getTime();
const expire = Number(order.expire);
if (!(expire > nowMs)) {
throw "Order has expired";
}
if (!(expire - nowMs <= MAXAPPROVEDORDERMS)) {
throw "Order expires more than 7 days from now; an approved order may stand for at most 7 days";
}
this.orderMaker = this.getActivityStreams(makerInput);
if (this.isReadOnlyKey(this.orderMaker)) {
throw "Maker key is read-only and cannot propose orders";
}
// The proposing key: the one that signed THIS transaction.
const proposerKey = this.swapSigningKeyHash(this.orderMaker);
const proposerLabel = this.swapSigningKeyLabel(this.orderMaker);
if (proposerLabel === "offledger") {
throw "Off-ledger key: no fund authority";
}
// A verify-only key has the stake to approve but may not initiate, as on
// a transfer ("A verifier key cannot raise transfers") and on a swap.
if (proposerLabel === "verifier") {
throw "Maker: a verifier key cannot raise orders";
}
const signedBy = this.verifyOrderSig(this.orderMaker, order, sig);
if (signedBy === null) {
throw "Maker order signature invalid";
}
if (!proposerKey || signedBy !== proposerKey) {
throw "Order must be signed by the proposing key";
}
if (!this.verifyOrderDomain(order)) {
throw "Maker order not signed for this deployment (domain mismatch)";
}
this.orderMakerState = this.orderMaker.getState();
if (this.orderMakerState.afx) {
throw "Maker identity is AFX-protected; order proposals are not permitted for it";
}
// The stateless give-leg guards of 5.9, on the WHOLE order: the most it
// can ever give. perTxMax is checked again at approval.
const policy = this.orderMakerState.restrictions?.[proposerKey]?.policy ?? null;
if (policy) {
const rule = this.policyRule(policy, this.orderGive.network, this.orderGive.token);
if (policy.assetsAllowlisted && !rule) {
throw "POLICY_ASSET_DENIED";
}
if (rule && rule.perTxMax != null && this.orderGive.amount.gt(BN.from(rule.perTxMax))) {
throw "POLICY_PER_TX_EXCEEDED";
}
}
// The order must still be open. The hash is the marker key fill, match
// and cancel already use, so a proposal names the same order they do.
this.orderHash = this.ActiveCrypto.Hash.getHash(JSON.stringify(order), "sha256");
const existing = this.orderMakerState.orders ? this.orderMakerState.orders[this.orderHash] : undefined;
if (this.readMarker(existing).terminal) {
throw "Order already filled or cancelled";
}
if (existing && existing.approved) {
throw "Order already approved";
}
// One live proposal per order. Two would ask approvers the same question
// twice, and approving both is what task 3's hold must never be asked to
// do. An expired summary (or one with no recorded expiry, which reads as
// expired, as in CryptoTransfer) does not block a fresh proposal.
// The same pass counts live proposals against MAXLIVEORDERPROPOSALS and
// MAXLIVEORDERPROPOSALSPERKEY.
const pending = this.orderMakerState.pendingOrderApprovals || {};
let liveTotal = 0;
let liveForKey = 0;
for (const id of Object.keys(pending)) {
const entry = pending[id];
if (!entry) continue;
const until = entry.expiresAt ? new Date(entry.expiresAt).getTime() : NaN;
if (Number.isNaN(until) || !(nowMs < until)) continue;
if (entry.orderHash === this.orderHash) {
throw "Order already has an open proposal";
}
liveTotal++;
if (entry.proposedBy === proposerKey) liveForKey++;
}
if (liveTotal >= MAXLIVEORDERPROPOSALS) {
throw "Too many open order proposals on this identity; void some or let them expire";
}
if (liveForKey >= MAXLIVEORDERPROPOSALSPERKEY) {
throw "Too many open order proposals from this key; void some or let them expire";
}
this.orderObj = order;
this.proposalSig = sig;
this.proposalKeyHash = proposerKey;
return true;
}/** * `proposeOrder` commit. Writes the proposal stream (`swap.order-proposal`), * which is the authority on the terms: the signed order and its signature, * the order hash, the identity, `proposedBy` (the proposing key's hash), * `at` and `expiresAt` (cDate + PROPOSALLIFETIMEMS, ISO-8601), and an empty * `confirmations` map so a quorum can be added later without changing the * record. It carries no `request` and no `requiresTreasury`, the fields * CryptoTransfer's confirm and void key on. Adds a summary to the * identity's `pendingOrderApprovals`, so an approver finds it by reading * the identity it already reads, emits `swap-order-pending` for push * notifications, and returns the proposal id. Moves no money. */
private async commitProposeOrder(): Promise<any> {
const expiresAt = new Date(new Date(this.cDate).getTime() + PROPOSALLIFETIMEMS).toISOString();
const give = {
network: this.orderGive.network,
token: this.orderGive.token,
amount: this.orderGive.amount.toString(),
};
const want = {
network: this.orderWant.network,
token: this.orderWant.token,
amount: this.orderWant.amount.toString(),
};
const identity = this.orderMaker.getId();
const expire = Number(this.orderObj.expire);
const proposal = this.newActivityStream(ORDERPROPOSALSTREAM);
proposal.setState({
kind: ORDERPROPOSALKIND,
umid: this.umid,
order: this.orderObj,
sig: this.proposalSig,
orderHash: this.orderHash,
identity,
proposedBy: this.proposalKeyHash,
at: this.cDate,
expiresAt,
confirmations: {},
});
const proposalId = proposal.getId();
if (!this.orderMakerState.pendingOrderApprovals) {
this.orderMakerState.pendingOrderApprovals = {};
}
// Prune summaries that can no longer be approved (expired, or with no
// recorded expiry, which reads as expired), so the list stays the size
// of what is outstanding. The proposal streams themselves are kept: they
// are the record, and a void still works on them.
const pending = this.orderMakerState.pendingOrderApprovals;
const nowMs = new Date(this.cDate).getTime();
for (const id of Object.keys(pending)) {
const until = pending[id] && pending[id].expiresAt ? new Date(pending[id].expiresAt).getTime() : NaN;
if (Number.isNaN(until) || !(nowMs < until)) {
delete pending[id];
}
}
pending[proposalId] = {
proposedBy: this.proposalKeyHash,
orderHash: this.orderHash,
give,
want,
expire,
at: this.cDate,
expiresAt,
};
this.orderMaker.setState(this.orderMakerState);
this.event.emit("swap-order-pending", {
identity,
proposal: proposalId,
orderHash: this.orderHash,
umid: this.umid,
give,
want,
expire,
proposedBy: this.proposalKeyHash,
expiresAt,
});
this.returnToRemote({ proposal: proposalId, orderHash: this.orderHash, expiresAt });
return true;
}/** * `voidOrder` vote: retire an unapproved order proposal, as CryptoTransfer's * voteVoid retires a transfer proposal. The proposal is named on * `$o.proposal`, which is caller-controlled, so the stream must prove it is * an order proposal (`kind`) for THIS identity. Allowed for the key that * raised it, or any key with stake 80 or more (the owner included); not * gated on expiry, because an expired proposal is the one most in need of * clearing. Refuses: a missing maker or `$o.proposal`; a read-only or * off-ledger key; a stream that is not an order proposal; another * identity's proposal; an approved proposal (cancel the order instead, * task 3); a voided one; and any other key. */
private async voteVoidOrder(): Promise<boolean> {
const makerInput = this.transactions.$i ? this.transactions.$i.maker : undefined;
if (!makerInput || !makerInput.$stream) {
throw "Void needs a maker input";
}
this.orderMaker = this.getActivityStreams(makerInput);
if (this.isReadOnlyKey(this.orderMaker)) {
throw "Maker key is read-only and cannot void";
}
if (this.swapSigningKeyLabel(this.orderMaker) === "offledger") {
throw "Off-ledger key: no fund authority";
}
const reference = this.transactions.$o ? this.transactions.$o.proposal : undefined;
if (!reference) {
throw "Missing proposal to void";
}
this.proposalStream = this.getActivityStreams(reference);
const proposalData = this.proposalStream && this.proposalStream.getState();
if (!proposalData || proposalData.kind !== ORDERPROPOSALKIND) {
throw "Not an order proposal";
}
if (proposalData.identity !== this.orderMaker.getId()) {
throw "Proposal Mismatched";
}
if (proposalData.approved) {
throw "Approved Already";
}
if (proposalData.voided) {
throw "Voided Already";
}
const voidingKey = this.swapSigningKeyHash(this.orderMaker);
const mayVoid =
this.hasAuthorityStake(80, this.orderMaker) ||
(!!proposalData.proposedBy && !!voidingKey && proposalData.proposedBy === voidingKey);
if (!mayVoid) {
throw "No authority to void this proposal";
}
return true;
}/** * `voidOrder` commit. Stamps `voided` / `voidedAt` / `voidedBy` (the KEY, * as `proposedBy` is) on the proposal, which is terminal, drops the * identity's summary, emits `swap-order-voided` and returns the proposal * id. Moves no money and writes no balance. */
private async commitVoidOrder(): Promise<any> {
const proposalData = this.proposalStream.getState();
const voidedBy = this.swapSigningKeyHash(this.orderMaker);
this.proposalStream.setState({
...proposalData,
voided: this.umid,
voidedAt: this.cDate,
voidedBy,
});
const proposalId = this.proposalStream.getId();
const makerState = this.orderMaker.getState();
if (makerState.pendingOrderApprovals) {
delete makerState.pendingOrderApprovals[proposalId];
this.orderMaker.setState(makerState);
}
this.event.emit("swap-order-voided", {
identity: this.orderMaker.getId(),
proposal: proposalId,
orderHash: proposalData.orderHash,
umid: this.umid,
voidedBy,
when: this.cDate,
});
this.returnToRemote({ voided: proposalId, umid: this.umid, when: this.cDate });
return true;
}/** * The policy rule for one asset, matching `<network>:<token>` case- * insensitively, as assertSwapAllowed and bumpSwapUsage match it. Null when * the policy has no rule for the asset. */
private policyRule(policy: any, network: string, token: string): any {
const rules = policy.rules || {};
for (const ruleKey of Object.keys(rules)) {
const sep = ruleKey.indexOf(":");
if (
ruleKey.slice(0, sep).toLowerCase() === String(network).toLowerCase() &&
ruleKey.slice(sep + 1).toLowerCase() === String(token || NATIVE).toLowerCase()
) {
return rules[ruleKey];
}
}
return null;
}/** * `approveOrder` vote. The approval is the ONE key that signs this * transaction: a transaction signed by more than one key on the identity * is refused, so no co-signature (the proposer's included) can be summed * into an approval - swapSigningKeyHash would read only the first key and * hasAuthorityStake would add them all, and neither may decide alone. * That key must be a live authority on the identity, not read-only, not * off-ledger, stake 80 or more on its own, and not the proposer. * * The proposal must be a `swap-order` stream for this identity that is * still listed in its `pendingOrderApprovals` (only proposeOrder writes * that, so a stream written elsewhere cannot pose as one), neither * approved nor voided, and approved before min(expiresAt, order.expire) * on the consensus clock. The stored order must hash to the stored * orderHash, name this identity, be for this deployment, and its signature * must still verify against `proposedBy`, which must still be a live * authority. The order must be untouched: not approved or held already (no * double hold), not filled, cancelled or partly filled. Against the * proposer's current policy, on the WHOLE give.amount: AFX, off-ledger, * the asset allowlist, `perTxMax` and `periodCap` (refused up front if the * full maximum would exceed it; spec section 11). Finally the balance must * cover give.amount. */
private async voteApproveOrder(): Promise<boolean> {
const makerInput = this.transactions.$i ? this.transactions.$i.maker : undefined;
if (!makerInput || !makerInput.$stream) {
throw "Approval needs a maker input";
}
this.orderMaker = this.getActivityStreams(makerInput);
const identity = this.orderMaker.getId();
const signers = Object.keys(((this as any).sigs && (this as any).sigs[identity]) || {});
if (signers.length !== 1) {
throw "Approval must be signed by exactly one key";
}
if (this.isReadOnlyKey(this.orderMaker)) {
throw "Approver key is read-only and cannot approve";
}
if (this.swapSigningKeyLabel(this.orderMaker) === "offledger") {
throw "Off-ledger key: no fund authority";
}
const approverKey = signers[0];
const approver = this.orderMaker.getAuthorities().find((candidate: any) => candidate.hash === approverKey);
if (!approver) {
throw "Approver key is not an authority on this identity";
}
if (!this.liveAuthority(this.orderMaker, approverKey)) {
throw "Approver key has expired";
}
const reference = this.transactions.$o ? this.transactions.$o.proposal : undefined;
if (!reference) {
throw "Missing proposal to approve";
}
this.proposalStream = this.getActivityStreams(reference);
const proposalData = this.proposalStream && this.proposalStream.getState();
if (!proposalData || proposalData.kind !== ORDERPROPOSALKIND) {
throw "Not an order proposal";
}
if (proposalData.identity !== identity) {
throw "Proposal Mismatched";
}
if (proposalData.approved) {
throw "Approved Already";
}
if (proposalData.voided) {
throw "Proposal Voided";
}
this.orderMakerState = this.orderMaker.getState();
const proposalId = this.proposalStream.getId();
const pending = this.orderMakerState.pendingOrderApprovals
? this.orderMakerState.pendingOrderApprovals[proposalId]
: undefined;
if (!pending || pending.orderHash !== proposalData.orderHash) {
throw "Proposal is not pending on this identity";
}
// Separation of duties: the proposer can never be its own approver.
const proposedBy = proposalData.proposedBy;
if (!proposedBy || approverKey === proposedBy) {
throw "Cannot verify your own proposal";
}
if (!(Number(approver.stake) >= 80)) {
throw "Approving needs a key with stake 80 or more";
}
// Consensus clock only. A proposal with no recorded expiry reads as
// expired, as in CryptoTransfer.
const nowMs = new Date(this.cDate).getTime();
const proposalExpiresAt = proposalData.expiresAt ? new Date(proposalData.expiresAt).getTime() : NaN;
if (Number.isNaN(proposalExpiresAt) || !(nowMs < proposalExpiresAt)) {
throw "Proposal Expired";
}
const order = proposalData.order;
if (!order || !(Number(order.expire) > nowMs)) {
throw "Order has expired";
}
// The approver signs over what is STORED, so the stored terms must be the
// ones proposeOrder checked.
this.orderHash = this.ActiveCrypto.Hash.getHash(JSON.stringify(order), "sha256");
if (this.orderHash !== proposalData.orderHash) {
throw "Stored order does not match its hash";
}
if (order.maker !== identity) {
throw "Order maker does not match the proposing identity";
}
this.orderGive = this.parseAsset(order.give, "Order give");
this.orderWant = this.parseAsset(order.want, "Order want");
if (!this.orderGive.amount.gt(0)) throw "Order give amount must be greater than 0";
if (!this.orderWant.amount.gt(0)) throw "Order want amount must be greater than 0";
if (!this.verifyOrderDomain(order)) {
throw "Maker order not signed for this deployment (domain mismatch)";
}
const proposer = this.liveAuthority(this.orderMaker, proposedBy);
if (!proposer || this.verifyOrderSig(this.orderMaker, order, proposalData.sig) !== proposedBy) {
throw "Order signature no longer verifies against the proposing key";
}
if (this.orderMakerState.afx) {
throw "Maker identity is AFX-protected; order approvals are not permitted for it";
}
if ((proposer.label ? String(proposer.label).toLowerCase().trim() : null) === "offledger") {
throw "Off-ledger key: no fund authority";
}
const existing = this.orderMakerState.orders ? this.orderMakerState.orders[this.orderHash] : undefined;
if ((existing && existing.approved) || (this.orderMakerState.orderHold && this.orderMakerState.orderHold[this.orderHash])) {
throw "Order already approved";
}
const marker = this.readMarker(existing);
if (marker.terminal) {
throw "Order already filled or cancelled";
}
if (marker.filledWant.gt(0) || marker.filledGive.gt(0)) {
throw "Order already partly filled; propose a new order";
}
// The proposer's policy on the whole maximum (5.9 item 6).
const policy = this.orderMakerState.restrictions?.[proposedBy]?.policy ?? null;
if (policy) {
const rule = this.policyRule(policy, this.orderGive.network, this.orderGive.token);
if (policy.assetsAllowlisted && !rule) {
throw "POLICY_ASSET_DENIED";
}
if (rule && rule.perTxMax != null && this.orderGive.amount.gt(BN.from(rule.perTxMax))) {
throw "POLICY_PER_TX_EXCEEDED";
}
if (rule && rule.periodCap != null && rule.windowMs != null) {
// Same tumbling window as assertSwapAllowed, on the consensus clock.
const assetKey = `${String(this.orderGive.network).toLowerCase()}:${String(this.orderGive.token).toLowerCase()}`;
const usage = this.orderMakerState.agentUsage?.[proposedBy]?.[assetKey] ?? { windowStart: nowMs, spent: "0" };
let spent = BN.from(usage.spent);
if (nowMs - usage.windowStart >= Number(rule.windowMs)) {
spent = BN.from(0);
}
if (spent.add(this.orderGive.amount).gt(BN.from(rule.periodCap))) {
throw "POLICY_PERIOD_CAP_EXCEEDED";
}
}
}
// The verifier never approves an order that could not settle (5.5).
const balance = this.l2Get(this.orderMakerState, this.orderGive.network, this.orderGive.token);
if (balance.lt(this.orderGive.amount)) {
throw `Balance too low to approve: ${balance} < ${this.orderGive.amount}`;
}
this.orderObj = order;
this.approverKeyHash = approverKey;
this.proposerUmid = proposer.umid ?? null;
this.proposalKeyHash = proposedBy;
return true;
}/**
* `approveOrder` commit, on the identity's own stream in one write: the
* balance drops by give.amount and `orderHold[hash]` holds it (with the
* order's expiry, the proposal and `proposedBy`, which release reads);
* `orders[hash]` gets `approved: {proposal, umid, by, at, proposedBy}`; the
* proposer's period counter is bumped by the whole give.amount (fills
* never bump it again, and nothing released later credits it back); the
* summary leaves `pendingOrderApprovals`. The proposal is stamped
* `approved` / `approvedAt` / `approvedBy` with the approving key in
* `confirmations`, and `swap-order-approved` is emitted so the gateways
* can put the order on the book.
*/ private async commitApproveOrder(): Promise<any> {
const give = {
network: this.orderGive.network,
token: this.orderGive.token,
amount: this.orderGive.amount.toString(),
};
const want = {
network: this.orderWant.network,
token: this.orderWant.token,
amount: this.orderWant.amount.toString(),
};
const identity = this.orderMaker.getId();
const proposalId = this.proposalStream.getId();
const expire = Number(this.orderObj.expire);
const state = this.orderMakerState;
const balance = this.l2Get(state, give.network, give.token);
this.l2Set(state, give.network, give.token, balance.sub(this.orderGive.amount));
if (!state.orderHold) state.orderHold = {};
state.orderHold[this.orderHash] = {
network: give.network,
token: give.token,
amount: give.amount,
expire,
proposal: proposalId,
proposedBy: this.proposalKeyHash,
proposerUmid: this.proposerUmid,
// The identity that signed the order. Recovery copies this hold to a
// new identity, where the order (maker = the old identity) can never
// fill; release reads this to let it go at once (voteRelease).
maker: identity,
};
if (!state.orders) state.orders = {};
state.orders[this.orderHash] = {
approved: {
proposal: proposalId,
umid: this.umid,
by: this.approverKeyHash,
at: this.cDate,
proposedBy: this.proposalKeyHash,
},
filledWant: "0",
filledGive: "0",
done: false,
};
this.bumpSwapUsage(state, this.proposalKeyHash, give.network, give.token, this.orderGive.amount);
if (state.pendingOrderApprovals) {
delete state.pendingOrderApprovals[proposalId];
}
this.orderMaker.setState(state);
const proposalData = this.proposalStream.getState();
this.proposalStream.setState({
...proposalData,
approved: this.umid,
approvedAt: this.cDate,
approvedBy: this.approverKeyHash,
confirmations: {
...(proposalData.confirmations || {}),
[this.approverKeyHash]: { umid: this.umid, at: this.cDate },
},
});
this.event.emit("swap-order-approved", {
identity,
proposal: proposalId,
orderHash: this.orderHash,
umid: this.umid,
approvedBy: this.approverKeyHash,
proposedBy: this.proposalKeyHash,
give,
want,
expire,
});
this.returnToRemote({ approved: proposalId, orderHash: this.orderHash, held: give, umid: this.umid });
return true;
}/** * `release` vote. Anyone may submit it (like match): it can only ever * credit `$o.owner`'s own balance with its own held funds. Allowed once the * held order can no longer settle - its marker is terminal, `order.expire` * has passed on the consensus clock, the hold was inherited through social * recovery (`recoveredFrom` set and the hold's maker is another identity, * so the order can never settle here), or its proposing key is no longer * the live authority that was approved (removed, expired, or removed and * re-added), which also stops every fill. * Refuses: a missing submitter, owner or orderHash; no hold for the order; * and an order that is still live (its owner can cancel it). A recovered * or frozen owner was refused at the top of vote(): recovery copies the old * state, hold included, to the new identity, so a release on the * tombstone would pay the same funds twice. */
private async voteRelease(): Promise<boolean> {
const submitter = this.transactions.$i ? this.transactions.$i.submitter : undefined;
if (!submitter || !submitter.$stream) {
throw "Release needs a submitter ($i.submitter)";
}
const ownerOut = this.transactions.$o ? this.transactions.$o.owner : undefined;
if (!ownerOut || !ownerOut.$stream || !ownerOut.orderHash) {
throw "Release needs the owner and the orderHash ($o.owner)";
}
this.releaseOwner = this.getActivityStreams(ownerOut);
this.orderMakerState = this.releaseOwner.getState();
this.orderHash = String(ownerOut.orderHash);
const hold = this.orderMakerState.orderHold ? this.orderMakerState.orderHold[this.orderHash] : undefined;
if (!hold) {
throw "No hold for this order";
}
const nowMs = new Date(this.cDate).getTime();
const marker = this.readMarker(this.orderMakerState.orders ? this.orderMakerState.orders[this.orderHash] : undefined);
if (marker.terminal) {
this.releaseReason = "closed";
} else if (!(Number(hold.expire) > nowMs)) {
this.releaseReason = "expired";
} else if (this.orderMakerState.recoveredFrom && hold.maker !== this.releaseOwner.getId()) {
// Inherited through social recovery: the order names the old identity
// as maker, so it can never settle here.
this.releaseReason = "recovered";
} else if (!this.holdProposerLive(this.releaseOwner, hold)) {
this.releaseReason = "key-removed";
} else {
throw "Order is still live; only its owner can cancel it";
}
return true;
}/** `release` commit: the hold back to the owner's balance; emits `swap-order-released`. */
private async commitRelease(): Promise<any> {
const hold = this.releaseHold(this.orderMakerState, this.orderHash);
this.releaseOwner.setState(this.orderMakerState);
if (hold) this.emitReleased(this.releaseOwner.getId(), this.orderHash, hold, this.releaseReason);
this.returnToRemote([
{ id: this.releaseOwner.getId(), partitions: this.orderMakerState.layer2 },
]);
return true;
}/** The `approved` record on an order's marker, or null when it has none. */
private approvedRecord(state: any, orderHash: string): any {
const marker = state && state.orders ? state.orders[orderHash] : undefined;
return marker && marker.approved ? marker.approved : null;
}/** * Move what is left in an order's hold back to its owner's balance and drop * the hold. Returns what moved, or null when there was no hold. */
private releaseHold(state: any, orderHash: string): { network: string; token: string; amount: string }/** * Exactly one key signed for `activity` in this transaction, and it is a live owner key (liveAuthority, stake exactly * 100, not labelled read, offledger or verifier). hasAuthorityStake(100) SUMS every signer's stake * (docs/tenancy/legacy-read-key-audit.md). Reads only this.sigs and the authorities already loaded. */
private isSingleOwnerKey(activity: any): boolean {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
const a = hashes.length === 1 ? this.liveAuthority(activity, hashes[0]) : null;
const label = a && a.label ? String(a.label).toLowerCase().trim() : null;
return !!a && a.stake === 100 && label !== "read" && label !== "offledger" && label !== "verifier";
}/** * The authority with `hash` on `activity` if it is still live: present, and * either permanent (no `expire` field) or with an `expire` after the * consensus clock. As the engine's isAuthorityExpired: expire <= the * transaction time is expired, and so is `expire: null` (read as the epoch) * or an unparseable value. Null otherwise. */
private liveAuthority(activity: any, hash: string | null): any {
if (!hash) return null;
const authority = activity.getAuthorities().find((candidate: any) => candidate.hash === hash);
if (!authority) return null;
if (authority.expire !== undefined) {
const expireAt = new Date(authority.expire).getTime();
if (Number.isNaN(expireAt) || !(expireAt > new Date(this.cDate).getTime())) return null;
}
return authority;
}/** * The hold's proposing authority if it is still the SAME live authority * that was approved: liveAuthority, and the engine's add stamp (`umid`) * unchanged since approval. A key removed and re-added has the same hash * but a new umid, and must not revive the orders approved under it. */
private holdProposerLive(activity: any, hold: any): any {
const authority = this.liveAuthority(activity, hold.proposedBy);
if (!authority) return null;
if ((authority.umid ?? null) !== (hold.proposerUmid ?? null)) return null;
return authority;
}/** Normalise and validate one input leg. */
private readLeg(input: any, label: string): SwapLeg {
if (!input.$stream) throw `Swap ${label} is missing $stream`;
if (input.network === undefined || input.network === null || input.network === "") {
throw `Swap ${label} is missing network`;
}
if (input.amount === undefined || input.amount === null) {
throw `Swap ${label} is missing amount`;
}
// Amount must be a plain decimal integer in smallest units. Reject hex
// ("0x.."), scientific ("1e3"), decimals ("1.5"), signs, blanks and
// whitespace explicitly — BigInt would silently accept some of these and
// move a wildly different value that both parties unwittingly signed.
const rawAmount = String(input.amount);
if (!/^[0-9]+$/.test(rawAmount)) {
throw `Swap ${label} amount must be a decimal integer in smallest units`;
}
// Partition keys are used EXACTLY as sent. The L2 balance map is keyed by
// the ledger network code in its OWN case (e.g. "TRX-NILE", "SEP") and by
// the normalised token contract address — the same raw keys the transfer
// contract uses. Lower-casing here would look up "trx-nile" and miss a
// balance stored under "TRX-NILE" (a real bug caught in the e2e). Clients
// (the SDK) are responsible for sending canonical keys.
const network = String(input.network);
const token =
input.token !== undefined && input.token !== null && input.token !== ""
? String(input.token)
: NATIVE;
return {
stream: input.$stream,
network,
token,
amount: BN.from(rawAmount),
};
}/** * Validate one asset leg of a signed order (give/want). Same amount and * partition-key rules as readLeg, but with no $stream — an order carries the * assets, and the streams come from $o.maker / $i.taker. */
private parseAsset(leg: any, label: string): { network: string; token: string; amount: BN }/** * Does a non-owner key's give-leg need treasury approval, per the identity's * own threshold? Mirrors Varnir.CryptoTransfer.overTreasuryThreshold for the * give-leg's asset: `requiresTreasury` is a single raw minimum or an object * keyed `<network>.<token>`; "-1" means never and "0" means everything. An * identity with no threshold for the asset fails closed (everything), as the * transfer contract does. */
private overTreasuryThreshold(state: any, network: string, token: string, amount: BN): boolean {
let treasuryMinValue: any = "0";
if (typeof state.requiresTreasury === "string") {
treasuryMinValue = state.requiresTreasury;
} else {
treasuryMinValue = state.requiresTreasury?.[`${network}.${token}`] ?? 0;
}
if (treasuryMinValue === "-1") {
return false;
}
const treasuryMin = BN.from(treasuryMinValue);
return treasuryMin.lt(amount) || treasuryMin.eq(0);
}/** * The hash of the key that signed THIS TRANSACTION for `activity`, resolved * exactly as Varnir.CryptoTransfer does: this.sigs is keyed by stream id, one * signature per input. Used for the LIVE tx signers (both co-sign swap * parties, a fill's taker). Returns null when the party did not tx-sign (e.g. * a resting-order maker carried in $o — governed instead via its order * signer, verifyOrderSig — or an unsigned stub), leaving it ungoverned by the * give-leg policy if no order-signer hash is supplied either. */
private swapSigningKeyHash(activity: any): string | null {
const currentAuth = (this as any).sigs?.[activity.getId()];
if (!currentAuth) {
return null;
}
const keys = Object.keys(currentAuth);
return keys.length ? keys[0] : null;
}/** * The label on the authority that tx-signed for `activity` - "read" or null * if it cannot be matched. Mirrors Varnir.CryptoTransfer.signingKeyLabel: * stake alone cannot be trusted to carry role going forward (stake is now * consensus weight only), so the label is the primary signal. The * stake-9000 check (READONLY_STAKE) stays as a fail-safe alongside this for * legacy authorities that predate labels. */
private swapSigningKeyLabel(activity: any): string | null {
const hash = this.swapSigningKeyHash(activity);
if (!hash) {
return null;
}
const authority = activity
.getAuthorities()
.find((candidate: any) => candidate.hash === hash);
const label = authority?.label;
return label ? String(label).toLowerCase().trim() : null;
}/** * Whether the key that tx-signed for `activity` is a read-only * (customer-service tier) key, which may never move funds. This is the ONE * shape every read gate in this contract uses: label-first, with the * stake-9000 fail-safe (READONLY_STAKE) OR'd in for legacy authorities that * predate labels. Kept as a single method so the gates cannot drift apart. */
private isReadOnlyKey(activity: any): boolean {
return (
this.swapSigningKeyLabel(activity) === "read" ||
this.hasAuthorityStake(READONLY_STAKE, activity)
);
}/** Creates `layer2[network][token] = {balance: "0"}` when missing. */ private l2Ensure(state: any, network: string, token: string): void {
if (!state.layer2) state.layer2 = {};
if (!state.layer2[network]) state.layer2[network] = {};
if (!state.layer2[network][token]) state.layer2[network][token] = { balance: "0" };
}/** The balance at `layer2[network][token]` (created as 0 when missing). */
private l2Get(state: any, network: string, token: string): BN {
this.l2Ensure(state, network, token);
return BN.from(state.layer2[network][token].balance);
}/** Writes the balance at `layer2[network][token]` as a decimal string. */
private l2Set(state: any, network: string, token: string, value: BN): void {
this.l2Ensure(state, network, token);
state.layer2[network][token].balance = value.toString();
} public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>((resolve) => resolve(true));
}