@ocap/tx-protocols 1.30.25 → 1.31.0

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.
Files changed (118) hide show
  1. package/esm/execute.d.mts +7 -0
  2. package/esm/execute.mjs +196 -71
  3. package/esm/gas-security-guard.d.mts +374 -0
  4. package/esm/gas-security-guard.mjs +1101 -0
  5. package/esm/index.d.mts +35 -5
  6. package/esm/index.mjs +3 -1
  7. package/esm/pipes/ensure-cost.mjs +314 -58
  8. package/esm/protocols/account/delegate.mjs +64 -16
  9. package/esm/protocols/account/migrate.d.mts +3 -0
  10. package/esm/protocols/account/migrate.mjs +235 -35
  11. package/esm/protocols/account/revoke-delegate.d.mts +3 -3
  12. package/esm/protocols/account/revoke-delegate.mjs +70 -38
  13. package/esm/protocols/asset/acquire-v2.mjs +29 -12
  14. package/esm/protocols/asset/acquire-v3.mjs +78 -22
  15. package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
  16. package/esm/protocols/asset/calls/transfer.mjs +1 -0
  17. package/esm/protocols/asset/consume.mjs +12 -4
  18. package/esm/protocols/asset/create.mjs +18 -5
  19. package/esm/protocols/asset/mint.mjs +23 -1
  20. package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
  21. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
  22. package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
  23. package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
  24. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
  25. package/esm/protocols/asset/update.d.mts +13 -2
  26. package/esm/protocols/asset/update.mjs +133 -14
  27. package/esm/protocols/factory/create.mjs +14 -6
  28. package/esm/protocols/governance/claim-stake.mjs +92 -10
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-stake.mjs +17 -5
  31. package/esm/protocols/governance/slash-stake.mjs +64 -25
  32. package/esm/protocols/governance/stake.mjs +63 -13
  33. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  34. package/esm/protocols/rollup/close.mjs +1 -1
  35. package/esm/protocols/rollup/create-block.mjs +8 -7
  36. package/esm/protocols/rollup/create.mjs +17 -6
  37. package/esm/protocols/rollup/join.mjs +3 -3
  38. package/esm/protocols/rollup/leave.mjs +1 -1
  39. package/esm/protocols/rollup/migrate.mjs +7 -4
  40. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  41. package/esm/protocols/rollup/update.mjs +6 -1
  42. package/esm/protocols/token/create.mjs +23 -12
  43. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  44. package/esm/protocols/token/deposit-v2.mjs +81 -29
  45. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  46. package/esm/protocols/token-factory/burn.mjs +43 -10
  47. package/esm/protocols/token-factory/create.mjs +23 -14
  48. package/esm/protocols/token-factory/mint.mjs +54 -21
  49. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  50. package/esm/protocols/token-factory/update.mjs +16 -6
  51. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  52. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  53. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  54. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  55. package/esm/util.d.mts +3 -1
  56. package/esm/util.mjs +26 -17
  57. package/lib/execute.cjs +193 -67
  58. package/lib/execute.d.cts +7 -0
  59. package/lib/gas-security-guard.cjs +1140 -0
  60. package/lib/gas-security-guard.d.cts +374 -0
  61. package/lib/index.cjs +122 -1
  62. package/lib/index.d.cts +36 -6
  63. package/lib/pipes/ensure-cost.cjs +313 -57
  64. package/lib/protocols/account/delegate.cjs +64 -16
  65. package/lib/protocols/account/migrate.cjs +235 -35
  66. package/lib/protocols/account/migrate.d.cts +3 -0
  67. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  68. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  69. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  70. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  71. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  72. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  73. package/lib/protocols/asset/consume.cjs +11 -3
  74. package/lib/protocols/asset/create.cjs +19 -6
  75. package/lib/protocols/asset/mint.cjs +23 -1
  76. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  77. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  78. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  79. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  80. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  81. package/lib/protocols/asset/update.cjs +131 -12
  82. package/lib/protocols/asset/update.d.cts +13 -2
  83. package/lib/protocols/factory/create.cjs +14 -6
  84. package/lib/protocols/governance/claim-stake.cjs +92 -9
  85. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  86. package/lib/protocols/governance/return-stake.cjs +44 -11
  87. package/lib/protocols/governance/return-stake.d.cts +1 -1
  88. package/lib/protocols/governance/revoke-stake.cjs +17 -5
  89. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  90. package/lib/protocols/governance/slash-stake.cjs +64 -24
  91. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  92. package/lib/protocols/governance/stake.cjs +65 -14
  93. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  94. package/lib/protocols/rollup/close.cjs +1 -1
  95. package/lib/protocols/rollup/create-block.cjs +9 -8
  96. package/lib/protocols/rollup/create-block.d.cts +1 -1
  97. package/lib/protocols/rollup/create.cjs +18 -7
  98. package/lib/protocols/rollup/join.cjs +3 -3
  99. package/lib/protocols/rollup/leave.cjs +1 -1
  100. package/lib/protocols/rollup/migrate.cjs +7 -4
  101. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  102. package/lib/protocols/rollup/update.cjs +6 -1
  103. package/lib/protocols/token/create.cjs +24 -13
  104. package/lib/protocols/token/deposit-v2.cjs +80 -28
  105. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  106. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  107. package/lib/protocols/token-factory/burn.cjs +42 -9
  108. package/lib/protocols/token-factory/create.cjs +24 -15
  109. package/lib/protocols/token-factory/mint.cjs +53 -20
  110. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  111. package/lib/protocols/token-factory/update.cjs +16 -6
  112. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  113. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  114. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  115. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  116. package/lib/util.cjs +26 -17
  117. package/lib/util.d.cts +4 -2
  118. package/package.json +16 -16
