@ocap/tx-protocols 1.31.0 → 1.31.1

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.
@@ -222,6 +222,7 @@ declare function verifyAndConsumeUnlinkableGasPass(params: {
222
222
  nowMs?: number;
223
223
  config: IChainConfig;
224
224
  statedb?: unknown;
225
+ consumeNullifier?: boolean;
225
226
  }): {
226
227
  valid: boolean;
227
228
  reason?: string;
@@ -464,14 +464,16 @@ function verifyAndConsumeUnlinkableGasPass(params) {
464
464
  reason: "GAS_PASS_NULLIFIER_ALREADY_SPENT"
465
465
  };
466
466
  }
467
- if (nullifierMap.size >= MAX_NULLIFIERS_PER_STAKE) {
468
- const oldest = nullifierMap.keys().next().value;
469
- if (oldest) nullifierMap.delete(oldest);
467
+ if (params.consumeNullifier !== false) {
468
+ if (nullifierMap.size >= MAX_NULLIFIERS_PER_STAKE) {
469
+ const oldest = nullifierMap.keys().next().value;
470
+ if (oldest) nullifierMap.delete(oldest);
471
+ }
472
+ nullifierMap.set(nullifier, {
473
+ epoch,
474
+ txHash
475
+ });
470
476
  }
471
- nullifierMap.set(nullifier, {
472
- epoch,
473
- txHash
474
- });
475
477
  return {
476
478
  valid: true,
477
479
  stakeId
package/esm/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, IAbuseSlashEvidence, IGasSecurityConfig, IPaymasterDecodedClaims, IStakeForGasEligibilityResult, ITxGasQuotaTelemetry, ITxSecurityWarning, IUnlinkableGasPass, SecurityStrikeTier, StrikeReasonCategory, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
2
  import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.mjs";
3
- import { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
3
+ import { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot } from "./execute.mjs";
4
4
  import { TokenInput } from "./protocols/trade/transfer-v2.mjs";
5
5
  import { MultiInput } from "./protocols/trade/transfer-v3.mjs";
6
6
  import { TokenInput as TokenInput$1 } from "./protocols/trade/exchange-v2.mjs";
@@ -810,4 +810,4 @@ declare const defaultExecutor: {
810
810
  };
811
811
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
812
812
  //#endregion
813
- export { COUNTER_NAMES, type CounterName, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, type IAbuseSlashEvidence, type IGasSecurityConfig, type IPaymasterDecodedClaims, type IStakeForGasEligibilityResult, type ITxGasQuotaTelemetry, type ITxSecurityWarning, type IUnlinkableGasPass, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PostExecutionInvariantGate, PreFlightWaf, type QueueState, STAGE_LABELS, type SecurityStrikeTier, type StageLabel, type StrikeReasonCategory, TRACKED_STATE_TABLES, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, defaultExecutor as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
813
+ export { COUNTER_NAMES, type CounterName, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, type IAbuseSlashEvidence, type IGasSecurityConfig, type IPaymasterDecodedClaims, type IStakeForGasEligibilityResult, type ITxGasQuotaTelemetry, type ITxSecurityWarning, type IUnlinkableGasPass, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, type QueueState, STAGE_LABELS, type SecurityStrikeTier, type StageLabel, type StrikeReasonCategory, TRACKED_STATE_TABLES, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, defaultExecutor as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
package/esm/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
2
  import { WriteLedger } from "./pipes/write-ledger.mjs";
3
3
  import { COUNTER_NAMES, STAGE_LABELS, TxTimer } from "./tx-timer.mjs";
4
- import execute_default, { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
4
+ import execute_default, { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot } from "./execute.mjs";
5
5
  import delegate_default from "./protocols/account/delegate.mjs";
6
6
  import migrate_default from "./protocols/account/migrate.mjs";
7
7
  import revoke_delegate_default from "./protocols/account/revoke-delegate.mjs";
@@ -101,4 +101,4 @@ const { execute } = defaultExecutor;
101
101
  var src_default = defaultExecutor;
102
102
 
103
103
  //#endregion
104
- export { COUNTER_NAMES, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PostExecutionInvariantGate, PreFlightWaf, STAGE_LABELS, TRACKED_STATE_TABLES, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, src_default as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
104
+ export { COUNTER_NAMES, DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, PostExecutionInvariantGate, PreFlightWaf, STAGE_LABELS, TRACKED_STATE_TABLES, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, assertKnownItxFields, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, createExecutor, src_default as default, evaluateBurstQuota, evaluateStakeForGasEligibility, execute, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeActorAddress, normalizeEntityKey, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, rollbackTrackedStateWrites, scanItxPayloadAnomalies, setTxSecurityWarningForHash, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };
@@ -2,11 +2,11 @@ import { evaluateStakeForGasEligibility, extractTransactionTargets, getActorSecu
2
2
  import { applyTokenUpdates, isGasStakeValid } from "../util.mjs";
3
3
  import { isFromPublicKey, toAddress } from "@arcblock/did";
4
4
  import { toStakeAddress } from "@arcblock/did-util";
5
+ import * as JWT from "@arcblock/jwt";
5
6
  import { account } from "@ocap/state";
6
7
  import { BN, fromTokenToUnit, fromUnitToToken, hexToNumber, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
7
8
  import { CustomError } from "@ocap/util/lib/error";
8
9
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
9
- import * as JWT from "@arcblock/jwt";
10
10
  import noop from "lodash/noop.js";
11
11
  import Debug from "debug";
12
12
 
@@ -27,6 +27,8 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
27
27
  const { config } = context;
28
28
  const { tx: tx$1, extra = {}, txHash = "", txTime } = context;
29
29
  const isFailedTxGasCharge = Boolean(context.isFailedTxGasCharge);
30
+ const canChargeSenderDirectly = Boolean(senderState);
31
+ const txSize = context._baseTxSize ?? context.txSize;
30
32
  const nowMs = txTime ? +new Date(txTime) : Date.now();
31
33
  const { token: token$1, pk } = extra.gasStakeHeaders || {};
32
34
  const rawGasPass = extra.gasPass || extra.txExtra?.gasPass;
@@ -65,7 +67,7 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
65
67
  };
66
68
  };
67
69
  let isThirdPartyGasPass = false;
68
- if (!isFailedTxGasCharge && rawGasPass) {
70
+ if ((!isFailedTxGasCharge || !canChargeSenderDirectly) && rawGasPass) {
69
71
  const passStakeState = rawGasPass.stakeId ? await statedb.stake?.get?.(rawGasPass.stakeId, context) : null;
70
72
  const passResult = verifyAndConsumeUnlinkableGasPass({
71
73
  gasPass: rawGasPass,
@@ -83,7 +85,16 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
83
85
  const passOwner = passStakeState?.sender || rawGasPass.stakeId;
84
86
  isThirdPartyGasPass = Boolean(passOwner && (!tx$1?.from || !isSameDid(passOwner, tx$1.from)) && (!tx$1?.delegator || !isSameDid(passOwner, tx$1.delegator)));
85
87
  const selfStakeInfo = isThirdPartyGasPass ? await resolveSignerSelfGasStake() : null;
86
- if (selfStakeInfo?.valid) {
88
+ const selfStakeEligible = Boolean(selfStakeInfo?.valid) && evaluateStakeForGasEligibility({
89
+ txType,
90
+ txSize,
91
+ gasEstimate,
92
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
93
+ isThirdPartySponsor: false,
94
+ enforceSponsor3DEligibility: false,
95
+ config
96
+ }).eligible;
97
+ if (selfStakeInfo?.valid && selfStakeEligible) {
87
98
  gasStake.owner = selfStakeInfo.owner;
88
99
  gasStake.stakeId = selfStakeInfo.stakeId;
89
100
  gasStake.state = selfStakeInfo.state;
@@ -93,7 +104,7 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
93
104
  gasStake.stakeId = passResult.stakeId;
94
105
  gasStake.state = passStakeState;
95
106
  }
96
- } else if (!isFailedTxGasCharge && token$1 && pk) {
107
+ } else if ((!isFailedTxGasCharge || !canChargeSenderDirectly) && token$1 && pk) {
97
108
  const decoded = JWT.decode(token$1) || {};
98
109
  const sponsorAddress = toAddress(decoded.iss || "");
99
110
  if (!sponsorAddress || !isFromPublicKey(sponsorAddress, pk)) {
@@ -138,7 +149,7 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
138
149
  }
139
150
  if (!isSponsorMigrated && !isSponsorBlocked) {
140
151
  const sponsorStakeId = toStakeAddress(sponsorAddress, sponsorAddress);
141
- const isDirectMode = decoded.mode === "paymaster";
152
+ const isDirectMode = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
142
153
  const sponsorStakeState = !isDirectMode ? await statedb.stake?.get?.(sponsorStakeId, context) : null;
143
154
  const officialTok = config.token?.address || "";
144
155
  const sponsorIsBacked = isDirectMode ? Boolean(sponsorState && officialTok && new BN(sponsorState.tokens?.[officialTok] || 0).gte((totalGas ?? ZERO).gt(ZERO) ? totalGas ?? ZERO : new BN(1))) : isGasStakeValid(sponsorStakeState, config);
@@ -173,7 +184,16 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
173
184
  }
174
185
  }
175
186
  const selfStakeInfo = await resolveSignerSelfGasStake();
176
- if (selfStakeInfo.valid) {
187
+ const selfStakeEligible = Boolean(selfStakeInfo.valid) && evaluateStakeForGasEligibility({
188
+ txType,
189
+ txSize,
190
+ gasEstimate,
191
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
192
+ isThirdPartySponsor: false,
193
+ enforceSponsor3DEligibility: false,
194
+ config
195
+ }).eligible;
196
+ if (selfStakeInfo.valid && selfStakeEligible) {
177
197
  gasStake.owner = selfStakeInfo.owner;
178
198
  gasStake.stakeId = selfStakeInfo.stakeId;
179
199
  gasStake.state = selfStakeInfo.state;
@@ -199,9 +219,9 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
199
219
  if (!gasStake.state && gasStake.stakeId) gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
200
220
  const eligibility = evaluateStakeForGasEligibility({
201
221
  txType,
202
- txSize: context._baseTxSize ?? context.txSize,
222
+ txSize,
203
223
  gasEstimate,
204
- isFailedTxGasCharge,
224
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
205
225
  isThirdPartySponsor,
206
226
  enforceSponsor3DEligibility,
207
227
  config
@@ -246,7 +266,7 @@ function isMatchingAccountPublicKey(onChainPk, headerPk) {
246
266
  value: totalGasBN.toString(10)
247
267
  };
248
268
  context.gasVaultChange = changes.gas;
249
- if (isPaymasterDirectCharge && !isFailedTxGasCharge) sponsorGasCost = totalGasBN;
269
+ if (isPaymasterDirectCharge && (!isFailedTxGasCharge || !canChargeSenderDirectly)) sponsorGasCost = totalGasBN;
250
270
  else txCost = txCost.add(totalGasBN);
251
271
  }
252
272
  if (changes.fee) if (config.vaults.txFees?.length) {
@@ -1,6 +1,7 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes } from "./revoke-ledger.mjs";
4
5
  import { account, asset, evidence, stake, token } from "@ocap/state";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
7
  import { BN } from "@ocap/util";
@@ -100,10 +101,15 @@ runner.use(pipes.VerifyInfo([
100
101
  error: "WITHIN_WAITING_PERIOD",
101
102
  message: "You can not claim stake before waiting period ends",
102
103
  fn: (ctx) => {
103
- const { txState, stakeState, txTime } = ctx;
104
+ const { itx, txState, stakeState, txTime } = ctx;
104
105
  const waitingMs = (stakeState.revokeWaitingPeriod || 0) * 1e3;
105
106
  const txEnd = +new Date(txState.time) + waitingMs;
106
- const stateEnd = stakeState.context?.renaissanceTime ? +new Date(stakeState.context.renaissanceTime) + waitingMs : 0;
107
+ const revokes = normalizeStakeRevokes(stakeState);
108
+ const evidenceHash = itx.evidence?.hash || "";
109
+ const trackedEntry = Object.hasOwn(revokes, evidenceHash) ? revokes[evidenceHash] : void 0;
110
+ const legacyEntry = Object.hasOwn(revokes, LEGACY_REVOKE_KEY) ? revokes[LEGACY_REVOKE_KEY] : void 0;
111
+ const baseTime = trackedEntry ? trackedEntry.txTime : legacyEntry?.txTime || stakeState.context?.renaissanceTime;
112
+ const stateEnd = baseTime ? +new Date(baseTime) + waitingMs : 0;
107
113
  const end = Math.max(txEnd, stateEnd);
108
114
  return +new Date(txTime) > end;
109
115
  }
@@ -117,13 +123,20 @@ runner.use(pipes.VerifyTxInput({
117
123
  assetsKey: "assets"
118
124
  }));
119
125
  runner.use((context, next) => {
120
- const { outputs = [], stakeState } = context;
126
+ const { itx, outputs = [], stakeState } = context;
121
127
  const ZERO = new BN(0);
128
+ const revokes = normalizeStakeRevokes(stakeState);
129
+ const evidenceHash = itx.evidence?.hash || "";
130
+ const targetBucket = Object.hasOwn(revokes, evidenceHash) ? revokes[evidenceHash] : Object.hasOwn(revokes, LEGACY_REVOKE_KEY) ? revokes[LEGACY_REVOKE_KEY] : void 0;
131
+ const bucketTokens = targetBucket?.tokens || {};
132
+ const bucketAssets = new Set(targetBucket?.assets || []);
122
133
  const availableRevokedTokens = {};
123
134
  Object.entries(stakeState.revokedTokens || {}).forEach(([addr, val]) => {
124
- availableRevokedTokens[addr] = new BN(val || "0");
135
+ const totalAvail = new BN(val || "0");
136
+ const bucketAvail = new BN(bucketTokens[addr] || "0");
137
+ availableRevokedTokens[addr] = BN.min(totalAvail, bucketAvail);
125
138
  });
126
- const availableRevokedAssets = new Set(stakeState.revokedAssets || []);
139
+ const availableRevokedAssets = new Set((stakeState.revokedAssets || []).filter((a) => bucketAssets.has(a)));
127
140
  let hasClaimable = false;
128
141
  const clampedOutputs = [];
129
142
  outputs.forEach((output) => {
@@ -266,10 +279,19 @@ runner.use(async (context, next) => {
266
279
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates, newEvidenceState] = await Promise.all([
267
280
  statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, receiverUpdates[senderState.address] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
268
281
  Promise.all(uniqBy(receiverStates, "address").filter((x) => x.address !== senderState.address).map((x) => statedb.account.update(x.address, account.update(x, receiverUpdates[x.address], context), context))),
269
- statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, Object.values(stakeUpdates.revokedTokens || {}).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0 ? {
270
- ...context,
271
- txTime: stakeState.context?.renaissanceTime || context.txTime
272
- } : context), context),
282
+ (() => {
283
+ const nextRevokes = consumeStakeRevoke(stakeState, itx.evidence.hash, outputs);
284
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
285
+ ...stakeUpdates,
286
+ context: {
287
+ ...stakeState.context,
288
+ revokes: nextRevokes
289
+ }
290
+ }, Object.values(stakeUpdates.revokedTokens || {}).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0 ? {
291
+ ...context,
292
+ txTime: stakeState.context?.renaissanceTime || context.txTime
293
+ } : context), context);
294
+ })(),
273
295
  Promise.all(assetStates.map(async (x) => {
274
296
  const nextOwner = assetUpdates[x.address]?.owner;
275
297
  const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
@@ -0,0 +1,34 @@
1
+ import { IStakeRevokeEntry, IStakeState } from "@ocap/types";
2
+
3
+ //#region src/protocols/governance/revoke-ledger.d.ts
4
+ declare const LEGACY_REVOKE_KEY = "__legacy__";
5
+ interface TokenInputLike {
6
+ address: string;
7
+ value: string;
8
+ }
9
+ interface OutputLike {
10
+ tokensList?: TokenInputLike[];
11
+ tokens?: TokenInputLike[];
12
+ assetsList?: string[];
13
+ assets?: string[];
14
+ }
15
+ /**
16
+ * Normalizes `stakeState.context?.revokes` against aggregate `stakeState.revokedTokens` and `stakeState.revokedAssets`.
17
+ * Any unattributed aggregate revoked tokens/assets (e.g. from pre-upgrade legacy stakes) are placed into
18
+ * `revokes[LEGACY_REVOKE_KEY]` at the head of the FIFO queue with `renaissanceTime` as their unlock base.
19
+ */
20
+ declare function normalizeStakeRevokes(stakeState: IStakeState): Record<string, IStakeRevokeEntry>;
21
+ /**
22
+ * Records a new `revoke_stake` transaction's outputs into the per-revoke ledger under `txHash`.
23
+ */
24
+ declare function recordStakeRevoke(stakeState: IStakeState, txHash: string, txTime: string, outputs: OutputLike[]): Record<string, IStakeRevokeEntry>;
25
+ /**
26
+ * Deducts slashed revoked tokens and assets from the per-revoke ledger in FIFO order (oldest first).
27
+ */
28
+ declare function slashStakeRevokes(stakeState: IStakeState, nextRevokedTokens: Record<string, string>, nextRevokedAssets: string[], slashTxTime: string): Record<string, IStakeRevokeEntry>;
29
+ /**
30
+ * Consumes claimed tokens and assets from the target revoke entry (`evidenceHash` or `LEGACY_REVOKE_KEY`).
31
+ */
32
+ declare function consumeStakeRevoke(stakeState: IStakeState, evidenceHash: string, claimedOutputs: OutputLike[]): Record<string, IStakeRevokeEntry>;
33
+ //#endregion
34
+ export { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes, recordStakeRevoke, slashStakeRevokes };
@@ -0,0 +1,179 @@
1
+ import { BN } from "@ocap/util";
2
+ import { getListField } from "@ocap/util/lib/get-list-field";
3
+
4
+ //#region src/protocols/governance/revoke-ledger.ts
5
+ const LEGACY_REVOKE_KEY = "__legacy__";
6
+ const ZERO = new BN(0);
7
+ function hasPositiveEntry(entry) {
8
+ if (!entry) return false;
9
+ const hasTokens = Object.values(entry.tokens || {}).some((v) => new BN(String(v || "0")).gt(ZERO));
10
+ const hasAssets = Array.isArray(entry.assets) && entry.assets.length > 0;
11
+ return hasTokens || hasAssets;
12
+ }
13
+ /**
14
+ * Normalizes `stakeState.context?.revokes` against aggregate `stakeState.revokedTokens` and `stakeState.revokedAssets`.
15
+ * Any unattributed aggregate revoked tokens/assets (e.g. from pre-upgrade legacy stakes) are placed into
16
+ * `revokes[LEGACY_REVOKE_KEY]` at the head of the FIFO queue with `renaissanceTime` as their unlock base.
17
+ */
18
+ function normalizeStakeRevokes(stakeState) {
19
+ const aggTokens = stakeState.revokedTokens || {};
20
+ const aggAssets = Array.isArray(stakeState.revokedAssets) ? stakeState.revokedAssets : [];
21
+ const rawRevokes = stakeState.context?.revokes || {};
22
+ const orderedKeys = [...Object.hasOwn(rawRevokes, LEGACY_REVOKE_KEY) ? [LEGACY_REVOKE_KEY] : [], ...Object.keys(rawRevokes).filter((k) => k !== LEGACY_REVOKE_KEY)];
23
+ const remainingTokenCap = {};
24
+ for (const [tok, val] of Object.entries(aggTokens)) {
25
+ const bnVal = new BN(String(val || "0"));
26
+ if (bnVal.gt(ZERO)) remainingTokenCap[tok] = bnVal;
27
+ }
28
+ const aggAssetSet = new Set(aggAssets);
29
+ const seenAssets = /* @__PURE__ */ new Set();
30
+ const normalized = {};
31
+ for (const key of orderedKeys) {
32
+ const raw = rawRevokes[key];
33
+ if (!raw || typeof raw !== "object") continue;
34
+ const clampedTokens = {};
35
+ for (const [tok, val] of Object.entries(raw.tokens || {})) {
36
+ const cap = remainingTokenCap[tok] || ZERO;
37
+ const entryBn = new BN(String(val || "0"));
38
+ const actual = BN.min(entryBn, cap);
39
+ if (actual.gt(ZERO)) {
40
+ clampedTokens[tok] = actual.toString(10);
41
+ remainingTokenCap[tok] = cap.sub(actual);
42
+ }
43
+ }
44
+ const clampedAssets = (Array.isArray(raw.assets) ? raw.assets : []).filter((a) => {
45
+ if (aggAssetSet.has(a) && !seenAssets.has(a)) {
46
+ seenAssets.add(a);
47
+ return true;
48
+ }
49
+ return false;
50
+ });
51
+ normalized[key] = {
52
+ txTime: typeof raw.txTime === "string" ? raw.txTime : "",
53
+ tokens: clampedTokens,
54
+ assets: clampedAssets
55
+ };
56
+ }
57
+ const unattributedTokens = {};
58
+ for (const [tok, rem] of Object.entries(remainingTokenCap)) if (rem.gt(ZERO)) unattributedTokens[tok] = rem.toString(10);
59
+ const unattributedAssets = aggAssets.filter((a) => !seenAssets.has(a));
60
+ if (Object.keys(unattributedTokens).length > 0 || unattributedAssets.length > 0) {
61
+ const existingLegacy = normalized[LEGACY_REVOKE_KEY];
62
+ const mergedLegacyTokens = { ...existingLegacy?.tokens || {} };
63
+ for (const [tok, val] of Object.entries(unattributedTokens)) mergedLegacyTokens[tok] = new BN(mergedLegacyTokens[tok] || "0").add(new BN(val)).toString(10);
64
+ const mergedLegacyAssets = Array.from(new Set([...existingLegacy?.assets || [], ...unattributedAssets]));
65
+ const legacyEntry = {
66
+ txTime: existingLegacy?.txTime || stakeState.context?.renaissanceTime || stakeState.context?.genesisTime || "",
67
+ tokens: mergedLegacyTokens,
68
+ assets: mergedLegacyAssets
69
+ };
70
+ const reordered = { [LEGACY_REVOKE_KEY]: legacyEntry };
71
+ for (const [k, v] of Object.entries(normalized)) if (k !== LEGACY_REVOKE_KEY && hasPositiveEntry(v)) reordered[k] = v;
72
+ return reordered;
73
+ }
74
+ const result = {};
75
+ for (const [k, v] of Object.entries(normalized)) if (hasPositiveEntry(v)) result[k] = v;
76
+ return result;
77
+ }
78
+ /**
79
+ * Records a new `revoke_stake` transaction's outputs into the per-revoke ledger under `txHash`.
80
+ */
81
+ function recordStakeRevoke(stakeState, txHash, txTime, outputs) {
82
+ const revokes = normalizeStakeRevokes(stakeState);
83
+ const prev = Object.hasOwn(revokes, txHash) ? revokes[txHash] : void 0;
84
+ const mergedTokens = { ...prev?.tokens || {} };
85
+ const mergedAssets = new Set(prev?.assets || []);
86
+ for (const out of outputs || []) {
87
+ const tokensList = getListField(out, "tokens") || [];
88
+ const assetsList = getListField(out, "assets") || [];
89
+ for (const { address, value } of tokensList) {
90
+ const addBn = new BN(String(value || "0"));
91
+ if (addBn.gt(ZERO)) mergedTokens[address] = new BN(mergedTokens[address] || "0").add(addBn).toString(10);
92
+ }
93
+ for (const assetAddr of assetsList) mergedAssets.add(assetAddr);
94
+ }
95
+ const nextEntry = {
96
+ txTime: txTime || prev?.txTime || "",
97
+ tokens: mergedTokens,
98
+ assets: Array.from(mergedAssets)
99
+ };
100
+ if (hasPositiveEntry(nextEntry)) revokes[txHash] = nextEntry;
101
+ return revokes;
102
+ }
103
+ /**
104
+ * Deducts slashed revoked tokens and assets from the per-revoke ledger in FIFO order (oldest first).
105
+ */
106
+ function slashStakeRevokes(stakeState, nextRevokedTokens, nextRevokedAssets, slashTxTime) {
107
+ const revokes = normalizeStakeRevokes(stakeState);
108
+ const prevRevokedTokens = stakeState.revokedTokens || {};
109
+ const slashedTokens = {};
110
+ for (const [tok, prevVal] of Object.entries(prevRevokedTokens)) {
111
+ const prevBn = new BN(String(prevVal || "0"));
112
+ const nextBn = new BN(String(nextRevokedTokens?.[tok] || "0"));
113
+ const diff = prevBn.sub(nextBn);
114
+ if (diff.gt(ZERO)) slashedTokens[tok] = diff;
115
+ }
116
+ const nextAssetSet = new Set(nextRevokedAssets || []);
117
+ const result = {};
118
+ for (const [key, entry] of Object.entries(revokes)) {
119
+ let shrunk = false;
120
+ const updatedTokens = {};
121
+ for (const [tok, val] of Object.entries(entry.tokens || {})) {
122
+ const avail = new BN(String(val || "0"));
123
+ const toSlash = slashedTokens[tok] || ZERO;
124
+ const deduct = BN.min(avail, toSlash);
125
+ if (deduct.gt(ZERO)) {
126
+ shrunk = true;
127
+ slashedTokens[tok] = toSlash.sub(deduct);
128
+ }
129
+ const rem = avail.sub(deduct);
130
+ if (rem.gt(ZERO)) updatedTokens[tok] = rem.toString(10);
131
+ }
132
+ const prevAssets = entry.assets || [];
133
+ const updatedAssets = prevAssets.filter((a) => nextAssetSet.has(a));
134
+ if (updatedAssets.length < prevAssets.length) shrunk = true;
135
+ const updatedEntry = {
136
+ txTime: key === LEGACY_REVOKE_KEY && shrunk && slashTxTime ? slashTxTime : entry.txTime,
137
+ tokens: updatedTokens,
138
+ assets: updatedAssets
139
+ };
140
+ if (hasPositiveEntry(updatedEntry)) result[key] = updatedEntry;
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * Consumes claimed tokens and assets from the target revoke entry (`evidenceHash` or `LEGACY_REVOKE_KEY`).
146
+ */
147
+ function consumeStakeRevoke(stakeState, evidenceHash, claimedOutputs) {
148
+ const revokes = normalizeStakeRevokes(stakeState);
149
+ const targetKey = evidenceHash && Object.hasOwn(revokes, evidenceHash) ? evidenceHash : LEGACY_REVOKE_KEY;
150
+ const target = Object.hasOwn(revokes, targetKey) ? revokes[targetKey] : void 0;
151
+ if (!target) return revokes;
152
+ const claimedTokens = {};
153
+ const claimedAssets = /* @__PURE__ */ new Set();
154
+ for (const out of claimedOutputs || []) {
155
+ const tokensList = out.tokens || out.tokensList || [];
156
+ const assetsList = out.assets || out.assetsList || [];
157
+ for (const { address, value } of tokensList) claimedTokens[address] = (claimedTokens[address] || ZERO).add(new BN(String(value || "0")));
158
+ for (const assetAddr of assetsList) claimedAssets.add(assetAddr);
159
+ }
160
+ const remainingTokens = {};
161
+ for (const [tok, val] of Object.entries(target.tokens || {})) {
162
+ const avail = new BN(String(val || "0"));
163
+ const deduct = BN.min(avail, claimedTokens[tok] || ZERO);
164
+ const rem = avail.sub(deduct);
165
+ if (rem.gt(ZERO)) remainingTokens[tok] = rem.toString(10);
166
+ }
167
+ const remainingAssets = (target.assets || []).filter((a) => !claimedAssets.has(a));
168
+ const updatedTarget = {
169
+ txTime: target.txTime,
170
+ tokens: remainingTokens,
171
+ assets: remainingAssets
172
+ };
173
+ if (hasPositiveEntry(updatedTarget)) revokes[targetKey] = updatedTarget;
174
+ else delete revokes[targetKey];
175
+ return revokes;
176
+ }
177
+
178
+ //#endregion
179
+ export { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes, recordStakeRevoke, slashStakeRevokes };
@@ -1,6 +1,7 @@
1
1
  import { applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { recordStakeRevoke } from "./revoke-ledger.mjs";
4
5
  import { account, stake } from "@ocap/state";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
7
  import { BN } from "@ocap/util";
@@ -166,10 +167,17 @@ runner.use(async (context, next) => {
166
167
  nonce: tx$1.nonce,
167
168
  ...senderUpdates
168
169
  }, context), context), (() => {
170
+ const nextRevokes = recordStakeRevoke(stakeState, context.txHash, context.txTime, outputs);
169
171
  const hasPendingRevokedTokens = Object.values(stakeState.revokedTokens || {}).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)));
170
172
  const hasPendingRevokedAssets = Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0;
171
173
  const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState.context?.renaissanceTime;
172
- return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, preserveRenaissanceTime ? {
174
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
175
+ ...stakeUpdates,
176
+ context: {
177
+ ...stakeState.context,
178
+ revokes: nextRevokes
179
+ }
180
+ }, preserveRenaissanceTime ? {
173
181
  ...context,
174
182
  txTime: preserveRenaissanceTime
175
183
  } : context), context);
@@ -1,6 +1,7 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { slashStakeRevokes } from "./revoke-ledger.mjs";
4
5
  import { toTypeInfo } from "@arcblock/did";
5
6
  import { types } from "@ocap/mcrypto";
6
7
  import { account, asset, stake, token } from "@ocap/state";
@@ -220,9 +221,16 @@ runner.use(async (context, next) => {
220
221
  (() => {
221
222
  const prevRevoked = stakeState.revokedTokens || {};
222
223
  const nextRevoked = stakeUpdates.revokedTokens || {};
224
+ const nextRevokes = slashStakeRevokes(stakeState, nextRevoked, stakeUpdates.revokedAssets || [], context.txTime);
223
225
  const poolShrunk = Object.keys(prevRevoked).some((k) => new BN(prevRevoked[k] || "0").gt(new BN(nextRevoked[k] || "0"))) || (stakeUpdates.revokedAssets || []).length < (stakeState.revokedAssets || []).length;
224
226
  const hasPending = Object.values(nextRevoked).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0;
225
- return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, hasPending && !poolShrunk ? {
227
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
228
+ ...stakeUpdates,
229
+ context: {
230
+ ...stakeState.context,
231
+ revokes: nextRevokes
232
+ }
233
+ }, hasPending && !poolShrunk ? {
226
234
  ...context,
227
235
  txTime: stakeState.context?.renaissanceTime || context.txTime
228
236
  } : context), context);