@odatano/core 2.0.0-rc.3 → 2.0.0-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@cds-models/CardanoAgentService/index.d.ts +151 -0
- package/@cds-models/CardanoAgentService/index.js +21 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
- package/@cds-models/odatano/cardano/index.d.ts +50 -0
- package/@cds-models/odatano/cardano/index.js +3 -0
- package/README.md +31 -0
- package/db/schema.cds +72 -0
- package/package.json +173 -173
- package/src/index.d.ts +6 -0
- package/src/index.js +17 -1
- package/src/plugin.js +33 -30
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
- package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
- package/srv/blockchain/wallet-worker/build-request.js +35 -6
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
- package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
- package/srv/blockchain/wallet-worker/job-store.js +42 -9
- package/srv/cardano-agent-service.cds +84 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +16 -0
- package/srv/cardano-tx-service.cds +32 -26
- package/srv/cardano-tx-service.js +96 -38
- package/srv/server.d.ts +2 -1
- package/srv/server.js +12 -0
- package/srv/utils/agent-grants-config.d.ts +48 -0
- package/srv/utils/agent-grants-config.js +124 -0
- package/srv/utils/agent-grants.d.ts +211 -0
- package/srv/utils/agent-grants.js +541 -0
- package/srv/utils/agent-token-auth.d.ts +106 -0
- package/srv/utils/agent-token-auth.js +239 -0
- package/srv/utils/rate-limiter.d.ts +57 -0
- package/srv/utils/rate-limiter.js +126 -0
- package/srv/utils/tx-request-parsers.d.ts +13 -0
- package/srv/utils/tx-request-parsers.js +32 -0
- package/srv/utils/types.d.ts +15 -0
|
@@ -246,13 +246,15 @@ class BuildooorTxBuilder {
|
|
|
246
246
|
const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
|
|
247
247
|
// Parse the minting policy script once
|
|
248
248
|
const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
|
|
249
|
-
// Calculate total mint value for output (only positive quantities - mints, not burns)
|
|
249
|
+
// Calculate total mint value for output (only positive quantities - mints, not burns).
|
|
250
|
+
// Multi-policy mint FR: each action mints under ITS script (own or top-level).
|
|
250
251
|
let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
|
|
251
|
-
for (const mintAction of req.mintActions) {
|
|
252
|
+
for (const [index, mintAction] of req.mintActions.entries()) {
|
|
252
253
|
const quantity = BigInt(mintAction.quantity);
|
|
253
254
|
if (quantity > 0n) {
|
|
255
|
+
const actionScript = this._mintActionScript(mintAction, script, index);
|
|
254
256
|
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
|
|
255
|
-
mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(
|
|
257
|
+
mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), quantity));
|
|
256
258
|
}
|
|
257
259
|
}
|
|
258
260
|
// Partition forced vs candidate UTxOs. Forced inputs are already committed;
|
|
@@ -264,8 +266,15 @@ class BuildooorTxBuilder {
|
|
|
264
266
|
coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
|
|
265
267
|
const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
|
|
266
268
|
const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
|
|
267
|
-
// Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
|
|
268
|
-
|
|
269
|
+
// Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
|
|
270
|
+
// thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
|
|
271
|
+
// demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
|
|
272
|
+
// from the wallet).
|
|
273
|
+
let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
|
|
274
|
+
if (req.extraOutputs && req.extraOutputs.length > 0) {
|
|
275
|
+
const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
|
|
276
|
+
requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
|
|
277
|
+
}
|
|
269
278
|
const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
|
|
270
279
|
const inputs = [...forcedInputs, ...selectedFunding];
|
|
271
280
|
logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
|
|
@@ -281,15 +290,24 @@ class BuildooorTxBuilder {
|
|
|
281
290
|
const resolvedInlineDatum = req.inlineDatum
|
|
282
291
|
? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
|
|
283
292
|
: undefined;
|
|
284
|
-
|
|
293
|
+
const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
|
|
294
|
+
// Build output — recipient gets the minted assets + min ADA. When extra
|
|
295
|
+
// outputs are declared (FR-2 on mint) THEY carry the minted assets (each
|
|
296
|
+
// token on its own output with its own datum, e.g. datum-bound predicate
|
|
297
|
+
// tokens), so the primary output stays ADA(+datum)-only.
|
|
285
298
|
let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
|
|
286
|
-
|
|
299
|
+
if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
|
|
300
|
+
outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
|
|
301
|
+
}
|
|
287
302
|
const refScript = this._parseReferenceScript(req.referenceScript);
|
|
288
303
|
const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
|
|
289
|
-
//
|
|
290
|
-
|
|
304
|
+
// Append extra outputs, each independently min-ADA checked.
|
|
305
|
+
this._appendExtraOutputs(outputs, resolvedExtraOutputs);
|
|
306
|
+
// Mint entries for the build args (uses pre-resolved redeemers; per-action
|
|
307
|
+
// redeemers resolve their own placeholders). Note: Buildooor ignores
|
|
308
|
+
// caller-supplied execution units — the real units are stamped into the
|
|
291
309
|
// redeemers post-build by _buildScriptTx.
|
|
292
|
-
const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
|
|
310
|
+
const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
|
|
293
311
|
// CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
|
|
294
312
|
const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
|
|
295
313
|
// Resolve validity bounds once — both passes must share them so redeemer ExUnits
|
|
@@ -394,11 +412,12 @@ class BuildooorTxBuilder {
|
|
|
394
412
|
}
|
|
395
413
|
// If mints are present and no extraOutputs handle the minted assets, attach positive mints to the primary output.
|
|
396
414
|
if (hasMint && (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0)) {
|
|
397
|
-
for (const action of req.mintActions) {
|
|
415
|
+
for (const [index, action] of req.mintActions.entries()) {
|
|
398
416
|
const qty = BigInt(action.quantity);
|
|
399
417
|
if (qty > 0n) {
|
|
418
|
+
const actionScript = this._mintActionScript(action, mintScript, index);
|
|
400
419
|
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
|
|
401
|
-
outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(
|
|
420
|
+
outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), qty));
|
|
402
421
|
}
|
|
403
422
|
}
|
|
404
423
|
}
|
|
@@ -411,7 +430,7 @@ class BuildooorTxBuilder {
|
|
|
411
430
|
// caller-supplied execution units — the real units are stamped into the
|
|
412
431
|
// redeemers post-build by _buildScriptTx.
|
|
413
432
|
const mints = hasMint
|
|
414
|
-
? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
|
|
433
|
+
? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
|
|
415
434
|
: undefined;
|
|
416
435
|
const scriptInput = {
|
|
417
436
|
utxo: scriptLedgerUtxo,
|
|
@@ -760,21 +779,86 @@ class BuildooorTxBuilder {
|
|
|
760
779
|
return [];
|
|
761
780
|
return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
|
|
762
781
|
}
|
|
782
|
+
/**
|
|
783
|
+
* Funding requirement contributed by extra outputs on a mint build:
|
|
784
|
+
* the summed lovelace of all entries plus, per asset unit, the demand the
|
|
785
|
+
* transaction's own positive mints do NOT cover. Minted quantities are
|
|
786
|
+
* aggregated per unit and subtracted from the aggregated output demand;
|
|
787
|
+
* only a positive remainder is requested from the wallet (a fully covered
|
|
788
|
+
* unit is not requested at all — it does not exist before this tx).
|
|
789
|
+
*/
|
|
790
|
+
_extraOutputsFundingAfterMint(mintActions, extraOutputs) {
|
|
791
|
+
const mintedByUnit = new Map();
|
|
792
|
+
for (const action of mintActions) {
|
|
793
|
+
const quantity = BigInt(action.quantity);
|
|
794
|
+
if (quantity > 0n) {
|
|
795
|
+
const unit = action.assetUnit.toLowerCase();
|
|
796
|
+
mintedByUnit.set(unit, (mintedByUnit.get(unit) ?? 0n) + quantity);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
const demandByUnit = new Map();
|
|
800
|
+
let lovelace = 0n;
|
|
801
|
+
for (const extra of extraOutputs) {
|
|
802
|
+
lovelace += BigInt(extra.lovelaceAmount);
|
|
803
|
+
for (const asset of extra.assets ?? []) {
|
|
804
|
+
const unit = asset.unit.toLowerCase();
|
|
805
|
+
demandByUnit.set(unit, (demandByUnit.get(unit) ?? 0n) + BigInt(asset.quantity));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const assets = [];
|
|
809
|
+
for (const [unit, demand] of demandByUnit) {
|
|
810
|
+
const uncovered = demand - (mintedByUnit.get(unit) ?? 0n);
|
|
811
|
+
if (uncovered > 0n)
|
|
812
|
+
assets.push({ unit, quantity: uncovered.toString() });
|
|
813
|
+
}
|
|
814
|
+
return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* The script an individual mint action executes under: its own
|
|
818
|
+
* per-action policy when set (multi-policy mint FR), else the request's
|
|
819
|
+
* top-level policy script.
|
|
820
|
+
*/
|
|
821
|
+
_mintActionScript(action, defaultScript, index) {
|
|
822
|
+
if (!action.mintingPolicyScript)
|
|
823
|
+
return defaultScript;
|
|
824
|
+
return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
|
|
825
|
+
}
|
|
763
826
|
/**
|
|
764
827
|
* Build the Buildooor mint-entry array shared by the mint-only flow and the
|
|
765
828
|
* combined spend+mint flow (Buildooor ignores caller-supplied execution units;
|
|
766
829
|
* they are stamped into the redeemers post-build by _buildScriptTx).
|
|
830
|
+
*
|
|
831
|
+
* Multi-policy mint FR: each action may carry its own policy script and
|
|
832
|
+
* redeemer; absent fields fall back to the request-level ones. The ledger
|
|
833
|
+
* carries ONE redeemer per policy, so actions resolving to the same policy
|
|
834
|
+
* must agree on their redeemer, checked here.
|
|
767
835
|
*/
|
|
768
|
-
_buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
|
|
769
|
-
|
|
836
|
+
_buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
|
|
837
|
+
const redeemerByPolicy = new Map();
|
|
838
|
+
return mintActions.map((action, index) => {
|
|
839
|
+
const script = this._mintActionScript(action, mintScript, index);
|
|
840
|
+
const actionRedeemer = action.redeemerJson !== undefined
|
|
841
|
+
? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
|
|
842
|
+
: resolvedMintRedeemer;
|
|
843
|
+
const redeemerData = actionRedeemer !== undefined
|
|
844
|
+
? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
|
|
845
|
+
: new plutus_data_1.DataI(action.redeemer ?? 0);
|
|
846
|
+
const policyId = script.hash.toString();
|
|
847
|
+
// Canonical comparison over the encoded PlutusData: JSON key order must
|
|
848
|
+
// not matter, and a JSON {int:0} equals the DataI(0) fallback.
|
|
849
|
+
const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
|
|
850
|
+
const seen = redeemerByPolicy.get(policyId);
|
|
851
|
+
if (seen !== undefined && seen !== redeemerFingerprint) {
|
|
852
|
+
throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
|
|
853
|
+
'split them into separate transactions or align the redeemers');
|
|
854
|
+
}
|
|
855
|
+
redeemerByPolicy.set(policyId, redeemerFingerprint);
|
|
770
856
|
const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
|
|
771
857
|
return {
|
|
772
|
-
value: cardano_ledger_ts_1.Value.singleAsset(
|
|
858
|
+
value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
|
|
773
859
|
script: {
|
|
774
|
-
inline:
|
|
775
|
-
redeemer:
|
|
776
|
-
? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
|
|
777
|
-
: new plutus_data_1.DataI(action.redeemer ?? 0)
|
|
860
|
+
inline: script,
|
|
861
|
+
redeemer: redeemerData
|
|
778
862
|
}
|
|
779
863
|
};
|
|
780
864
|
});
|
|
@@ -42,12 +42,13 @@ function parseScriptParams(raw) {
|
|
|
42
42
|
fail('scriptParamsJson must be a JSON array');
|
|
43
43
|
return parsed;
|
|
44
44
|
}
|
|
45
|
-
/** Mirrors the BuildMint/BuildPlutusSpend mint-action parsing (bigint quantities
|
|
45
|
+
/** Mirrors the BuildMint/BuildPlutusSpend mint-action parsing (bigint quantities,
|
|
46
|
+
* multi-policy per-action fields). */
|
|
46
47
|
function parseMintActions(raw, allowBareNames) {
|
|
47
48
|
const parsed = parseJsonField(raw, 'mintActionsJson');
|
|
48
49
|
if (!Array.isArray(parsed))
|
|
49
50
|
fail('mintActionsJson must be a JSON array');
|
|
50
|
-
return parsed.map((rawAction) => {
|
|
51
|
+
return parsed.map((rawAction, i) => {
|
|
51
52
|
if (!rawAction || typeof rawAction !== 'object') {
|
|
52
53
|
fail('Each mint action must be an object with assetUnit and quantity');
|
|
53
54
|
}
|
|
@@ -57,14 +58,37 @@ function parseMintActions(raw, allowBareNames) {
|
|
|
57
58
|
}
|
|
58
59
|
if (typeof action.assetUnit !== 'string')
|
|
59
60
|
fail('Each mint action must have an assetUnit string');
|
|
60
|
-
|
|
61
|
+
// Multi-policy mint FR: optional per-action mintingPolicyScript + redeemerJson.
|
|
62
|
+
const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, i);
|
|
63
|
+
if (policyFields.error)
|
|
64
|
+
fail(policyFields.error);
|
|
65
|
+
let actionPolicyId;
|
|
66
|
+
if (policyFields.script) {
|
|
67
|
+
actionPolicyId = scriptHashOf(policyFields.script, `mintActions[${i}].mintingPolicyScript is not a valid Plutus script`);
|
|
68
|
+
}
|
|
69
|
+
const bareAssetNameForExpansion = (allowBareNames || !!actionPolicyId) &&
|
|
61
70
|
action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
|
|
62
71
|
action.assetUnit.length % 2 === 0 &&
|
|
63
72
|
/^[0-9a-fA-F]*$/.test(action.assetUnit);
|
|
64
73
|
if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
|
|
65
|
-
fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson is set)`);
|
|
74
|
+
fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson or a per-action mintingPolicyScript is set)`);
|
|
75
|
+
}
|
|
76
|
+
let assetUnit = action.assetUnit;
|
|
77
|
+
if (actionPolicyId) {
|
|
78
|
+
if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
|
|
79
|
+
assetUnit = actionPolicyId + assetUnit;
|
|
80
|
+
}
|
|
81
|
+
else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
|
|
82
|
+
fail(`mintActions[${i}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`);
|
|
83
|
+
}
|
|
66
84
|
}
|
|
67
|
-
return {
|
|
85
|
+
return {
|
|
86
|
+
assetUnit,
|
|
87
|
+
quantity: BigInt(action.quantity),
|
|
88
|
+
...(typeof action.redeemer === 'number' ? { redeemer: action.redeemer } : {}),
|
|
89
|
+
...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
|
|
90
|
+
...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
|
|
91
|
+
};
|
|
68
92
|
});
|
|
69
93
|
}
|
|
70
94
|
function scriptHashOf(scriptHex, context) {
|
|
@@ -81,7 +105,9 @@ function scriptHashOf(scriptHex, context) {
|
|
|
81
105
|
* would mint a truncated asset name.
|
|
82
106
|
*/
|
|
83
107
|
function assertPolicyPrefix(actions, policyId) {
|
|
84
|
-
|
|
108
|
+
// Actions with their own per-action script were already checked against THAT
|
|
109
|
+
// script's policy id during parsing.
|
|
110
|
+
const mismatch = actions.find((a) => !a.mintingPolicyScript && !a.assetUnit.toLowerCase().startsWith(policyId));
|
|
85
111
|
if (mismatch) {
|
|
86
112
|
fail(`assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`);
|
|
87
113
|
}
|
|
@@ -153,6 +179,7 @@ function prepareMint(raw, network) {
|
|
|
153
179
|
const mintRedeemer = parseJsonField(raw, 'mintRedeemerJson');
|
|
154
180
|
const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
|
|
155
181
|
const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
|
|
182
|
+
const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
|
|
156
183
|
if (raw.lockOnScript && (!scriptParams || scriptParams.length === 0)) {
|
|
157
184
|
fail('lockOnScript requires scriptParamsJson to derive script address');
|
|
158
185
|
}
|
|
@@ -172,6 +199,7 @@ function prepareMint(raw, network) {
|
|
|
172
199
|
delete clean.lockOnScript;
|
|
173
200
|
delete clean.forceInputsJson;
|
|
174
201
|
delete clean.referenceInputsJson;
|
|
202
|
+
delete clean.extraOutputsJson;
|
|
175
203
|
if (parsedMetadata)
|
|
176
204
|
clean.metadataJson = parsedMetadata;
|
|
177
205
|
else
|
|
@@ -219,6 +247,7 @@ function prepareMint(raw, network) {
|
|
|
219
247
|
mintRedeemer,
|
|
220
248
|
forceInputs,
|
|
221
249
|
referenceInputs,
|
|
250
|
+
extraOutputs,
|
|
222
251
|
};
|
|
223
252
|
}
|
|
224
253
|
function preparePlutusSpend(raw, network) {
|
|
@@ -28,6 +28,13 @@ export interface TrackedJob {
|
|
|
28
28
|
submittedAt: string;
|
|
29
29
|
foundSlot: number | null;
|
|
30
30
|
foundHeight: number | null;
|
|
31
|
+
/**
|
|
32
|
+
* Polling round in which the tx was last SEEN on-chain (found or
|
|
33
|
+
* re-validated). A job found in the current round needs no second lookup
|
|
34
|
+
* before it is confirmed; one found in an earlier round is re-checked, so a
|
|
35
|
+
* rollback the crawler did not report (crawler off) cannot slip through.
|
|
36
|
+
*/
|
|
37
|
+
seenRound?: number;
|
|
31
38
|
}
|
|
32
39
|
export interface ConfirmationTrackerOptions {
|
|
33
40
|
confirmationDepth: number;
|
|
@@ -59,6 +66,8 @@ export declare class ConfirmationTracker {
|
|
|
59
66
|
private running;
|
|
60
67
|
private polling;
|
|
61
68
|
private lastKnownTipHeight;
|
|
69
|
+
/** Polling round counter; see TrackedJob.seenRound. */
|
|
70
|
+
private round;
|
|
62
71
|
constructor(deps: ConfirmationTrackerDeps);
|
|
63
72
|
start(): void;
|
|
64
73
|
stop(): void;
|
|
@@ -77,10 +86,32 @@ export declare class ConfirmationTracker {
|
|
|
77
86
|
}): void;
|
|
78
87
|
private onBlockIndexed;
|
|
79
88
|
private onReorg;
|
|
89
|
+
/**
|
|
90
|
+
* The recorded inclusion is gone (a reorg the crawler reported, or a polling
|
|
91
|
+
* re-check that no longer finds the tx): back to watching, and optionally
|
|
92
|
+
* re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
|
|
93
|
+
* guard. "Already known" means the tx survived into the new chain's mempool;
|
|
94
|
+
* that is success, not an error.
|
|
95
|
+
*/
|
|
96
|
+
private forgetInclusion;
|
|
80
97
|
/** One polling round. Public for tests; guarded against overlapping rounds. */
|
|
81
98
|
pollOnce(): Promise<void>;
|
|
82
|
-
/**
|
|
99
|
+
/**
|
|
100
|
+
* Confirm every found job whose depth requirement is met by the known tip.
|
|
101
|
+
* `revalidate` (polling path): an inclusion not seen in THIS round is looked
|
|
102
|
+
* up again first — the crawler's reorg events are the only rollback signal,
|
|
103
|
+
* and with the crawler off there is none, so a tx that was found at height N
|
|
104
|
+
* and then rolled back would otherwise be confirmed on the tip alone.
|
|
105
|
+
*/
|
|
83
106
|
private confirmMature;
|
|
107
|
+
/**
|
|
108
|
+
* Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
|
|
109
|
+
* moved to another block (re-included after a rollback) gets its new point
|
|
110
|
+
* and is judged at the new height; one that is gone is forgotten (back to
|
|
111
|
+
* watching, optional same-CBOR re-submit) and the tip is re-learned next
|
|
112
|
+
* round, because the pre-rollback tip may overstate the depth.
|
|
113
|
+
*/
|
|
114
|
+
private stillIncluded;
|
|
84
115
|
private finalize;
|
|
85
116
|
}
|
|
86
117
|
//# sourceMappingURL=confirmation-tracker.d.ts.map
|
|
@@ -18,6 +18,8 @@ class ConfirmationTracker {
|
|
|
18
18
|
running = false;
|
|
19
19
|
polling = false;
|
|
20
20
|
lastKnownTipHeight = null;
|
|
21
|
+
/** Polling round counter; see TrackedJob.seenRound. */
|
|
22
|
+
round = 0;
|
|
21
23
|
constructor(deps) {
|
|
22
24
|
this.deps = deps;
|
|
23
25
|
}
|
|
@@ -103,29 +105,38 @@ class ConfirmationTracker {
|
|
|
103
105
|
for (const job of this.pending.values()) {
|
|
104
106
|
if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
|
|
105
107
|
logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
|
|
106
|
-
job
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
108
|
+
await this.forgetInclusion(job);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The recorded inclusion is gone (a reorg the crawler reported, or a polling
|
|
114
|
+
* re-check that no longer finds the tx): back to watching, and optionally
|
|
115
|
+
* re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
|
|
116
|
+
* guard. "Already known" means the tx survived into the new chain's mempool;
|
|
117
|
+
* that is success, not an error.
|
|
118
|
+
*/
|
|
119
|
+
async forgetInclusion(job) {
|
|
120
|
+
job.foundSlot = null;
|
|
121
|
+
job.foundHeight = null;
|
|
122
|
+
job.seenRound = undefined;
|
|
123
|
+
try {
|
|
124
|
+
await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
|
|
128
|
+
}
|
|
129
|
+
if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
|
|
130
|
+
try {
|
|
131
|
+
await this.deps.client.submitTransaction(job.signedTxCbor);
|
|
132
|
+
logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
if (err instanceof errors_1.TransactionAlreadySubmittedError) {
|
|
136
|
+
logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
|
|
113
137
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
// survived into the new chain's mempool; that is success, not an error.
|
|
117
|
-
try {
|
|
118
|
-
await this.deps.client.submitTransaction(job.signedTxCbor);
|
|
119
|
-
logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
|
|
120
|
-
}
|
|
121
|
-
catch (err) {
|
|
122
|
-
if (err instanceof errors_1.TransactionAlreadySubmittedError) {
|
|
123
|
-
logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
|
|
124
|
-
}
|
|
125
|
-
else {
|
|
126
|
-
logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
138
|
+
else {
|
|
139
|
+
logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
|
|
129
140
|
}
|
|
130
141
|
}
|
|
131
142
|
}
|
|
@@ -136,6 +147,7 @@ class ConfirmationTracker {
|
|
|
136
147
|
if (!this.running || this.polling || this.pending.size === 0)
|
|
137
148
|
return;
|
|
138
149
|
this.polling = true;
|
|
150
|
+
this.round++;
|
|
139
151
|
try {
|
|
140
152
|
// Tip first — also serves the depth check for hook-found entries when the
|
|
141
153
|
// crawler is off.
|
|
@@ -156,6 +168,7 @@ class ConfirmationTracker {
|
|
|
156
168
|
const tx = await this.deps.client.getTransaction(job.txHash);
|
|
157
169
|
job.foundSlot = tx.slot ?? null;
|
|
158
170
|
job.foundHeight = tx.blockHeight ?? null;
|
|
171
|
+
job.seenRound = this.round;
|
|
159
172
|
await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
|
|
160
173
|
logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
|
|
161
174
|
}
|
|
@@ -175,31 +188,73 @@ class ConfirmationTracker {
|
|
|
175
188
|
}
|
|
176
189
|
}
|
|
177
190
|
}
|
|
178
|
-
|
|
191
|
+
// Polling has no reorg signal, so an inclusion recorded in an EARLIER
|
|
192
|
+
// round is re-checked before it counts (see stillIncluded).
|
|
193
|
+
await this.confirmMature(true);
|
|
179
194
|
}
|
|
180
195
|
finally {
|
|
181
196
|
this.polling = false;
|
|
182
197
|
}
|
|
183
198
|
}
|
|
184
199
|
// ---- Shared -----------------------------------------------------------------
|
|
185
|
-
/**
|
|
186
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Confirm every found job whose depth requirement is met by the known tip.
|
|
202
|
+
* `revalidate` (polling path): an inclusion not seen in THIS round is looked
|
|
203
|
+
* up again first — the crawler's reorg events are the only rollback signal,
|
|
204
|
+
* and with the crawler off there is none, so a tx that was found at height N
|
|
205
|
+
* and then rolled back would otherwise be confirmed on the tip alone.
|
|
206
|
+
*/
|
|
207
|
+
async confirmMature(revalidate = false) {
|
|
187
208
|
const tip = this.lastKnownTipHeight;
|
|
188
209
|
if (tip == null)
|
|
189
210
|
return;
|
|
190
211
|
for (const job of [...this.pending.values()]) {
|
|
191
212
|
if (job.foundHeight == null)
|
|
192
213
|
continue;
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
214
|
+
if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
|
|
215
|
+
continue;
|
|
216
|
+
if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
|
|
217
|
+
continue;
|
|
218
|
+
await this.finalize(job, 'confirmed');
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
|
|
223
|
+
* moved to another block (re-included after a rollback) gets its new point
|
|
224
|
+
* and is judged at the new height; one that is gone is forgotten (back to
|
|
225
|
+
* watching, optional same-CBOR re-submit) and the tip is re-learned next
|
|
226
|
+
* round, because the pre-rollback tip may overstate the depth.
|
|
227
|
+
*/
|
|
228
|
+
async stillIncluded(job, tip) {
|
|
229
|
+
try {
|
|
230
|
+
const tx = await this.deps.client.getTransaction(job.txHash);
|
|
231
|
+
const height = tx.blockHeight ?? null;
|
|
232
|
+
job.seenRound = this.round;
|
|
233
|
+
if (height != null && height !== job.foundHeight) {
|
|
234
|
+
logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
|
|
235
|
+
job.foundHeight = height;
|
|
236
|
+
job.foundSlot = tx.slot ?? null;
|
|
237
|
+
await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
|
|
238
|
+
return tip - height + 1 >= this.deps.options.confirmationDepth;
|
|
239
|
+
}
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
|
|
244
|
+
logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
|
|
245
|
+
this.lastKnownTipHeight = null;
|
|
246
|
+
await this.forgetInclusion(job);
|
|
247
|
+
return false;
|
|
196
248
|
}
|
|
249
|
+
logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
|
|
250
|
+
return false;
|
|
197
251
|
}
|
|
198
252
|
}
|
|
199
253
|
async finalize(job, outcome, errorCode, err) {
|
|
254
|
+
let transitioned = false;
|
|
200
255
|
try {
|
|
201
256
|
await cds_1.default.tx(async (tx) => {
|
|
202
|
-
|
|
257
|
+
transitioned = outcome === 'confirmed'
|
|
203
258
|
? await (0, job_store_1.markConfirmed)(tx, job.jobId)
|
|
204
259
|
: await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
|
|
205
260
|
if (transitioned) {
|
|
@@ -212,6 +267,13 @@ class ConfirmationTracker {
|
|
|
212
267
|
return; // keep tracking — the next poll round retries the transition
|
|
213
268
|
}
|
|
214
269
|
this.pending.delete(job.jobId);
|
|
270
|
+
if (!transitioned) {
|
|
271
|
+
// Somebody else (another tracker instance, a reconciliation pass, a
|
|
272
|
+
// cancel) reached the terminal state first. The job is done either way,
|
|
273
|
+
// but the stats bump and the terminal event belong to the winner only.
|
|
274
|
+
logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
215
277
|
logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
|
|
216
278
|
this.deps.onFinal?.({
|
|
217
279
|
jobId: job.jobId,
|
|
@@ -103,6 +103,17 @@ export interface InsertJobResult {
|
|
|
103
103
|
/** True when an idempotent retry matched an existing non-failed job. */
|
|
104
104
|
deduplicated: boolean;
|
|
105
105
|
}
|
|
106
|
+
/** The job that currently owns an idempotency key, or null when it is free. */
|
|
107
|
+
/**
|
|
108
|
+
* The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
|
|
109
|
+
* submits. Two agents (two grants, two users) may both use `order-1` on the
|
|
110
|
+
* same wallet: each must get its own job, never a "deduplicated" answer that
|
|
111
|
+
* hands one the other's job id. A key from an owner-less caller (privileged
|
|
112
|
+
* test context) stays as-is; an owned key becomes a hash of owner + key, which
|
|
113
|
+
* fits the String(100) column whatever the owner id's length and never collides
|
|
114
|
+
* with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
|
|
115
|
+
*/
|
|
116
|
+
export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
|
|
106
117
|
/**
|
|
107
118
|
* Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
|
|
108
119
|
* docs). Idempotency: an active-or-successful row with the same (walletId, kind,
|
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES = exports.WORKER_LEASE_TTL_MS = void 0;
|
|
7
|
+
exports.dedupKeyFor = dedupKeyFor;
|
|
7
8
|
exports.insertJob = insertJob;
|
|
8
9
|
exports.getJobById = getJobById;
|
|
9
10
|
exports.findDueJobs = findDueJobs;
|
|
@@ -160,6 +161,21 @@ function isUniqueViolation(err) {
|
|
|
160
161
|
return text.includes('unique constraint') || text.includes('duplicate key');
|
|
161
162
|
}
|
|
162
163
|
/** The job that currently owns an idempotency key, or null when it is free. */
|
|
164
|
+
/**
|
|
165
|
+
* The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
|
|
166
|
+
* submits. Two agents (two grants, two users) may both use `order-1` on the
|
|
167
|
+
* same wallet: each must get its own job, never a "deduplicated" answer that
|
|
168
|
+
* hands one the other's job id. A key from an owner-less caller (privileged
|
|
169
|
+
* test context) stays as-is; an owned key becomes a hash of owner + key, which
|
|
170
|
+
* fits the String(100) column whatever the owner id's length and never collides
|
|
171
|
+
* with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
|
|
172
|
+
*/
|
|
173
|
+
function dedupKeyFor(owner, idempotencyKey) {
|
|
174
|
+
const scope = owner?.trim() ?? '';
|
|
175
|
+
if (!scope)
|
|
176
|
+
return idempotencyKey;
|
|
177
|
+
return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
|
|
178
|
+
}
|
|
163
179
|
async function readDedupHolder(db, walletId, kind, dedupKey) {
|
|
164
180
|
const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
|
|
165
181
|
return row ? toJobRow(row) : null;
|
|
@@ -185,10 +201,12 @@ async function readDedupHolder(db, walletId, kind, dedupKey) {
|
|
|
185
201
|
*/
|
|
186
202
|
async function insertJob(db, args) {
|
|
187
203
|
const idempotencyKey = args.idempotencyKey ?? null;
|
|
188
|
-
|
|
204
|
+
// The claim is per principal: the same key from another owner is another job.
|
|
205
|
+
const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
|
|
206
|
+
if (claim) {
|
|
189
207
|
// Fast path: an owner exists (by construction it is non-terminal). Terminal
|
|
190
208
|
// jobs release their claim, so they never show up here.
|
|
191
|
-
const holder = await readDedupHolder(db, args.walletId, args.kind,
|
|
209
|
+
const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
|
|
192
210
|
if (holder) {
|
|
193
211
|
if (holder.status !== 'failed' && holder.status !== 'cancelled') {
|
|
194
212
|
return { jobId: holder.ID, status: holder.status, deduplicated: true };
|
|
@@ -208,7 +226,7 @@ async function insertJob(db, args) {
|
|
|
208
226
|
idempotencyKey,
|
|
209
227
|
// No key → the row's own ID: unique by construction, so keyless jobs never
|
|
210
228
|
// contend for the constraint.
|
|
211
|
-
dedupKey:
|
|
229
|
+
dedupKey: claim ?? jobId,
|
|
212
230
|
request: args.request,
|
|
213
231
|
priority: args.priority ?? 100,
|
|
214
232
|
notBefore: args.notBefore ?? null,
|
|
@@ -223,9 +241,9 @@ async function insertJob(db, args) {
|
|
|
223
241
|
catch (err) {
|
|
224
242
|
// Lost the race: another transaction committed the same key first. Its job is
|
|
225
243
|
// the one and only job for this key — hand it back instead of paying twice.
|
|
226
|
-
if (!
|
|
244
|
+
if (!claim || !isUniqueViolation(err))
|
|
227
245
|
throw err;
|
|
228
|
-
const winner = await readDedupHolder(db, args.walletId, args.kind,
|
|
246
|
+
const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
|
|
229
247
|
if (!winner)
|
|
230
248
|
throw err; // constraint fired for some other reason — do not mask it
|
|
231
249
|
logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
|
|
@@ -285,14 +303,29 @@ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
|
|
|
285
303
|
async function releaseDedupClaim(db, jobId) {
|
|
286
304
|
await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
|
|
287
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Move a job from one of `fromStatuses` to `set.status` and report whether THIS
|
|
308
|
+
* call did it. The guard is the conditional UPDATE; the answer is its affected
|
|
309
|
+
* row count (every @cap-js adapter returns a number). A second caller that
|
|
310
|
+
* finds the row already in the target state gets `false`: the transition, the
|
|
311
|
+
* wallet-stats bump and the terminal event belong to the first one only.
|
|
312
|
+
* Two trackers confirming the same job used to count it twice.
|
|
313
|
+
*
|
|
314
|
+
* Fallback for an adapter that returns something that is not a count: read
|
|
315
|
+
* the row back, and accept the target state only if the row was NOT already
|
|
316
|
+
* there before this call (checked with a pre-read in that branch).
|
|
317
|
+
*/
|
|
288
318
|
async function guardedTransition(db, jobId, fromStatuses, set) {
|
|
289
|
-
await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
|
|
319
|
+
const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
|
|
290
320
|
.set(set)
|
|
291
321
|
.where({ ID: jobId, status: { in: fromStatuses } }));
|
|
292
|
-
|
|
293
|
-
|
|
322
|
+
const n = typeof affected === 'number' ? affected : Number(affected);
|
|
323
|
+
if (Number.isFinite(n))
|
|
324
|
+
return n > 0;
|
|
325
|
+
// Unknown return shape: the row is in the target state AND that state is not
|
|
326
|
+
// one it could have been in before (the guard excludes it) means we moved it.
|
|
294
327
|
const row = await getJobById(db, jobId);
|
|
295
|
-
return row?.status === set.status;
|
|
328
|
+
return row?.status === set.status && !fromStatuses.includes(set.status);
|
|
296
329
|
}
|
|
297
330
|
/** pending → building. Increments the attempt counter. Returns false when lost. */
|
|
298
331
|
async function markBuilding(db, jobId, attempt) {
|