Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/mesh-transaction/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,10 @@ Collateral inputs given as `collateral(...)` parts that do not cover the collate
the same way, after them: from the payer's UTxOs (never a given one again, and no more than
`maxCollateralInputs` in all), else from the answer of `getCollateral`. With the build option
`topUpCollateral: false` they are put up as given, and collateral they do not cover is
`INSUFFICIENT_COLLATERAL`.
`INSUFFICIENT_COLLATERAL`. A UTxO a `collateral(...)` part puts up stays selectable for payment:
when the payer's UTxOs hold it (a snapshot's `utxos`, a wallet's `getUtxos`), selection may spend
it as an input too, which the ledger allows. To keep it unspent, leave it out of the payer's UTxOs
or refuse it with `canSelect`; it is put up as collateral either way.

With the build option `collateralReturn: false` the transaction carries collateral inputs only,
neither a collateral return nor a total collateral: all of their lovelace is at stake if a script
Expand Down
6 changes: 0 additions & 6 deletions packages/mesh-transaction/src/mesh-tx-builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,12 +368,6 @@ export class MeshTxBuilder extends MeshTxBuilderCore {
[DECLARED_OUTPUTS]: {
unread: translated.unread,
scriptSizes: translated.scriptSizes,
// Selection may spend a collateral input too, as it always could here
selectableCollateral: new Set(
body.collaterals.map(
({ txIn }) => `${txIn.txHash.toLowerCase()}#${txIn.txIndex}`,
),
),
},
};
const built = await builder.build(translated.parts, options);
Expand Down
36 changes: 11 additions & 25 deletions packages/mesh-transaction/src/tx-builder/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export type BalanceContext = {
/** The payer's change address, where change and, by default, the collateral return go */
changeAddress: string;
/**
* UTxOs inputs and collateral may be selected from. Those the parts read are never selected,
* and those named by collateral parts are never selected as inputs.
* UTxOs inputs and collateral may be selected from. Those the parts read are never selected;
* one a collateral part puts up may be selected as an input as well.
*/
utxos: readonly Utxo[];
/** Out refs of the UTxOs selected neither as inputs nor as collateral: a filter refused them */
Expand All @@ -98,8 +98,6 @@ export type BalanceContext = {
sendAllTo?: string;
/** Every UTxO known to the build, keyed by `txHash#index` */
known: ReadonlyMap<string, Utxo>;
/** Out refs named by collateral parts that selection may still spend as inputs */
selectableCollateral?: ReadonlySet<string>;
/**
* Reference-script sizes stated for out refs whose UTxO the build does not know, keyed by
* `txHash#index`: counted for the fee where no known UTxO holds a script
Expand Down Expand Up @@ -241,14 +239,6 @@ const readByParts = (parts: readonly TxPart[]): Set<string> => {
return read;
};

/** The out refs a part names as collateral */
const putUpByParts = (parts: readonly TxPart[]): Set<string> =>
new Set(
parts.flatMap((p) =>
p.kind === "collateral" ? [outRefString(p.input)] : [],
),
);

/** Whether a UTxO is locked by a key: a key payment credential, or a Byron address */
export const isKeyLocked = (utxo: Utxo) => {
const address = Address.fromString(utxo.address);
Expand All @@ -271,23 +261,21 @@ const byOutRef = (a: Utxo, b: Utxo) =>
);

/**
* The payer's UTxOs selection may take for payment: key-locked, not spent, read or named as
* collateral by a part, and not refused by the filter; with the count of the others, each by
* its first reason
* The payer's UTxOs selection may take for payment: key-locked, not spent or read by a part, and
* not refused by the filter; with the count of the others, each by its first reason. One a
* collateral part puts up is taken as any other: the payer leaves it out, or the filter refuses
* it, to keep it unspent.
*/
export const paymentPool = (
parts: readonly TxPart[],
utxos: readonly Utxo[],
refused: ReadonlySet<string> = new Set(),
spentByAfter = 0,
selectableCollateral: ReadonlySet<string> = new Set(),
): { pool: Utxo[]; counts: InsufficientFundsDetails["pool"] } => {
const spent = new Set(
parts.flatMap((p) => (p.kind === "spend" ? [utxoKey(p.utxo!)] : [])),
);
const read = readByParts(parts);
const putUp = putUpByParts(parts);
for (const key of selectableCollateral) putUp.delete(key);
const pool: Utxo[] = [];
const counts: InsufficientFundsDetails["pool"] = {
// Those spent by `after` were given too, and are counted by that reason
Expand All @@ -300,8 +288,8 @@ export const paymentPool = (
};
for (const utxo of utxos) {
const key = utxoKey(utxo);
// Already in the transaction: only given
if (spent.has(key) || putUp.has(key)) continue;
// Already an input: only given
if (spent.has(key)) continue;
if (!isKeyLocked(utxo)) counts.scriptLocked++;
else if (read.has(key)) counts.readByParts++;
else if (refused.has(key)) counts.excludedByFilter++;
Expand Down Expand Up @@ -369,20 +357,19 @@ export const oversizedRoundOf = (error: unknown): OversizedRound | undefined =>

/**
* The out refs of the UTxOs a filter refuses, asking it once about each UTxO it could let be
* selected: key-locked, not read by a part and not named as collateral. What the filter throws
* is not caught.
* selected: key-locked and not read by a part, those collateral parts put up among them. What
* the filter throws is not caught.
*/
export const refusedBy = (
canSelect: (utxo: Utxo) => boolean,
parts: readonly TxPart[],
utxos: readonly Utxo[],
): Set<string> => {
const read = readByParts(parts);
const putUp = putUpByParts(parts);
const refused = new Set<string>();
for (const utxo of utxos) {
const key = utxoKey(utxo);
if (!isKeyLocked(utxo) || read.has(key) || putUp.has(key)) continue;
if (!isKeyLocked(utxo) || read.has(key)) continue;
if (!canSelect(utxo)) refused.add(key);
}
return refused;
Expand Down Expand Up @@ -766,7 +753,6 @@ export const balance = (
ctx.utxos,
refused,
ctx.spentByAfter,
ctx.selectableCollateral,
);
const selected: Utxo[] = [];
const selectedKeys = new Set<string>();
Expand Down
16 changes: 3 additions & 13 deletions packages/mesh-transaction/src/tx-builder/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,6 @@ export type DeclaredOutputs = {
* Reference-script sizes declared for out refs whose UTxO the build does not know, for the fee
*/
readonly scriptSizes: ReadonlyMap<string, number>;
/** Out refs named as collateral that selection may still spend, as the old builder's did */
readonly selectableCollateral: ReadonlySet<string>;
};

/** The key `DeclaredOutputs` travels under in the options of a build */
Expand Down Expand Up @@ -2784,13 +2782,8 @@ export class TxBuilder {
type: "payer",
changeAddress: payer.changeAddress,
utxos: payerUtxos.length,
selectable: paymentPool(
filled,
selectable,
refused || undefined,
0,
declared?.selectableCollateral,
).pool.length,
selectable: paymentPool(filled, selectable, refused || undefined).pool
.length,
});
if (fetched.length > 0) emit({ type: "fetched", outRefs: fetched });

Expand Down Expand Up @@ -2824,10 +2817,7 @@ export class TxBuilder {
...(coinSelection && { coinSelection }),
...(sendAllTo !== undefined && { sendAllTo }),
known,
...(declared && {
scriptSizes: declared.scriptSizes,
selectableCollateral: declared.selectableCollateral,
}),
...(declared && { scriptSizes: declared.scriptSizes }),
...(fee !== undefined && { fee }),
registeredPools: new Set(registeredPools ?? []),
extraKeyWitnesses: extraKeyWitnesses ?? 0,
Expand Down
45 changes: 37 additions & 8 deletions packages/mesh-transaction/test/tx-builder/builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -728,16 +728,17 @@ describe("TxBuilder: what INSUFFICIENT_FUNDS reports", () => {
],
utxos: [oracle, spent, putUp, plain, locked],
});
// The UTxO put up as collateral is selectable as any other
expect(short.pool).toEqual({
given: 5,
selectable: 1,
selectable: 2,
scriptLocked: 1,
excludedByFilter: 0,
readByParts: 1,
spentByAfter: 0,
});
// The spent UTxO counts as what the parts bring in
expect(short.available).toBe(ada(10));
expect(short.available).toBe(ada(15));
});

it("counts a fixed fee as it is, and no change the build does not need", async () => {
Expand Down Expand Up @@ -2058,13 +2059,20 @@ describe("TxBuilder: UTxOs left out of selection", () => {
(built.prototype.body.reference_inputs ?? []).map(
(i) => `${i.transaction_id}#${i.index}`,
);
const build = (parts: TxPart[], utxos: Utxo[]) =>
const build = (
parts: TxPart[],
utxos: Utxo[],
canSelect?: (utxo: Utxo) => boolean,
) =>
new TxBuilder({
network,
costModels,
params,
evaluator: fakeEvaluator().evaluator,
}).build(parts, { payer: { changeAddress: wallet, utxos } });
}).build(parts, {
payer: { changeAddress: wallet, utxos },
...(canSelect && { canSelect }),
});

it("does not spend a UTxO a reference input reads", async () => {
const plain = utxo(lovelace(ada(40)));
Expand Down Expand Up @@ -2140,17 +2148,38 @@ describe("TxBuilder: UTxOs left out of selection", () => {
}
});

it("does not spend a UTxO a collateral part puts up", async () => {
it("selects a UTxO a collateral part puts up as any other of the payer's", async () => {
const plain = utxo(lovelace(ada(40)));
const putUp = utxo(lovelace(ada(50)));
const parts = () => [scriptSpend(), pay(30), collateral({ utxo: putUp })];

// The largest pays first, and stays the collateral
const built = await build(parts(), [plain, putUp]);
expect(built.collateral!.inputs).toEqual([putUp]);
expect(built.selectedInputs).toEqual([plain]);
expect(built.inputs).not.toContainEqual(putUp);
expect(built.selectedInputs).toEqual([putUp]);

const alone = await build(parts(), [putUp]);
expect(alone.collateral!.inputs).toEqual([putUp]);
expect(alone.selectedInputs).toEqual([putUp]);
});

await expectBuildError(build(parts(), [putUp]), "INSUFFICIENT_FUNDS");
it("does not spend a UTxO a collateral part puts up when the payer leaves it out or refuses it", async () => {
const plain = utxo(lovelace(ada(40)));
const putUp = utxo(lovelace(ada(50)));
const parts = () => [scriptSpend(), pay(30), collateral({ utxo: putUp })];

for (const built of [
await build(parts(), [plain]),
await build(
parts(),
[plain, putUp],
(utxo) => keyOf(utxo) !== keyOf(putUp),
),
]) {
expect(built.collateral!.inputs).toEqual([putUp]);
expect(built.selectedInputs).toEqual([plain]);
expect(built.inputs).not.toContainEqual(putUp);
}
});

it("spends a collateral UTxO that a spend part names too", async () => {
Expand Down
43 changes: 29 additions & 14 deletions packages/mesh-transaction/test/tx-builder/traps-emulator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ describe("TxBuilder's input traps on the emulator", () => {
await submit(emulator, built);
});

it("spends a collateral part's UTxO only when a spend part names it too", async () => {
it("selects a collateral part's UTxO for payment unless the payer leaves it out", async () => {
const putUp = at(address, 50);
const [first, second] = [locked(), locked()];
const emulator = await emulatorWith([
Expand All @@ -150,22 +150,37 @@ describe("TxBuilder's input traps on the emulator", () => {
first,
second,
]);

const kept = await build(emulator, [
unlock(first, plutusScript),
const parts = (lock: Utxo): TxPart[] => [
unlock(lock, plutusScript),
collateral({ utxo: putUp }),
output({ address, value: { lovelace: 30_000_000n } }),
]);
const { body } = kept.prototype;
expect(outRefs(body.collateral)).toEqual([keyOf(putUp)]);
expect(outRefs(body.inputs)).not.toContain(keyOf(putUp));
await submit(emulator, kept);
];
const builder = new TxBuilder({
network,
provider: emulator,
evaluator: emulator,
});
const utxos = await emulator.fetchAddressUTxOs(address);

const spent = await build(emulator, [
unlock(second, plutusScript),
spend.pubKey({ utxo: putUp }),
collateral({ utxo: putUp }),
]);
// Refused by the filter, or left out of the payer's UTxOs: the other UTxO pays
const refused = await builder.build(parts(first), {
payer: { changeAddress: address, utxos },
canSelect: (utxo) => keyOf(utxo) !== keyOf(putUp),
});
const leftOut = await builder.build(parts(first), {
payer: {
changeAddress: address,
utxos: utxos.filter(({ input }) => input.txHash !== putUp.txHash),
},
});
for (const { prototype } of [refused, leftOut]) {
expect(outRefs(prototype.body.collateral)).toEqual([keyOf(putUp)]);
expect(outRefs(prototype.body.inputs)).not.toContain(keyOf(putUp));
}
await submit(emulator, refused);

// Among the payer's UTxOs it is selected as any other, here as the largest
const spent = await build(emulator, parts(second));
expect(outRefs(spent.prototype.body.collateral)).toEqual([keyOf(putUp)]);
expect(outRefs(spent.prototype.body.inputs)).toContain(keyOf(putUp));
await submit(emulator, spent);
Expand Down
Loading