package/esm/index.d.mts CHANGED
@@ -1,3 +1,4 @@
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";
1
2
  import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.mjs";
2
3
  import { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
3
4
  import { TokenInput } from "./protocols/trade/transfer-v2.mjs";
@@ -21,6 +22,7 @@ import { TokenChange as TokenChange$2 } from "./protocols/rollup/claim-reward.mj
21
22
  import { WriteLedger } from "./pipes/write-ledger.mjs";
22
23
  import * as states from "@ocap/state";
23
24
  import * as _ocap_tx_pipeline0 from "@ocap/tx-pipeline";
25
+ import { MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PostExecutionInvariantGate, PreFlightWaf, TRACKED_STATE_TABLES, assertKnownItxFields, assertRawWireEnvelope, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites, scanItxPayloadAnomalies } from "@ocap/tx-pipeline";
24
26
  import * as _ocap_util0 from "@ocap/util";
25
27
  import * as _ocap_message0 from "@ocap/message";
26
28
  import * as _ocap_types0 from "@ocap/types";
@@ -100,6 +102,8 @@ declare const createExecutor: ({
100
102
  tokens: TokenInput$1[];
101
103
  };
102
104
  tokenStates?: _ocap_types0.ITokenState[];
105
+ senderTokenStates?: _ocap_types0.ITokenState[];
106
+ receiverTokenStates?: _ocap_types0.ITokenState[];
103
107
  receiver?: string;
104
108
  delegationStates?: _ocap_types0.IDelegateState[];
105
109
  priv?: {
@@ -109,6 +113,8 @@ declare const createExecutor: ({
109
113
  }>;
110
114
  accountMigrate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TAccountMigrateTx> & Partial<_ocap_types0.IWithSender> & {
111
115
  receiverState?: _ocap_types0.IAccountState;
116
+ hasVerifiedPreRotationOrEvent?: boolean;
117
+ hasActivePreRotationCommitment?: boolean;
112
118
  }>;
113
119
  delegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TDelegateTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithReceiver> & Partial<_ocap_types0.IWithDelegation> & {
114
120
  formattedItx?: {
@@ -150,7 +156,7 @@ declare const createExecutor: ({
150
156
  }>;
151
157
  };
152
158
  }>;
153
- revokeDelegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TRevokeDelegateTx> & _ocap_types0.IWithSender & _ocap_types0.IWithDelegation & {
159
+ revokeDelegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TRevokeDelegateTx> & _ocap_types0.IWithSender & _ocap_types0.IWithDelegation & Partial<_ocap_types0.IWithReceiver> & {
154
160
  typeUrls?: string[];
155
161
  }>;
156
162
  createAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TCreateAssetTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithIssuer> & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithDelegation> & Partial<_ocap_types0.IWithAsset> & {
@@ -160,8 +166,16 @@ declare const createExecutor: ({
160
166
  parentAsset?: _ocap_types0.IAssetState;
161
167
  isDelegationChanged?: boolean;
162
168
  }>;
163
- updateAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & Partial<_ocap_types0.IWithIssuer> & {
169
+ updateAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithDelegation> & Partial<_ocap_types0.IWithIssuer> & {
164
170
  newData: _ocap_message0.AnyData | null;
171
+ isDelegationChanged?: boolean;
172
+ tokenInfoForVerification?: {
173
+ symbol: string;
174
+ address: string;
175
+ website?: string | null;
176
+ };
177
+ charterWebsite?: string;
178
+ charterCommunityUrl?: string;
165
179
  }>;
166
180
  consumeAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TConsumeAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & _ocap_types0.IWithIssuer & _ocap_types0.IWithOwner & _ocap_types0.IWithSigners & {
167
181
  signers: string[];
@@ -230,6 +244,8 @@ declare const createExecutor: ({
230
244
  stakeAddress?: string;
231
245
  lockerAddress?: string;
232
246
  lockerState?: _ocap_types0.IStakeState;
247
+ receiverState?: _ocap_types0.IAccountState | null;
248
+ isProposerSponsor?: boolean;
233
249
  signers?: string[];
234
250
  stakeStates?: _ocap_types0.IStakeState[];
235
251
  updatedAccounts?: TokenChange[];
@@ -470,6 +486,8 @@ declare const defaultExecutor: {
470
486
  tokens: TokenInput$1[];
471
487
  };
472
488
  tokenStates?: _ocap_types0.ITokenState[];
489
+ senderTokenStates?: _ocap_types0.ITokenState[];
490
+ receiverTokenStates?: _ocap_types0.ITokenState[];
473
491
  receiver?: string;
474
492
  delegationStates?: _ocap_types0.IDelegateState[];
475
493
  priv?: {
@@ -479,6 +497,8 @@ declare const defaultExecutor: {
479
497
  }>;
480
498
  accountMigrate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TAccountMigrateTx> & Partial<_ocap_types0.IWithSender> & {
481
499
  receiverState?: _ocap_types0.IAccountState;
500
+ hasVerifiedPreRotationOrEvent?: boolean;
501
+ hasActivePreRotationCommitment?: boolean;
482
502
  }>;
483
503
  delegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TDelegateTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithReceiver> & Partial<_ocap_types0.IWithDelegation> & {
484
504
  formattedItx?: {
@@ -520,7 +540,7 @@ declare const defaultExecutor: {
520
540
  }>;
521
541
  };
522
542
  }>;
523
- revokeDelegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TRevokeDelegateTx> & _ocap_types0.IWithSender & _ocap_types0.IWithDelegation & {
543
+ revokeDelegate: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TRevokeDelegateTx> & _ocap_types0.IWithSender & _ocap_types0.IWithDelegation & Partial<_ocap_types0.IWithReceiver> & {
524
544
  typeUrls?: string[];
525
545
  }>;
526
546
  createAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TCreateAssetTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithIssuer> & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithDelegation> & Partial<_ocap_types0.IWithAsset> & {
@@ -530,8 +550,16 @@ declare const defaultExecutor: {
530
550
  parentAsset?: _ocap_types0.IAssetState;
531
551
  isDelegationChanged?: boolean;
532
552
  }>;
533
- updateAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & Partial<_ocap_types0.IWithIssuer> & {
553
+ updateAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TUpdateAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithDelegation> & Partial<_ocap_types0.IWithIssuer> & {
534
554
  newData: _ocap_message0.AnyData | null;
555
+ isDelegationChanged?: boolean;
556
+ tokenInfoForVerification?: {
557
+ symbol: string;
558
+ address: string;
559
+ website?: string | null;
560
+ };
561
+ charterWebsite?: string;
562
+ charterCommunityUrl?: string;
535
563
  }>;
536
564
  consumeAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TConsumeAssetTx> & _ocap_types0.IWithAsset & _ocap_types0.IWithSender & _ocap_types0.IWithIssuer & _ocap_types0.IWithOwner & _ocap_types0.IWithSigners & {
537
565
  signers: string[];
@@ -600,6 +628,8 @@ declare const defaultExecutor: {
600
628
  stakeAddress?: string;
601
629
  lockerAddress?: string;
602
630
  lockerState?: _ocap_types0.IStakeState;
631
+ receiverState?: _ocap_types0.IAccountState | null;
632
+ isProposerSponsor?: boolean;
603
633
  signers?: string[];
604
634
  stakeStates?: _ocap_types0.IStakeState[];
605
635
  updatedAccounts?: TokenChange[];
@@ -780,4 +810,4 @@ declare const defaultExecutor: {
780
810
  };
781
811
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
782
812
  //#endregion
783
- export { COUNTER_NAMES, type CounterName, type QueueState, STAGE_LABELS, type StageLabel, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, createExecutor, defaultExecutor as default, execute, toUnsignedEvidenceKey };
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 };
package/esm/index.mjs CHANGED
@@ -1,3 +1,4 @@
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";
1
2
  import { WriteLedger } from "./pipes/write-ledger.mjs";
2
3
  import { COUNTER_NAMES, STAGE_LABELS, TxTimer } from "./tx-timer.mjs";
3
4
  import execute_default, { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
@@ -37,6 +38,7 @@ import exchange_v2_default from "./protocols/trade/exchange-v2.mjs";
37
38
  import transfer_v2_default from "./protocols/trade/transfer-v2.mjs";
38
39
  import transfer_v3_default from "./protocols/trade/transfer-v3.mjs";
39
40
  import * as states from "@ocap/state";
41
+ import { MAX_POST_EXECUTION_WRITE_SET_ENTRIES, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, PostExecutionInvariantGate, PreFlightWaf, TRACKED_STATE_TABLES, assertKnownItxFields, assertRawWireEnvelope, inspectPostExecutionInvariants, inspectTransactionPreFlight, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites, scanItxPayloadAnomalies } from "@ocap/tx-pipeline";
40
42
 
41
43
  //#region src/index.ts
42
44
  const createExecutor = ({ filter, runAsLambda }) => {
@@ -99,4 +101,4 @@ const { execute } = defaultExecutor;
99
101
  var src_default = defaultExecutor;
100
102
 
101
103
  //#endregion
102
- export { COUNTER_NAMES, STAGE_LABELS, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, createExecutor, src_default as default, execute, toUnsignedEvidenceKey };
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 };
@@ -1,9 +1,11 @@
1
+ import { evaluateStakeForGasEligibility, extractTransactionTargets, getActorSecurityStatus, resolveGasSecurityConfig, setTxSecurityWarningForHash, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "../gas-security-guard.mjs";
1
2
  import { applyTokenUpdates, isGasStakeValid } from "../util.mjs";
3
+ import { isFromPublicKey, toAddress } from "@arcblock/did";
4
+ import { toStakeAddress } from "@arcblock/did-util";
2
5
  import { account } from "@ocap/state";
3
- import { BN, fromTokenToUnit, fromUnitToToken, hexToNumber } from "@ocap/util";
6
+ import { BN, fromTokenToUnit, fromUnitToToken, hexToNumber, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
4
7
  import { CustomError } from "@ocap/util/lib/error";
5
- import { toAddress } from "@arcblock/did";
6
- import { toStakeAddress } from "@arcblock/did-util";
8
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
7
9
  import * as JWT from "@arcblock/jwt";
8
10
  import noop from "lodash/noop.js";
9
11
  import Debug from "debug";
@@ -11,34 +13,221 @@ import Debug from "debug";
11
13
  //#region src/pipes/ensure-cost.ts
12
14
  const debug = Debug("@ocap/tx-protocols:pipes:ensure-cost");
13
15
  const ZERO = new BN(0);
16
+ function isMatchingAccountPublicKey(onChainPk, headerPk) {
17
+ if (onChainPk === headerPk) return true;
18
+ try {
19
+ const headerBuf = toBuffer(headerPk);
20
+ if (toBase58(headerBuf) === onChainPk || toBase64(headerBuf) === onChainPk) return true;
21
+ } catch {}
22
+ return false;
23
+ }
14
24
  /** Context for ensure cost pipe */ function CreateEnsureTxCostPipe({ attachSenderChanges = true, throwOnInsufficientFund = true, gasOnly = false } = {}) {
15
25
  return async function EnsureTxCost(context, next) {
16
26
  const { statedb, txType, senderState, gasEstimate, totalGas } = context;
17
27
  const { config } = context;
18
- const { tx: tx$1, extra = {}, txHash = "" } = context;
28
+ const { tx: tx$1, extra = {}, txHash = "", txTime } = context;
29
+ const isFailedTxGasCharge = Boolean(context.isFailedTxGasCharge);
30
+ const nowMs = txTime ? +new Date(txTime) : Date.now();
19
31
  const { token: token$1, pk } = extra.gasStakeHeaders || {};
32
+ const rawGasPass = extra.gasPass || extra.txExtra?.gasPass;
20
33
  const gasStake = {};
21
- if (token$1 && pk && await JWT.verify(token$1, pk, {
22
- enforceTimestamp: true,
23
- tolerance: 5
24
- })) {
25
- const decoded = JWT.decode(token$1);
26
- if ((decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean).includes(txHash)) {
27
- gasStake.owner = toAddress(decoded.iss);
28
- gasStake.stakeId = toStakeAddress(gasStake.owner, gasStake.owner);
29
- } else console.warn(`Invalid gas payer header for: ${txHash}`);
34
+ let isThirdPartySponsor = false;
35
+ let enforceSponsor3DEligibility = false;
36
+ let isPaymasterDirectCharge = false;
37
+ let sponsorAccountState = null;
38
+ const resolveSignerSelfGasStake = async () => {
39
+ const officialTok = config.token?.address || "";
40
+ if (!officialTok) return {
41
+ hasSelfStake: false,
42
+ owner: "",
43
+ stakeId: "",
44
+ state: null,
45
+ valid: false
46
+ };
47
+ const candidates = Array.from(new Set([tx$1?.from, tx$1?.delegator].filter(Boolean)));
48
+ for (const candidate of candidates) {
49
+ const stakeId = toStakeAddress(candidate, candidate);
50
+ const selfStake = await statedb.stake?.get?.(stakeId, context);
51
+ if (new BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
52
+ hasSelfStake: true,
53
+ owner: candidate,
54
+ stakeId,
55
+ state: selfStake || null,
56
+ valid: isGasStakeValid(selfStake, config)
57
+ };
58
+ }
59
+ return {
60
+ hasSelfStake: false,
61
+ owner: "",
62
+ stakeId: "",
63
+ state: null,
64
+ valid: false
65
+ };
66
+ };
67
+ let isThirdPartyGasPass = false;
68
+ if (!isFailedTxGasCharge && rawGasPass) {
69
+ const passStakeState = rawGasPass.stakeId ? await statedb.stake?.get?.(rawGasPass.stakeId, context) : null;
70
+ const passResult = verifyAndConsumeUnlinkableGasPass({
71
+ gasPass: rawGasPass,
72
+ stakeState: passStakeState,
73
+ txHash,
74
+ nowMs,
75
+ config,
76
+ statedb
77
+ });
78
+ if (!passResult.valid) {
79
+ const passErr = new CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`);
80
+ passErr._unauthenticatedExtraFailure = true;
81
+ return next(passErr);
82
+ }
83
+ const passOwner = passStakeState?.sender || rawGasPass.stakeId;
84
+ isThirdPartyGasPass = Boolean(passOwner && (!tx$1?.from || !isSameDid(passOwner, tx$1.from)) && (!tx$1?.delegator || !isSameDid(passOwner, tx$1.delegator)));
85
+ const selfStakeInfo = isThirdPartyGasPass ? await resolveSignerSelfGasStake() : null;
86
+ if (selfStakeInfo?.valid) {
87
+ gasStake.owner = selfStakeInfo.owner;
88
+ gasStake.stakeId = selfStakeInfo.stakeId;
89
+ gasStake.state = selfStakeInfo.state;
90
+ isThirdPartyGasPass = false;
91
+ } else {
92
+ gasStake.owner = passOwner;
93
+ gasStake.stakeId = passResult.stakeId;
94
+ gasStake.state = passStakeState;
95
+ }
96
+ } else if (!isFailedTxGasCharge && token$1 && pk) {
97
+ const decoded = JWT.decode(token$1) || {};
98
+ const sponsorAddress = toAddress(decoded.iss || "");
99
+ if (!sponsorAddress || !isFromPublicKey(sponsorAddress, pk)) {
100
+ const hdrErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key");
101
+ hdrErr._unauthenticatedExtraFailure = true;
102
+ return next(hdrErr);
103
+ }
104
+ if (await JWT.verify(token$1, pk, {
105
+ enforceTimestamp: !txTime,
106
+ tolerance: 5
107
+ })) {
108
+ const toleranceSec = 5;
109
+ const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
110
+ const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
111
+ const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
112
+ const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
113
+ const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
114
+ const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
115
+ const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
116
+ const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
117
+ if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
118
+ const sponsorState = await statedb.account?.get?.(sponsorAddress, {
119
+ ...context,
120
+ traceMigration: false
121
+ });
122
+ if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
123
+ const pkErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT signer public key does not match on-chain sponsor account");
124
+ pkErr._unauthenticatedExtraFailure = true;
125
+ return next(pkErr);
126
+ }
127
+ const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
128
+ const sponsorAddresses = getRelatedAddresses(sponsorState || { address: sponsorAddress });
129
+ const checkBlocked = async (checker, addr) => {
130
+ if (typeof checker?.isBlocked !== "function") return false;
131
+ if (await Promise.resolve(checker.isBlocked(addr))) return true;
132
+ return Boolean(await Promise.resolve(checker.isBlocked([addr])));
133
+ };
134
+ let isSponsorBlocked = false;
135
+ for (const addr of sponsorAddresses) if (await checkBlocked(context.filter, addr) || await checkBlocked(statedb.blacklist, addr)) {
136
+ isSponsorBlocked = true;
137
+ break;
138
+ }
139
+ if (!isSponsorMigrated && !isSponsorBlocked) {
140
+ const sponsorStakeId = toStakeAddress(sponsorAddress, sponsorAddress);
141
+ const isDirectMode = decoded.mode === "paymaster";
142
+ const sponsorStakeState = !isDirectMode ? await statedb.stake?.get?.(sponsorStakeId, context) : null;
143
+ const officialTok = config.token?.address || "";
144
+ 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);
145
+ const paymasterCheck = verifyPaymasterConstraints({
146
+ decoded,
147
+ tx: tx$1,
148
+ itx: context.itx,
149
+ txType,
150
+ totalGas: totalGas ?? ZERO
151
+ });
152
+ if (!paymasterCheck.valid) {
153
+ const pmErr = new CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`);
154
+ pmErr._strikeRecorded = true;
155
+ pmErr._unauthenticatedExtraFailure = true;
156
+ return next(pmErr);
157
+ }
158
+ if (paymasterCheck.isPaymasterDirectCharge) {
159
+ const txTargets = extractTransactionTargets(tx$1, context.itx, txType);
160
+ if ([
161
+ tx$1?.from,
162
+ tx$1?.delegator,
163
+ context.gasVault,
164
+ context.feeVault,
165
+ config.vaults?.txFee,
166
+ ...Array.isArray(config.vaults?.txGas) ? config.vaults.txGas : [],
167
+ ...Array.isArray(config.vaults?.txFees) ? config.vaults.txFees : [],
168
+ ...txTargets
169
+ ].filter(Boolean).some((candidate) => isSameDid(sponsorAddress, candidate) || sponsorAddress === candidate)) {
170
+ const aliasErr = new CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault");
171
+ aliasErr._unauthenticatedExtraFailure = true;
172
+ return next(aliasErr);
173
+ }
174
+ }
175
+ const selfStakeInfo = await resolveSignerSelfGasStake();
176
+ if (selfStakeInfo.valid) {
177
+ gasStake.owner = selfStakeInfo.owner;
178
+ gasStake.stakeId = selfStakeInfo.stakeId;
179
+ gasStake.state = selfStakeInfo.state;
180
+ } else if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else {
181
+ isThirdPartySponsor = true;
182
+ enforceSponsor3DEligibility = decoded.enforce3DEligibility === true || (config.transaction?.txGas)?.enforceSponsor3DEligibility === true;
183
+ isPaymasterDirectCharge = paymasterCheck.isPaymasterDirectCharge;
184
+ sponsorAccountState = sponsorState || null;
185
+ if (isPaymasterDirectCharge && sponsorAccountState) context.sponsorState = sponsorAccountState;
186
+ gasStake.owner = sponsorAddress;
187
+ gasStake.stakeId = sponsorStakeId;
188
+ if (sponsorStakeState) gasStake.state = sponsorStakeState;
189
+ }
190
+ }
191
+ } else console.warn(`Invalid gas payer header for: ${txHash}`);
192
+ }
30
193
  }
31
194
  if (!gasStake.owner && tx$1?.from) {
32
195
  const owner = tx$1.from;
33
196
  gasStake.owner = owner;
34
197
  gasStake.stakeId = toStakeAddress(owner, owner);
35
198
  }
36
- gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
37
- gasStake.valid = isGasStakeValid(gasStake.state, config);
199
+ if (!gasStake.state && gasStake.stakeId) gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
200
+ const eligibility = evaluateStakeForGasEligibility({
201
+ txType,
202
+ txSize: context._baseTxSize ?? context.txSize,
203
+ gasEstimate,
204
+ isFailedTxGasCharge,
205
+ isThirdPartySponsor,
206
+ enforceSponsor3DEligibility,
207
+ config
208
+ });
209
+ const baseStakeValid = !isPaymasterDirectCharge && isGasStakeValid(gasStake.state, config) && eligibility.eligible;
210
+ const effectiveTotalGas = totalGas ?? ZERO;
211
+ const warnActor = tx$1?.delegator || tx$1?.from || "";
212
+ if (!isFailedTxGasCharge && warnActor && resolveGasSecurityConfig(config).enabled) {
213
+ const status = getActorSecurityStatus({
214
+ actor: warnActor,
215
+ config,
216
+ statedb,
217
+ nowMs
218
+ });
219
+ if (status.warning) {
220
+ context.securityWarning = status.warning;
221
+ if (txHash) setTxSecurityWarningForHash(txHash, status.warning, statedb);
222
+ }
223
+ }
224
+ gasStake.valid = baseStakeValid;
38
225
  context.gasStake = gasStake;
226
+ context.gasEligibility = eligibility;
39
227
  debug("gasStake", gasStake, context.extra);
40
228
  const changes = {};
41
229
  let txCost = new BN(0);
230
+ let sponsorGasCost = new BN(0);
42
231
  const txFeeMap = config.transaction.txFee;
43
232
  const txFee = txType ? txFeeMap[txType] : void 0;
44
233
  if (!gasOnly && txFee) {
@@ -50,76 +239,143 @@ const ZERO = new BN(0);
50
239
  };
51
240
  context.feeVaultChange = changes.fee;
52
241
  }
53
- const totalGasBN = totalGas ?? ZERO;
242
+ const totalGasBN = effectiveTotalGas;
54
243
  if (!gasStake.valid && totalGasBN.gt(ZERO)) {
55
- txCost = txCost.add(totalGasBN);
56
244
  changes.gas = {
57
245
  address: config.token.address,
58
246
  value: totalGasBN.toString(10)
59
247
  };
60
248
  context.gasVaultChange = changes.gas;
249
+ if (isPaymasterDirectCharge && !isFailedTxGasCharge) sponsorGasCost = totalGasBN;
250
+ else txCost = txCost.add(totalGasBN);
61
251
  }
62
252
  if (changes.fee) if (config.vaults.txFees?.length) {
63
253
  const feeIndex = hexToNumber(txHash.slice(-8)) % config.vaults.txFees.length;
64
254
  context.feeVault = config.vaults.txFees[feeIndex];
65
255
  } else context.feeVault = config.vaults.txFee;
256
+ if (changes.gas && !context.gasVault) {
257
+ if (config.vaults.txGas?.length) {
258
+ const gasIndex = hexToNumber(txHash.slice(-8)) % config.vaults.txGas.length;
259
+ context.gasVault = config.vaults.txGas[gasIndex];
260
+ } else if (config.vaults.txFee) context.gasVault = config.vaults.txFee;
261
+ }
262
+ if (sponsorGasCost.gt(ZERO)) {
263
+ const sponsorBalance = new BN(sponsorAccountState?.tokens?.[config.token.address] || 0);
264
+ if (!sponsorAccountState) {
265
+ const noSponsorErr = new CustomError("INVALID_GAS_PAYER", `Paymaster sponsor ${gasStake.owner} does not exist on chain`);
266
+ noSponsorErr._unauthenticatedExtraFailure = true;
267
+ return next(noSponsorErr);
268
+ }
269
+ if (sponsorBalance.lt(sponsorGasCost)) {
270
+ const sponsorFundErr = new CustomError("INSUFFICIENT_FUND", `Insufficient fund in paymaster sponsor ${sponsorAccountState.address} to pay gas`);
271
+ sponsorFundErr._unauthenticatedExtraFailure = true;
272
+ return next(sponsorFundErr);
273
+ }
274
+ }
66
275
  let isCostCharged = false;
67
- if (txCost.gt(ZERO)) {
276
+ if (txCost.gt(ZERO) || sponsorGasCost.gt(ZERO)) {
68
277
  const expected = new BN(gasEstimate?.payment || 0).add(txCost);
69
278
  const actual = new BN(senderState?.tokens?.[config.token.address] || 0);
70
- if (senderState && actual.gte(expected)) {
279
+ if (txCost.eq(ZERO) || Boolean(senderState) && actual.gte(expected)) {
71
280
  isCostCharged = true;
72
- context.senderUpdates = applyTokenUpdates([{
73
- address: config.token.address,
74
- value: txCost.toString(10)
75
- }], senderState, "sub");
76
- context.senderChange = {
77
- address: senderState.address,
78
- token: config.token.address,
79
- delta: `-${txCost.toString(10)}`
80
- };
281
+ if (txCost.gt(ZERO) && senderState) {
282
+ context.senderUpdates = applyTokenUpdates([{
283
+ address: config.token.address,
284
+ value: txCost.toString(10)
285
+ }], senderState, "sub");
286
+ context.senderChange = {
287
+ address: senderState.address,
288
+ token: config.token.address,
289
+ delta: `-${txCost.toString(10)}`
290
+ };
291
+ } else {
292
+ context.senderUpdates = {};
293
+ context.senderChange = null;
294
+ }
81
295
  debug({
82
296
  changes,
83
297
  senderUpdates: context.senderUpdates
84
298
  });
85
299
  context.updateVaults = async function updateVaults() {
86
- const [feeVaultState, gasVaultState] = await Promise.all([changes.fee && context.feeVault ? statedb.account.get(context.feeVault, context) : null, changes.gas && context.gasVault ? statedb.account.get(context.gasVault, context) : null]);
87
- const [newFeeVaultState, newGasVaultState] = await Promise.all([changes.fee && feeVaultState ? statedb.account.update(feeVaultState.address, account.update(feeVaultState, applyTokenUpdates([changes.fee], feeVaultState, "add"), context), context) : null, changes.gas && gasVaultState ? statedb.account.update(gasVaultState.address, account.update(gasVaultState, applyTokenUpdates([changes.gas], gasVaultState, "add"), context), context) : null]);
88
- if (newFeeVaultState) context.feeVaultState = newFeeVaultState;
89
- if (newGasVaultState) context.gasVaultState = newGasVaultState;
300
+ if (context.gasPaid) return;
301
+ if (sponsorGasCost.gt(ZERO) && sponsorAccountState && changes.gas) {
302
+ const latestSponsor = await statedb.account.get(sponsorAccountState.address, context) || sponsorAccountState;
303
+ const tokenDelta = applyTokenUpdates([changes.gas], latestSponsor, "sub");
304
+ let updatedSponsorPayload;
305
+ try {
306
+ updatedSponsorPayload = account.update(latestSponsor, tokenDelta, context);
307
+ } catch {
308
+ updatedSponsorPayload = {
309
+ ...latestSponsor,
310
+ ...tokenDelta
311
+ };
312
+ }
313
+ const nextSponsorState = await statedb.account.update(latestSponsor.address, updatedSponsorPayload, context);
314
+ if (nextSponsorState && typeof nextSponsorState === "object") nextSponsorState._retrievedAt = Date.now() + 1;
315
+ context.sponsorState = nextSponsorState;
316
+ }
317
+ let feeVaultState = null;
318
+ let gasVaultState = null;
319
+ if (changes.fee && changes.gas && context.feeVault && context.gasVault && context.feeVault === context.gasVault) {
320
+ const sharedVaultState = await statedb.account.get(context.feeVault, context);
321
+ feeVaultState = sharedVaultState;
322
+ gasVaultState = sharedVaultState;
323
+ if (sharedVaultState) {
324
+ const combinedState = await statedb.account.update(sharedVaultState.address, account.update(sharedVaultState, applyTokenUpdates([changes.fee, changes.gas], sharedVaultState, "add"), context), context);
325
+ context.feeVaultState = combinedState;
326
+ context.gasVaultState = combinedState;
327
+ }
328
+ } else {
329
+ [feeVaultState, gasVaultState] = await Promise.all([changes.fee && context.feeVault ? statedb.account.get(context.feeVault, context) : null, changes.gas && context.gasVault ? statedb.account.get(context.gasVault, context) : null]);
330
+ const [newFeeVaultState, newGasVaultState] = await Promise.all([changes.fee && feeVaultState ? statedb.account.update(feeVaultState.address, account.update(feeVaultState, applyTokenUpdates([changes.fee], feeVaultState, "add"), context), context) : null, changes.gas && gasVaultState ? statedb.account.update(gasVaultState.address, account.update(gasVaultState, applyTokenUpdates([changes.gas], gasVaultState, "add"), context), context) : null]);
331
+ if (newFeeVaultState) context.feeVaultState = newFeeVaultState;
332
+ if (newGasVaultState) context.gasVaultState = newGasVaultState;
333
+ }
90
334
  context.updatedAccounts = context.updatedAccounts || [];
91
335
  if (changes.fee && feeVaultState) {
92
- context.updatedAccounts.push({
93
- address: feeVaultState.address,
94
- token: config.token.address,
95
- delta: changes.fee.value,
96
- action: "fee"
97
- });
98
- if (attachSenderChanges) context.updatedAccounts.push({
99
- address: senderState.address,
100
- token: config.token.address,
101
- delta: `-${changes.fee.value}`,
102
- action: "fee"
103
- });
336
+ if (!Boolean(attachSenderChanges && senderState && isSameDid(senderState.address, feeVaultState.address))) {
337
+ context.updatedAccounts.push({
338
+ address: feeVaultState.address,
339
+ token: config.token.address,
340
+ delta: changes.fee.value,
341
+ action: "fee"
342
+ });
343
+ if (attachSenderChanges && senderState) context.updatedAccounts.push({
344
+ address: senderState.address,
345
+ token: config.token.address,
346
+ delta: `-${changes.fee.value}`,
347
+ action: "fee"
348
+ });
349
+ }
104
350
  }
105
351
  if (changes.gas && gasVaultState) {
106
- context.updatedAccounts.push({
107
- address: gasVaultState.address,
108
- token: config.token.address,
109
- delta: changes.gas.value,
110
- action: "gas"
111
- });
112
- if (attachSenderChanges) context.updatedAccounts.push({
113
- address: senderState.address,
114
- token: config.token.address,
115
- delta: `-${changes.gas.value}`,
116
- action: "gas"
117
- });
352
+ const gasPayerAddress = sponsorGasCost.gt(ZERO) && sponsorAccountState ? sponsorAccountState.address : attachSenderChanges && senderState ? senderState.address : "";
353
+ if (!gasPayerAddress || !isSameDid(gasPayerAddress, gasVaultState.address)) {
354
+ context.updatedAccounts.push({
355
+ address: gasVaultState.address,
356
+ token: config.token.address,
357
+ delta: changes.gas.value,
358
+ action: "gas"
359
+ });
360
+ if (gasPayerAddress) context.updatedAccounts.push({
361
+ address: gasPayerAddress,
362
+ token: config.token.address,
363
+ delta: `-${changes.gas.value}`,
364
+ action: "gas"
365
+ });
366
+ }
118
367
  }
119
368
  context.gasPaid = true;
120
369
  };
121
- } else if (!senderState) return next(new CustomError("INVALID_GAS_PAYER", `Gas payer ${tx$1.from} does not exist on chain`));
122
- else if (throwOnInsufficientFund) return next(new CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${senderState.address || tx$1.from}, expected ${fromUnitToToken(expected, config.token.decimal)} ${config.token.symbol}, got ${fromUnitToToken(actual, config.token.decimal)} ${config.token.symbol}`));
370
+ } else if (!senderState) {
371
+ const noSenderErr = new CustomError("INVALID_GAS_PAYER", `Gas payer ${tx$1.from} does not exist on chain`);
372
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) noSenderErr._unauthenticatedExtraFailure = true;
373
+ return next(noSenderErr);
374
+ } else if (throwOnInsufficientFund) {
375
+ const senderFundErr = new CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${senderState.address || tx$1.from}, expected ${fromUnitToToken(expected, config.token.decimal)} ${config.token.symbol}, got ${fromUnitToToken(actual, config.token.decimal)} ${config.token.symbol}`);
376
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) senderFundErr._unauthenticatedExtraFailure = true;
377
+ return next(senderFundErr);
378
+ }
123
379
  }
124
380
  if (!isCostCharged) {
125
381
  context.senderUpdates = {};