@ocap/tx-protocols 1.31.0 → 1.31.2
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/esm/bridge-release-crypto.d.mts +39 -0
- package/esm/bridge-release-crypto.mjs +88 -0
- package/esm/bridge-release-window.d.mts +47 -0
- package/esm/bridge-release-window.mjs +62 -0
- package/esm/bridge-reserve.d.mts +24 -0
- package/esm/bridge-reserve.mjs +41 -0
- package/esm/execute.d.mts +5 -3
- package/esm/execute.mjs +593 -21
- package/esm/gas-security-guard.d.mts +7 -2
- package/esm/gas-security-guard.mjs +25 -16
- package/esm/index.d.mts +38 -19
- package/esm/index.mjs +7 -3
- package/esm/pipes/ensure-cost.mjs +36 -10
- package/esm/pipes/write-ledger.d.mts +2 -2
- package/esm/pipes/write-ledger.mjs +6 -3
- package/esm/protocols/account/delegate.mjs +6 -4
- package/esm/protocols/account/migrate.mjs +5 -3
- package/esm/protocols/account/revoke-delegate.mjs +5 -3
- package/esm/protocols/asset/acquire-v2.mjs +3 -1
- package/esm/protocols/asset/acquire-v3.mjs +4 -2
- package/esm/protocols/asset/consume.mjs +3 -1
- package/esm/protocols/asset/create.mjs +4 -2
- package/esm/protocols/asset/mint.mjs +4 -2
- package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
- package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
- package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
- package/esm/protocols/asset/update.mjs +4 -2
- package/esm/protocols/bridge/release.d.mts +34 -0
- package/esm/protocols/bridge/release.mjs +385 -0
- package/esm/protocols/factory/create.mjs +4 -2
- package/esm/protocols/governance/claim-stake.mjs +35 -11
- package/esm/protocols/governance/return-stake.mjs +4 -2
- package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
- package/esm/protocols/governance/revoke-ledger.mjs +179 -0
- package/esm/protocols/governance/revoke-stake.d.mts +7 -2
- package/esm/protocols/governance/revoke-stake.mjs +58 -29
- package/esm/protocols/governance/slash-stake.mjs +14 -4
- package/esm/protocols/governance/stake.mjs +6 -4
- package/esm/protocols/rollup/bridge-create.d.mts +13 -0
- package/esm/protocols/rollup/bridge-create.mjs +206 -0
- package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
- package/esm/protocols/rollup/bridge-membership.mjs +154 -0
- package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
- package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
- package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
- package/esm/protocols/rollup/bridge-v2.mjs +219 -0
- package/esm/protocols/rollup/claim-reward.mjs +4 -2
- package/esm/protocols/rollup/close.d.mts +2 -1
- package/esm/protocols/rollup/close.mjs +59 -6
- package/esm/protocols/rollup/create-block.mjs +4 -2
- package/esm/protocols/rollup/create.d.mts +3 -0
- package/esm/protocols/rollup/create.mjs +45 -6
- package/esm/protocols/rollup/join.d.mts +2 -1
- package/esm/protocols/rollup/join.mjs +31 -23
- package/esm/protocols/rollup/leave.d.mts +2 -1
- package/esm/protocols/rollup/leave.mjs +32 -24
- package/esm/protocols/rollup/migrate.d.mts +2 -1
- package/esm/protocols/rollup/migrate.mjs +19 -10
- package/esm/protocols/rollup/pause.d.mts +4 -1
- package/esm/protocols/rollup/pause.mjs +50 -6
- package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
- package/esm/protocols/rollup/resume.d.mts +2 -1
- package/esm/protocols/rollup/resume.mjs +26 -6
- package/esm/protocols/rollup/update.d.mts +5 -1
- package/esm/protocols/rollup/update.mjs +56 -9
- package/esm/protocols/token/create.mjs +4 -2
- package/esm/protocols/token/deposit-v2.mjs +5 -3
- package/esm/protocols/token/withdraw-v2.mjs +5 -3
- package/esm/protocols/token-factory/burn.mjs +4 -2
- package/esm/protocols/token-factory/create.mjs +8 -4
- package/esm/protocols/token-factory/mint.mjs +4 -2
- package/esm/protocols/token-factory/update.mjs +20 -5
- package/esm/protocols/trade/exchange-v2.d.mts +5 -1
- package/esm/protocols/trade/exchange-v2.mjs +89 -4
- package/esm/protocols/trade/transfer-v2.mjs +15 -4
- package/esm/protocols/trade/transfer-v3.mjs +5 -3
- package/esm/stateless-prefix.d.mts +16 -0
- package/esm/stateless-prefix.mjs +82 -0
- package/esm/tx-timer.d.mts +1 -1
- package/esm/tx-timer.mjs +1 -1
- package/esm/util.mjs +2 -2
- package/lib/bridge-release-crypto.cjs +93 -0
- package/lib/bridge-release-crypto.d.cts +39 -0
- package/lib/bridge-release-window.cjs +69 -0
- package/lib/bridge-release-window.d.cts +47 -0
- package/lib/bridge-reserve.cjs +45 -0
- package/lib/bridge-reserve.d.cts +24 -0
- package/lib/execute.cjs +594 -19
- package/lib/execute.d.cts +4 -2
- package/lib/gas-security-guard.cjs +25 -16
- package/lib/gas-security-guard.d.cts +7 -2
- package/lib/index.cjs +10 -1
- package/lib/index.d.cts +37 -18
- package/lib/pipes/ensure-cost.cjs +37 -11
- package/lib/pipes/write-ledger.cjs +6 -3
- package/lib/pipes/write-ledger.d.cts +2 -2
- package/lib/protocols/account/delegate.cjs +6 -4
- package/lib/protocols/account/migrate.cjs +5 -3
- package/lib/protocols/account/revoke-delegate.cjs +5 -3
- package/lib/protocols/asset/acquire-v2.cjs +3 -1
- package/lib/protocols/asset/acquire-v3.cjs +4 -2
- package/lib/protocols/asset/consume.cjs +3 -1
- package/lib/protocols/asset/create.cjs +4 -2
- package/lib/protocols/asset/mint.cjs +4 -2
- package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
- package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
- package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
- package/lib/protocols/asset/update.cjs +4 -2
- package/lib/protocols/bridge/release.cjs +390 -0
- package/lib/protocols/bridge/release.d.cts +34 -0
- package/lib/protocols/factory/create.cjs +4 -2
- package/lib/protocols/governance/claim-stake.cjs +35 -11
- package/lib/protocols/governance/return-stake.cjs +4 -2
- package/lib/protocols/governance/revoke-ledger.cjs +184 -0
- package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
- package/lib/protocols/governance/revoke-stake.cjs +58 -29
- package/lib/protocols/governance/revoke-stake.d.cts +7 -2
- package/lib/protocols/governance/slash-stake.cjs +14 -4
- package/lib/protocols/governance/stake.cjs +6 -4
- package/lib/protocols/rollup/bridge-create.cjs +209 -0
- package/lib/protocols/rollup/bridge-create.d.cts +13 -0
- package/lib/protocols/rollup/bridge-membership.cjs +157 -0
- package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
- package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
- package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
- package/lib/protocols/rollup/bridge-v2.cjs +244 -0
- package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
- package/lib/protocols/rollup/claim-reward.cjs +4 -2
- package/lib/protocols/rollup/close.cjs +59 -6
- package/lib/protocols/rollup/close.d.cts +2 -1
- package/lib/protocols/rollup/create-block.cjs +4 -2
- package/lib/protocols/rollup/create.cjs +45 -6
- package/lib/protocols/rollup/create.d.cts +3 -0
- package/lib/protocols/rollup/join.cjs +31 -23
- package/lib/protocols/rollup/join.d.cts +2 -1
- package/lib/protocols/rollup/leave.cjs +32 -24
- package/lib/protocols/rollup/leave.d.cts +2 -1
- package/lib/protocols/rollup/migrate.cjs +19 -10
- package/lib/protocols/rollup/migrate.d.cts +2 -1
- package/lib/protocols/rollup/pause.cjs +50 -6
- package/lib/protocols/rollup/pause.d.cts +4 -1
- package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
- package/lib/protocols/rollup/resume.cjs +26 -6
- package/lib/protocols/rollup/resume.d.cts +2 -1
- package/lib/protocols/rollup/update.cjs +56 -9
- package/lib/protocols/rollup/update.d.cts +5 -1
- package/lib/protocols/token/create.cjs +4 -2
- package/lib/protocols/token/deposit-v2.cjs +5 -3
- package/lib/protocols/token/withdraw-v2.cjs +5 -3
- package/lib/protocols/token-factory/burn.cjs +4 -2
- package/lib/protocols/token-factory/create.cjs +8 -4
- package/lib/protocols/token-factory/mint.cjs +4 -2
- package/lib/protocols/token-factory/update.cjs +20 -5
- package/lib/protocols/trade/exchange-v2.cjs +90 -3
- package/lib/protocols/trade/exchange-v2.d.cts +5 -1
- package/lib/protocols/trade/transfer-v2.cjs +15 -4
- package/lib/protocols/trade/transfer-v3.cjs +5 -3
- package/lib/stateless-prefix.cjs +88 -0
- package/lib/stateless-prefix.d.cts +16 -0
- package/lib/tx-timer.cjs +1 -1
- package/lib/tx-timer.d.cts +1 -1
- package/lib/util.cjs +2 -2
- package/package.json +16 -16
- package/tools/fixtures.ts +9 -4
package/esm/execute.mjs
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { assertBridgeReserveNotActor, assertBridgeReserveNotSponsor } from "./bridge-reserve.mjs";
|
|
2
|
+
import { classifyErrorStrikeCategory, evaluateStakeForGasEligibility, extractTransactionTargets, normalizeShortTxType, recordActorSecurityStrike, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
|
|
3
|
+
import { getRewardLocker, isGasStakeAddress, isGasStakeInput, isGasStakeValid } from "./util.mjs";
|
|
2
4
|
import ensure_cost_default from "./pipes/ensure-cost.mjs";
|
|
3
5
|
import ensure_gas_default from "./pipes/ensure-gas.mjs";
|
|
4
6
|
import { WriteLedger } from "./pipes/write-ledger.mjs";
|
|
7
|
+
import { assertStatelessTxRules } from "./stateless-prefix.mjs";
|
|
5
8
|
import { TxTimer } from "./tx-timer.mjs";
|
|
6
|
-
import { toTypeInfo } from "@arcblock/did";
|
|
7
|
-
import { toDelegateAddress } from "@arcblock/did-util";
|
|
8
9
|
import { toTxHash, types } from "@ocap/mcrypto";
|
|
9
|
-
import {
|
|
10
|
-
import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
|
|
11
|
-
import { BN, isSameDid } from "@ocap/util";
|
|
10
|
+
import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, prepareBridgeReserveGate, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
|
|
12
11
|
import { CustomError } from "@ocap/util/lib/error";
|
|
13
12
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
13
|
+
import { isFromPublicKey, toAddress, toTypeInfo } from "@arcblock/did";
|
|
14
|
+
import { toDelegateAddress, toStakeAddress } from "@arcblock/did-util";
|
|
15
|
+
import * as JWT from "@arcblock/jwt";
|
|
16
|
+
import { account, evidence, parseNonceBn } from "@ocap/state";
|
|
17
|
+
import { BN, fromTokenToUnit, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
|
|
14
18
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
15
19
|
import camelCase from "lodash/camelCase.js";
|
|
16
20
|
import cloneDeep from "lodash/cloneDeep.js";
|
|
@@ -19,6 +23,20 @@ import merge from "lodash/merge.js";
|
|
|
19
23
|
import pick from "lodash/pick.js";
|
|
20
24
|
|
|
21
25
|
//#region src/execute.ts
|
|
26
|
+
const ZERO = new BN(0);
|
|
27
|
+
const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = pipes.PreFlightWaf.SNAPSHOT_SYMBOL || Symbol.for("@ocap/tx-pipeline/preFlightVerifiedSnapshot");
|
|
28
|
+
const tryApplyPreFlightVerifiedSnapshot = (context) => {
|
|
29
|
+
const fn = pipes.PreFlightWaf.tryApplyVerifiedSnapshot;
|
|
30
|
+
return typeof fn === "function" ? fn(context) : false;
|
|
31
|
+
};
|
|
32
|
+
function isMatchingAccountPublicKey(onChainPk, headerPk) {
|
|
33
|
+
if (onChainPk === headerPk) return true;
|
|
34
|
+
try {
|
|
35
|
+
const headerBuf = toBuffer(headerPk);
|
|
36
|
+
if (toBase58(headerBuf) === onChainPk || toBase64(headerBuf) === onChainPk) return true;
|
|
37
|
+
} catch {}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
22
40
|
const ensureTxGas = ensure_gas_default(() => ({
|
|
23
41
|
create: 0,
|
|
24
42
|
update: 2
|
|
@@ -65,6 +83,29 @@ const MULTISIG_DELEGATION_TX_TYPES = new Set([
|
|
|
65
83
|
"fg:t:exchange_v2",
|
|
66
84
|
"fg:t:transfer_v3"
|
|
67
85
|
]);
|
|
86
|
+
/** Zero-stake onboarding transaction types permitted from a non-existent sender within free-gas size ceilings. */
|
|
87
|
+
const ONBOARDING_FREE_TX_TYPES = new Set([
|
|
88
|
+
"declare",
|
|
89
|
+
"poke",
|
|
90
|
+
"faucet"
|
|
91
|
+
]);
|
|
92
|
+
/**
|
|
93
|
+
* Transaction types whose protocol pipeline uses `status: 'OK'` on `ExtractState({ from: 'tx.from', to: 'senderState' })`
|
|
94
|
+
* and can therefore execute when `tx.from` has no `statedb.account` row (and is not an existing `ROLE_ASSET`).
|
|
95
|
+
*/
|
|
96
|
+
const NON_EXISTENT_SENDER_CAPABLE_TX_TYPES = new Set([
|
|
97
|
+
"declare",
|
|
98
|
+
"poke",
|
|
99
|
+
"faucet",
|
|
100
|
+
"delegate",
|
|
101
|
+
"account_migrate",
|
|
102
|
+
"acquire_asset_v3",
|
|
103
|
+
"stake",
|
|
104
|
+
"burn_token",
|
|
105
|
+
"mint_token",
|
|
106
|
+
"deposit_token_v2",
|
|
107
|
+
"transfer_v3"
|
|
108
|
+
]);
|
|
68
109
|
const shouldPersistTx = (err, context) => {
|
|
69
110
|
if (!err) return true;
|
|
70
111
|
if (!get(err, "props.persist")) return false;
|
|
@@ -121,6 +162,20 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
121
162
|
resolve();
|
|
122
163
|
})).catch(reject);
|
|
123
164
|
});
|
|
165
|
+
/**
|
|
166
|
+
* Append the tx to the verifiable ledger at the point where its tx state is written (#1419).
|
|
167
|
+
*
|
|
168
|
+
* Invariant: a ledger row exists only for a tx that also gets a `statedb.tx` row, i.e. a successful tx or a
|
|
169
|
+
* failed tx that went through the failed-tx gas charge (`ensureGasFeePaid`). The append used to run in the
|
|
170
|
+
* pre-execute pipeline, ahead of the protocol runner, so every protocol-phase rejection that is not persisted
|
|
171
|
+
* (itx schema errors, `VerifyInfo` defaults, every `VerifyDelegation` rejection, multisig signature failures,
|
|
172
|
+
* a failed-tx gas charge nobody can pay) left an uncharged row in the append-only ledger.
|
|
173
|
+
*
|
|
174
|
+
* The append still precedes `statedb.tx.create` and the statedb commit, so the ledger stays write-ahead of the
|
|
175
|
+
* committed state, and `WriteLedger` is idempotent per context (`ledgerSequence`), so `runAsLambda` retries
|
|
176
|
+
* reuse the sequence allocated by the first attempt (#973).
|
|
177
|
+
*/
|
|
178
|
+
const appendLedgerEntry = (context) => runSinglePipe(WriteLedger, context);
|
|
124
179
|
const hasCommittedUnsignedTx = async (context) => {
|
|
125
180
|
if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return false;
|
|
126
181
|
const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
|
|
@@ -156,16 +211,442 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
156
211
|
* - Sender migrated (statedb resolves `tx.from` to its successor): reject like
|
|
157
212
|
* VerifyAccountMigration, but before the ledger write.
|
|
158
213
|
*/
|
|
214
|
+
/**
|
|
215
|
+
* Pre-ledger admission check for non-existent senders (#1359).
|
|
216
|
+
*
|
|
217
|
+
* When `tx.from` has no account in `statedb.account`, it cannot pay direct gas or service fees
|
|
218
|
+
* from `senderState`. Rejecting unpaid or unexecutable transactions from non-existent senders before
|
|
219
|
+
* `WriteLedger` prevents unauthenticated actors from appending uncompensated entries to the immutable
|
|
220
|
+
* ledger for free.
|
|
221
|
+
*/
|
|
222
|
+
const estimatePreLedgerGasOps = async (context, shortTxType, from, statedb, isExistingAssetSender) => {
|
|
223
|
+
const itx = context.itx || {};
|
|
224
|
+
const accountStore = statedb?.account;
|
|
225
|
+
const inputs = getListField(itx, "inputs") || [];
|
|
226
|
+
const uniqueInputOwners = Array.from(new Set(inputs.map((inp) => typeof inp?.owner === "string" ? inp.owner : "").filter(Boolean)));
|
|
227
|
+
const uniqueInputAssets = Array.from(new Set(inputs.flatMap((inp) => getListField(inp, "assets") || []).filter((a) => typeof a === "string" && a.length > 0)));
|
|
228
|
+
switch (shortTxType) {
|
|
229
|
+
case "declare": return {
|
|
230
|
+
create: 1,
|
|
231
|
+
update: 0,
|
|
232
|
+
isGasSelfStakeTx: false
|
|
233
|
+
};
|
|
234
|
+
case "poke": return {
|
|
235
|
+
create: 1,
|
|
236
|
+
update: 1,
|
|
237
|
+
isGasSelfStakeTx: false
|
|
238
|
+
};
|
|
239
|
+
case "faucet": return {
|
|
240
|
+
create: 0,
|
|
241
|
+
update: 1,
|
|
242
|
+
isGasSelfStakeTx: false
|
|
243
|
+
};
|
|
244
|
+
case "account_migrate": return {
|
|
245
|
+
create: 2,
|
|
246
|
+
update: 0,
|
|
247
|
+
isGasSelfStakeTx: false
|
|
248
|
+
};
|
|
249
|
+
case "delegate": {
|
|
250
|
+
const result = {
|
|
251
|
+
create: 0,
|
|
252
|
+
update: 1,
|
|
253
|
+
isGasSelfStakeTx: false
|
|
254
|
+
};
|
|
255
|
+
const toAddr = typeof itx.to === "string" ? itx.to : "";
|
|
256
|
+
if (Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
|
|
257
|
+
else result.create += 1;
|
|
258
|
+
const delAddr = typeof itx.address === "string" ? itx.address : "";
|
|
259
|
+
if (Boolean(delAddr) && typeof statedb?.delegation?.get === "function" && Boolean(await statedb.delegation.get(delAddr, context))) result.update += 1;
|
|
260
|
+
else result.create += 1;
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
case "deposit_token_v2": {
|
|
264
|
+
const result = {
|
|
265
|
+
create: 2,
|
|
266
|
+
update: 1,
|
|
267
|
+
isGasSelfStakeTx: false
|
|
268
|
+
};
|
|
269
|
+
const proposer = typeof itx.proposer === "string" ? itx.proposer : "";
|
|
270
|
+
const toAddr = typeof itx.to === "string" ? itx.to : "";
|
|
271
|
+
if (proposer === from && toAddr && toAddr !== from) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
|
|
272
|
+
else result.create += 1;
|
|
273
|
+
const rollupAddr = typeof itx.rollup === "string" ? itx.rollup : "";
|
|
274
|
+
if (Boolean(rollupAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(getRewardLocker(rollupAddr), context))) result.update += 1;
|
|
275
|
+
else result.create += 1;
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
case "acquire_asset_v3": {
|
|
279
|
+
const result = {
|
|
280
|
+
create: 1,
|
|
281
|
+
update: 2 + uniqueInputOwners.length + uniqueInputAssets.length,
|
|
282
|
+
isGasSelfStakeTx: false
|
|
283
|
+
};
|
|
284
|
+
const ownerAddr = typeof itx.owner === "string" ? itx.owner : "";
|
|
285
|
+
if (!(Boolean(ownerAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(ownerAddr, context)))) result.create += 1;
|
|
286
|
+
return result;
|
|
287
|
+
}
|
|
288
|
+
case "transfer_v3": {
|
|
289
|
+
const result = {
|
|
290
|
+
create: 1,
|
|
291
|
+
update: uniqueInputOwners.length + uniqueInputAssets.length,
|
|
292
|
+
isGasSelfStakeTx: false
|
|
293
|
+
};
|
|
294
|
+
const outputs = getListField(itx, "outputs") || [];
|
|
295
|
+
const uniqueReceivers = Array.from(new Set(outputs.map((out) => typeof out?.owner === "string" ? out.owner : "").filter(Boolean)));
|
|
296
|
+
for (const r of uniqueReceivers) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(r, context))) result.update += 1;
|
|
297
|
+
else result.create += 1;
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
case "mint_token":
|
|
301
|
+
case "burn_token": {
|
|
302
|
+
const result = {
|
|
303
|
+
create: 1,
|
|
304
|
+
update: 2 + uniqueInputOwners.length,
|
|
305
|
+
isGasSelfStakeTx: false
|
|
306
|
+
};
|
|
307
|
+
const receiverAddr = typeof itx.receiver === "string" ? itx.receiver : "";
|
|
308
|
+
if (Boolean(receiverAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(receiverAddr, context))) result.update += 1;
|
|
309
|
+
else result.create += 1;
|
|
310
|
+
if (itx.reserveFee && /^\d+$/.test(String(itx.reserveFee)) && new BN(String(itx.reserveFee)).gt(ZERO)) result.update += 1;
|
|
311
|
+
return result;
|
|
312
|
+
}
|
|
313
|
+
case "stake": {
|
|
314
|
+
const stakeAddr = typeof itx.address === "string" ? itx.address : "";
|
|
315
|
+
const normalizedInputs = inputs.map((inp) => ({
|
|
316
|
+
assetsList: getListField(inp, "assets") || [],
|
|
317
|
+
tokensList: getListField(inp, "tokens") || []
|
|
318
|
+
}));
|
|
319
|
+
const officialTok = context.config?.token?.address || "";
|
|
320
|
+
if (stakeAddr && officialTok && isGasStakeAddress(from, stakeAddr) && isGasStakeInput(normalizedInputs, officialTok)) return {
|
|
321
|
+
create: 0,
|
|
322
|
+
update: 0,
|
|
323
|
+
isGasSelfStakeTx: true
|
|
324
|
+
};
|
|
325
|
+
const result = {
|
|
326
|
+
create: 1,
|
|
327
|
+
update: uniqueInputOwners.length + uniqueInputAssets.length,
|
|
328
|
+
isGasSelfStakeTx: false
|
|
329
|
+
};
|
|
330
|
+
if (Boolean(stakeAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(stakeAddr, context))) result.update += 1;
|
|
331
|
+
else result.create += 1;
|
|
332
|
+
return result;
|
|
333
|
+
}
|
|
334
|
+
default:
|
|
335
|
+
if (shortTxType === "create_asset" || shortTxType === "create_factory" || shortTxType === "create_token" || shortTxType === "create_token_factory" || shortTxType === "create_rollup") return {
|
|
336
|
+
create: 1,
|
|
337
|
+
update: 2,
|
|
338
|
+
isGasSelfStakeTx: false
|
|
339
|
+
};
|
|
340
|
+
if (shortTxType === "transfer_v2" || shortTxType === "transfer") {
|
|
341
|
+
const toAddr = typeof itx.to === "string" ? itx.to : "";
|
|
342
|
+
const hasReceiver = Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context));
|
|
343
|
+
const assetsList = getListField(itx, "assets") || [];
|
|
344
|
+
return {
|
|
345
|
+
create: hasReceiver ? 0 : 1,
|
|
346
|
+
update: (isExistingAssetSender ? 1 : 0) + (hasReceiver ? 1 : 0) + assetsList.length,
|
|
347
|
+
isGasSelfStakeTx: false
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
create: 0,
|
|
352
|
+
update: 2,
|
|
353
|
+
isGasSelfStakeTx: false
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const assertNonExistentSenderAdmissible = async (context) => {
|
|
358
|
+
const from = context.tx?.from;
|
|
359
|
+
const statedb = context.statedb;
|
|
360
|
+
const accountStore = statedb?.account;
|
|
361
|
+
if (!from || !context.ledger || typeof accountStore?.get !== "function") return;
|
|
362
|
+
if (context.tx?.delegator) {
|
|
363
|
+
if (!await accountStore.get(context.tx.delegator, context)) throw new CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: false });
|
|
364
|
+
}
|
|
365
|
+
const isExistingAssetSender = toTypeInfo(from).role === types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(from, context));
|
|
366
|
+
const config = context.config;
|
|
367
|
+
const txType = context.txType;
|
|
368
|
+
const shortTxType = normalizeShortTxType(txType);
|
|
369
|
+
const assertProtocolAdmissibleWithoutSenderState = async () => {
|
|
370
|
+
if (!isExistingAssetSender && !NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
|
|
371
|
+
if (shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token" || shortTxType === "mint_token" || shortTxType === "acquire_asset_v3") {
|
|
372
|
+
const inputs = getListField(context.itx, "inputs") || [];
|
|
373
|
+
if ((shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token") && inputs.length === 0) throw new CustomError("INVALID_TX", "Invalid itx: inputs must not be empty", { persist: false });
|
|
374
|
+
for (const inp of inputs) {
|
|
375
|
+
if (!inp?.owner) throw new CustomError("INVALID_TX", "Invalid itx: input owner is required", { persist: false });
|
|
376
|
+
if (!(Boolean(await accountStore.get(inp.owner, context)) || toTypeInfo(inp.owner).role === types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(inp.owner, context)))) throw new CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${inp.owner}`, { persist: false });
|
|
377
|
+
}
|
|
378
|
+
} else if (shortTxType === "deposit_token_v2") {
|
|
379
|
+
const signatures = getListField(context.tx, "signatures") || [];
|
|
380
|
+
if (signatures.length === 0) throw new CustomError("INVALID_TX", "itx.proposer must exist in signatures", { persist: false });
|
|
381
|
+
for (const sig of signatures) if (!sig?.signer || !await accountStore.get(sig.signer, context)) throw new CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${sig?.signer || ""}`, { persist: false });
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
const txFeeMap = config?.transaction?.txFee || {};
|
|
385
|
+
const rawTxFee = txType ? txFeeMap[txType] : void 0;
|
|
386
|
+
const feeCost = typeof rawTxFee === "number" && rawTxFee > 0 && Boolean(config?.token?.decimal) ? fromTokenToUnit(rawTxFee, config.token.decimal) : ZERO;
|
|
387
|
+
const txGasCfg = config?.transaction?.txGas;
|
|
388
|
+
const gasPriceRaw = txGasCfg?.price;
|
|
389
|
+
const gasPrice = txGasCfg?.enabled !== false && gasPriceRaw !== void 0 && gasPriceRaw !== null && /^\d+$/.test(String(gasPriceRaw)) ? new BN(String(gasPriceRaw)) : ZERO;
|
|
390
|
+
const estimatedOps = await estimatePreLedgerGasOps(context, shortTxType, from, statedb, isExistingAssetSender);
|
|
391
|
+
const gasEstimate = {
|
|
392
|
+
create: estimatedOps.create,
|
|
393
|
+
update: estimatedOps.update
|
|
394
|
+
};
|
|
395
|
+
const estimatedTotalGas = Boolean(context.txBaseGas) && !estimatedOps.isGasSelfStakeTx && gasPrice.gt(ZERO) ? gasPrice.mul(new BN(txGasCfg?.dataStorage || 0)).mul(new BN(context.txSize || 0)).add(gasPrice.mul(new BN(txGasCfg?.createState || 0)).mul(new BN(estimatedOps.create + 1))).add(gasPrice.mul(new BN(txGasCfg?.updateState || 0)).mul(new BN(estimatedOps.update))) : ZERO;
|
|
396
|
+
const requiresGasPayment = estimatedTotalGas.gt(ZERO);
|
|
397
|
+
const txSize = context._baseTxSize ?? context.txSize;
|
|
398
|
+
const secCfg = resolveGasSecurityConfig(config);
|
|
399
|
+
if (feeCost.lte(ZERO)) {
|
|
400
|
+
if (!requiresGasPayment) {
|
|
401
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (ONBOARDING_FREE_TX_TYPES.has(shortTxType) && (txSize || 0) <= secCfg.maxFreeGasTxSize) {
|
|
405
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
const extra = context.extra || {};
|
|
410
|
+
const txExtra = extra.txExtra && typeof extra.txExtra === "object" ? extra.txExtra : void 0;
|
|
411
|
+
const { token: token$1, pk } = extra.gasStakeHeaders || {};
|
|
412
|
+
const rawGasPass = extra.gasPass || txExtra?.gasPass;
|
|
413
|
+
const txHash = context.txHash || "";
|
|
414
|
+
const txTime = context.txTime;
|
|
415
|
+
const nowMs = txTime ? +new Date(txTime) : Date.now();
|
|
416
|
+
const officialTok = config?.token?.address || "";
|
|
417
|
+
const resolveSelfGasStake = async () => {
|
|
418
|
+
if (!officialTok || typeof statedb?.stake?.get !== "function") return {
|
|
419
|
+
hasSelfStake: false,
|
|
420
|
+
state: null,
|
|
421
|
+
valid: false
|
|
422
|
+
};
|
|
423
|
+
const candidates = Array.from(new Set([from, context.tx?.delegator].filter(Boolean)));
|
|
424
|
+
for (const candidate of candidates) {
|
|
425
|
+
const stakeId = toStakeAddress(candidate, candidate);
|
|
426
|
+
const selfStake = await statedb.stake.get(stakeId, context);
|
|
427
|
+
if (new BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
|
|
428
|
+
hasSelfStake: true,
|
|
429
|
+
state: selfStake,
|
|
430
|
+
valid: isGasStakeValid(selfStake, config)
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
hasSelfStake: false,
|
|
435
|
+
state: null,
|
|
436
|
+
valid: false
|
|
437
|
+
};
|
|
438
|
+
};
|
|
439
|
+
if (feeCost.lte(ZERO)) {
|
|
440
|
+
if (rawGasPass) {
|
|
441
|
+
const passStakeState = rawGasPass.stakeId && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(rawGasPass.stakeId, context) : null;
|
|
442
|
+
const passResult = verifyAndConsumeUnlinkableGasPass({
|
|
443
|
+
gasPass: rawGasPass,
|
|
444
|
+
stakeState: passStakeState,
|
|
445
|
+
txHash,
|
|
446
|
+
nowMs,
|
|
447
|
+
config,
|
|
448
|
+
statedb,
|
|
449
|
+
consumeNullifier: false
|
|
450
|
+
});
|
|
451
|
+
if (!passResult.valid) {
|
|
452
|
+
const passErr = new CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`, { persist: false });
|
|
453
|
+
passErr._unauthenticatedExtraFailure = true;
|
|
454
|
+
throw passErr;
|
|
455
|
+
}
|
|
456
|
+
const passOwner = passStakeState?.sender || rawGasPass.stakeId;
|
|
457
|
+
const isThirdPartyGasPass = Boolean(passOwner && !isSameDid(passOwner, from) && (!context.tx?.delegator || !isSameDid(passOwner, context.tx.delegator)));
|
|
458
|
+
const selfStakeInfo = isThirdPartyGasPass ? await resolveSelfGasStake() : null;
|
|
459
|
+
const selfStakeEligible = Boolean(selfStakeInfo?.valid) && evaluateStakeForGasEligibility({
|
|
460
|
+
txType,
|
|
461
|
+
txSize,
|
|
462
|
+
gasEstimate,
|
|
463
|
+
isFailedTxGasCharge: false,
|
|
464
|
+
isThirdPartySponsor: false,
|
|
465
|
+
enforceSponsor3DEligibility: false,
|
|
466
|
+
config
|
|
467
|
+
}).eligible;
|
|
468
|
+
const effectiveStakeState = selfStakeInfo?.valid && selfStakeEligible ? selfStakeInfo.state : passStakeState;
|
|
469
|
+
const eligibility = evaluateStakeForGasEligibility({
|
|
470
|
+
txType,
|
|
471
|
+
txSize,
|
|
472
|
+
gasEstimate,
|
|
473
|
+
isFailedTxGasCharge: false,
|
|
474
|
+
isThirdPartySponsor: selfStakeInfo?.valid && selfStakeEligible ? false : isThirdPartyGasPass,
|
|
475
|
+
enforceSponsor3DEligibility: false,
|
|
476
|
+
config
|
|
477
|
+
});
|
|
478
|
+
if (isGasStakeValid(effectiveStakeState, config) && eligibility.eligible) {
|
|
479
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
} else if (token$1 && pk) {
|
|
483
|
+
let decoded = {};
|
|
484
|
+
let sponsorAddress = "";
|
|
485
|
+
let issuerMatchesPk = false;
|
|
486
|
+
try {
|
|
487
|
+
if (typeof token$1 === "string" && typeof pk === "string") {
|
|
488
|
+
decoded = JWT.decode(token$1) || {};
|
|
489
|
+
sponsorAddress = toAddress(decoded.iss || "");
|
|
490
|
+
issuerMatchesPk = Boolean(sponsorAddress && isFromPublicKey(sponsorAddress, pk));
|
|
491
|
+
}
|
|
492
|
+
} catch {
|
|
493
|
+
issuerMatchesPk = false;
|
|
494
|
+
}
|
|
495
|
+
if (!issuerMatchesPk) {
|
|
496
|
+
const hdrErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key", { persist: false });
|
|
497
|
+
hdrErr._unauthenticatedExtraFailure = true;
|
|
498
|
+
throw hdrErr;
|
|
499
|
+
}
|
|
500
|
+
assertBridgeReserveNotSponsor(sponsorAddress);
|
|
501
|
+
let jwtVerified = false;
|
|
502
|
+
try {
|
|
503
|
+
jwtVerified = Boolean(await JWT.verify(token$1, pk, {
|
|
504
|
+
enforceTimestamp: !txTime,
|
|
505
|
+
tolerance: 5
|
|
506
|
+
}));
|
|
507
|
+
} catch {
|
|
508
|
+
jwtVerified = false;
|
|
509
|
+
}
|
|
510
|
+
if (jwtVerified) {
|
|
511
|
+
const toleranceSec = 5;
|
|
512
|
+
const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
|
|
513
|
+
const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
|
|
514
|
+
const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
|
|
515
|
+
const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
|
|
516
|
+
const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
|
|
517
|
+
const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
|
|
518
|
+
const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
|
|
519
|
+
const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
520
|
+
if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
|
|
521
|
+
const sponsorState = await accountStore.get(sponsorAddress, {
|
|
522
|
+
...context,
|
|
523
|
+
traceMigration: false
|
|
524
|
+
});
|
|
525
|
+
if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
|
|
526
|
+
const pkErr = new CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT signer public key does not match on-chain sponsor account", { persist: false });
|
|
527
|
+
pkErr._unauthenticatedExtraFailure = true;
|
|
528
|
+
throw pkErr;
|
|
529
|
+
}
|
|
530
|
+
const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
|
|
531
|
+
const sponsorAddresses = getRelatedAddresses(sponsorState || { address: sponsorAddress });
|
|
532
|
+
const checkBlocked = async (checker, addr) => {
|
|
533
|
+
if (typeof checker?.isBlocked !== "function") return false;
|
|
534
|
+
if (await Promise.resolve(checker.isBlocked(addr))) return true;
|
|
535
|
+
return Boolean(await Promise.resolve(checker.isBlocked([addr])));
|
|
536
|
+
};
|
|
537
|
+
let isSponsorBlocked = false;
|
|
538
|
+
for (const addr of sponsorAddresses) if (await checkBlocked(filter, addr) || await checkBlocked(statedb?.blacklist, addr)) {
|
|
539
|
+
isSponsorBlocked = true;
|
|
540
|
+
break;
|
|
541
|
+
}
|
|
542
|
+
if (!isSponsorMigrated && !isSponsorBlocked) {
|
|
543
|
+
const sponsorStakeId = toStakeAddress(sponsorAddress, sponsorAddress);
|
|
544
|
+
const isDirectMode = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
|
|
545
|
+
const sponsorStakeState = !isDirectMode && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(sponsorStakeId, context) : null;
|
|
546
|
+
const minSponsorBalance = estimatedTotalGas.gt(ZERO) ? estimatedTotalGas : new BN(1);
|
|
547
|
+
const sponsorIsBacked = isDirectMode ? Boolean(sponsorState && officialTok && new BN(sponsorState.tokens?.[officialTok] || 0).gte(minSponsorBalance)) : isGasStakeValid(sponsorStakeState, config);
|
|
548
|
+
const paymasterCheck = verifyPaymasterConstraints({
|
|
549
|
+
decoded,
|
|
550
|
+
tx: context.tx,
|
|
551
|
+
itx: context.itx,
|
|
552
|
+
txType,
|
|
553
|
+
totalGas: estimatedTotalGas
|
|
554
|
+
});
|
|
555
|
+
if (!paymasterCheck.valid) {
|
|
556
|
+
const pmErr = new CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`, { persist: false });
|
|
557
|
+
pmErr._strikeRecorded = true;
|
|
558
|
+
pmErr._unauthenticatedExtraFailure = true;
|
|
559
|
+
throw pmErr;
|
|
560
|
+
}
|
|
561
|
+
if (paymasterCheck.isPaymasterDirectCharge) {
|
|
562
|
+
const txTargets = extractTransactionTargets(context.tx, context.itx, txType);
|
|
563
|
+
if ([
|
|
564
|
+
from,
|
|
565
|
+
context.tx?.delegator,
|
|
566
|
+
context.gasVault,
|
|
567
|
+
context.feeVault,
|
|
568
|
+
config?.vaults?.txFee,
|
|
569
|
+
...Array.isArray(config?.vaults?.txGas) ? config.vaults.txGas : [],
|
|
570
|
+
...Array.isArray(config?.vaults?.txFees) ? config.vaults.txFees : [],
|
|
571
|
+
...txTargets
|
|
572
|
+
].filter(Boolean).some((candidate) => isSameDid(sponsorAddress, candidate) || sponsorAddress === candidate)) {
|
|
573
|
+
const aliasErr = new CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault", { persist: false });
|
|
574
|
+
aliasErr._unauthenticatedExtraFailure = true;
|
|
575
|
+
throw aliasErr;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const selfStakeInfo = await resolveSelfGasStake();
|
|
579
|
+
const selfStakeEligible = Boolean(selfStakeInfo.valid) && evaluateStakeForGasEligibility({
|
|
580
|
+
txType,
|
|
581
|
+
txSize,
|
|
582
|
+
gasEstimate,
|
|
583
|
+
isFailedTxGasCharge: false,
|
|
584
|
+
isThirdPartySponsor: false,
|
|
585
|
+
enforceSponsor3DEligibility: false,
|
|
586
|
+
config
|
|
587
|
+
}).eligible;
|
|
588
|
+
if (selfStakeInfo.valid && selfStakeEligible) {
|
|
589
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else if (paymasterCheck.isPaymasterDirectCharge) {
|
|
593
|
+
if (sponsorIsBacked) {
|
|
594
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
} else {
|
|
598
|
+
const eligibility = evaluateStakeForGasEligibility({
|
|
599
|
+
txType,
|
|
600
|
+
txSize,
|
|
601
|
+
gasEstimate,
|
|
602
|
+
isFailedTxGasCharge: false,
|
|
603
|
+
isThirdPartySponsor: true,
|
|
604
|
+
enforceSponsor3DEligibility: decoded.enforce3DEligibility === true || (config?.transaction?.txGas)?.enforceSponsor3DEligibility === true,
|
|
605
|
+
config
|
|
606
|
+
});
|
|
607
|
+
if (isGasStakeValid(sponsorStakeState, config) && eligibility.eligible) {
|
|
608
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (officialTok && typeof statedb?.stake?.get === "function") {
|
|
617
|
+
const directStakeId = toStakeAddress(from, from);
|
|
618
|
+
if (isGasStakeValid(await statedb.stake.get(directStakeId, context), config)) {
|
|
619
|
+
if (evaluateStakeForGasEligibility({
|
|
620
|
+
txType,
|
|
621
|
+
txSize,
|
|
622
|
+
gasEstimate,
|
|
623
|
+
isFailedTxGasCharge: false,
|
|
624
|
+
isThirdPartySponsor: false,
|
|
625
|
+
enforceSponsor3DEligibility: false,
|
|
626
|
+
config
|
|
627
|
+
}).eligible) {
|
|
628
|
+
await assertProtocolAdmissibleWithoutSenderState();
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (isExistingAssetSender) throw new CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${from}`, { persist: false });
|
|
635
|
+
if (txType === "fg:t:account_migrate" || Boolean(token$1 || pk) || Boolean(rawGasPass)) throw new CustomError("INVALID_GAS_PAYER", `Gas payer ${from} does not exist on chain`, { persist: false });
|
|
636
|
+
if (!NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
|
|
637
|
+
throw new CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
|
|
638
|
+
};
|
|
159
639
|
const assertSenderNonceFresh = async (context) => {
|
|
160
640
|
const from = context.tx?.from;
|
|
161
641
|
const accountStore = context.statedb?.account;
|
|
162
|
-
if (!from || typeof accountStore?.get !== "function") return;
|
|
642
|
+
if (!from || typeof accountStore?.get !== "function") return null;
|
|
163
643
|
const senderState = await accountStore.get(from, context);
|
|
164
|
-
if (!senderState) return;
|
|
644
|
+
if (!senderState) return null;
|
|
165
645
|
if (senderState.address !== from && senderState.address !== account.ensureChecksumAddress(from)) throw new CustomError("ACCOUNT_MIGRATED", `account ${from} is migrated`);
|
|
166
646
|
const incomingNonceBn = parseNonceBn(context.tx?.nonce);
|
|
167
647
|
const currentNonceBn = parseNonceBn(senderState.nonce) ?? new BN(0);
|
|
168
648
|
if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
|
|
649
|
+
return senderState;
|
|
169
650
|
};
|
|
170
651
|
/**
|
|
171
652
|
* Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
|
|
@@ -218,14 +699,62 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
218
699
|
}
|
|
219
700
|
};
|
|
220
701
|
const pre = new Runner("pre-execute");
|
|
221
|
-
pre.use(
|
|
702
|
+
pre.use((context, next) => {
|
|
703
|
+
context._preFlightSnapshotApplied = false;
|
|
704
|
+
if (tryApplyPreFlightVerifiedSnapshot(context)) {
|
|
705
|
+
context._preFlightSnapshotApplied = true;
|
|
706
|
+
return next();
|
|
707
|
+
}
|
|
708
|
+
return pipes.DecodeTx(context, next);
|
|
709
|
+
});
|
|
222
710
|
pre.use(pipes.VerifyBlocked({
|
|
223
711
|
filter,
|
|
224
712
|
stateKeys: ["tx.from"]
|
|
225
713
|
}));
|
|
226
|
-
pre.use(
|
|
227
|
-
|
|
228
|
-
|
|
714
|
+
pre.use((context, next) => {
|
|
715
|
+
if (context._preFlightSnapshotApplied) {
|
|
716
|
+
context.logger?.info("Tx decoded", {
|
|
717
|
+
txBase64: context.txBase64,
|
|
718
|
+
txHash: context.txHash,
|
|
719
|
+
txTime: context.txTime,
|
|
720
|
+
txSize: context.txSize,
|
|
721
|
+
txType: context.txType,
|
|
722
|
+
request: context.extra?.request
|
|
723
|
+
});
|
|
724
|
+
context.timer?.mark?.("decode");
|
|
725
|
+
return next();
|
|
726
|
+
}
|
|
727
|
+
return pipes.DecodeItx(context, next);
|
|
728
|
+
});
|
|
729
|
+
pre.use((context, next) => {
|
|
730
|
+
if (context._preFlightSnapshotApplied) return next();
|
|
731
|
+
return pipes.VerifyTx(context, next);
|
|
732
|
+
});
|
|
733
|
+
pre.use((context, next) => {
|
|
734
|
+
const protocolsMap = context._protocols;
|
|
735
|
+
if (protocolsMap && context.txType && !protocolsMap[getTxName(context.txType)]) return next(new CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`, { persist: false }));
|
|
736
|
+
return next();
|
|
737
|
+
});
|
|
738
|
+
pre.use((context, next) => {
|
|
739
|
+
try {
|
|
740
|
+
assertBridgeReserveNotActor(context);
|
|
741
|
+
return next();
|
|
742
|
+
} catch (err) {
|
|
743
|
+
return next(err);
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
pre.use(async (context, next) => {
|
|
747
|
+
try {
|
|
748
|
+
await assertStatelessTxRules(context, context._protocols);
|
|
749
|
+
return next();
|
|
750
|
+
} catch (err) {
|
|
751
|
+
return next(err);
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
pre.use((context, next) => {
|
|
755
|
+
if (context._preFlightSnapshotApplied) return next();
|
|
756
|
+
return pipes.VerifyServiceFee(context, next);
|
|
757
|
+
});
|
|
229
758
|
pre.use(async (context, next) => {
|
|
230
759
|
const syncState = getSyncState(context);
|
|
231
760
|
const execId = context.executionId;
|
|
@@ -241,9 +770,21 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
241
770
|
filter.add(context.txHash);
|
|
242
771
|
return next();
|
|
243
772
|
});
|
|
244
|
-
pre.use(
|
|
245
|
-
|
|
246
|
-
|
|
773
|
+
pre.use((context, next) => {
|
|
774
|
+
if (context._preFlightSnapshotApplied) return next();
|
|
775
|
+
return pipes.VerifyTxSize(context, next);
|
|
776
|
+
});
|
|
777
|
+
pre.use((context, next) => {
|
|
778
|
+
if (context._preFlightSnapshotApplied) return next();
|
|
779
|
+
return pipes.PreFlightWaf(context, next);
|
|
780
|
+
});
|
|
781
|
+
pre.use((context, next) => {
|
|
782
|
+
if (context._preFlightSnapshotApplied) {
|
|
783
|
+
context.timer?.mark?.("verify");
|
|
784
|
+
return next();
|
|
785
|
+
}
|
|
786
|
+
return pipes.VerifySignature(context, next);
|
|
787
|
+
});
|
|
247
788
|
pre.use((context, next) => {
|
|
248
789
|
context.isSignatureVerified = true;
|
|
249
790
|
return next();
|
|
@@ -258,16 +799,16 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
258
799
|
const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
|
|
259
800
|
if (existingTxOwner && existingTxOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
260
801
|
}
|
|
261
|
-
await assertSenderNonceFresh(context);
|
|
802
|
+
const senderState = await assertSenderNonceFresh(context);
|
|
262
803
|
await assertDelegationAuthorized(context);
|
|
263
804
|
if (context.unsignedTxHash) {
|
|
264
805
|
const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
|
|
265
806
|
if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
266
807
|
}
|
|
267
808
|
if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
|
|
809
|
+
if (!senderState) await assertNonExistentSenderAdmissible(context);
|
|
268
810
|
if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
|
|
269
811
|
if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
|
|
270
|
-
await runSinglePipe(WriteLedger, context);
|
|
271
812
|
});
|
|
272
813
|
return next();
|
|
273
814
|
} catch (err) {
|
|
@@ -276,8 +817,16 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
276
817
|
});
|
|
277
818
|
const ensureGasFeePaid = (context) => {
|
|
278
819
|
const gasRunner = new Runner("ensure-gas-fee-paid");
|
|
279
|
-
gasRunner.use((ctx, next) => {
|
|
820
|
+
gasRunner.use(async (ctx, next) => {
|
|
280
821
|
if (ctx.senderState?.address && ctx.stateSnapshot?.[ctx.senderState.address]) ctx.senderState = cloneDeep(ctx.stateSnapshot[ctx.senderState.address]);
|
|
822
|
+
else if (!ctx.senderState && ctx.tx?.from && typeof ctx.statedb?.account?.get === "function") {
|
|
823
|
+
const fetched = await ctx.statedb.account.get(ctx.tx.from, ctx);
|
|
824
|
+
if (fetched && (fetched.address === ctx.tx.from || isSameDid(fetched.address, ctx.tx.from)) && !(Array.isArray(fetched.migratedTo) && fetched.migratedTo.length > 0)) ctx.senderState = fetched;
|
|
825
|
+
}
|
|
826
|
+
if (ctx.senderState?.address && !ctx.stateSnapshot?.[ctx.senderState.address]) ctx.stateSnapshot = {
|
|
827
|
+
...ctx.stateSnapshot || {},
|
|
828
|
+
[ctx.senderState.address]: cloneDeep(ctx.senderState)
|
|
829
|
+
};
|
|
281
830
|
ctx.isFailedTxGasCharge = true;
|
|
282
831
|
ctx.gasPaid = false;
|
|
283
832
|
ctx.senderUpdates = {};
|
|
@@ -301,7 +850,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
301
850
|
}, ctx);
|
|
302
851
|
ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
|
|
303
852
|
if (updateVaults) await updateVaults();
|
|
304
|
-
}
|
|
853
|
+
} else if (updateVaults) await updateVaults();
|
|
305
854
|
return next();
|
|
306
855
|
});
|
|
307
856
|
return new Promise((resolve, reject) => {
|
|
@@ -351,6 +900,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
351
900
|
if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
|
|
352
901
|
};
|
|
353
902
|
const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
|
|
903
|
+
context._protocols = protocols;
|
|
354
904
|
pre.run(context, async (err) => {
|
|
355
905
|
if (err) {
|
|
356
906
|
if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
|
|
@@ -370,6 +920,7 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
370
920
|
let error = rawError;
|
|
371
921
|
context.timer?.mark("protocol");
|
|
372
922
|
if (!error) try {
|
|
923
|
+
await prepareBridgeReserveGate(context);
|
|
373
924
|
inspectPostExecutionInvariants(context);
|
|
374
925
|
} catch (invariantErr) {
|
|
375
926
|
error = invariantErr;
|
|
@@ -391,6 +942,20 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
391
942
|
await ensureGasFeePaid(context);
|
|
392
943
|
txState = states.tx.create(context, txStatus);
|
|
393
944
|
}
|
|
945
|
+
try {
|
|
946
|
+
await appendLedgerEntry(context);
|
|
947
|
+
} catch (ledgerErr) {
|
|
948
|
+
if (!error) {
|
|
949
|
+
await rollbackTrackedStateWrites(context);
|
|
950
|
+
context.events = [];
|
|
951
|
+
}
|
|
952
|
+
context.logger?.error("Failed to append transaction to ledger", {
|
|
953
|
+
error: ledgerErr,
|
|
954
|
+
txError: error,
|
|
955
|
+
txHash: context.txHash
|
|
956
|
+
});
|
|
957
|
+
return reject(error || ledgerErr);
|
|
958
|
+
}
|
|
394
959
|
await context.statedb.tx.create(txState.hash, txState, context);
|
|
395
960
|
await recordUnsignedTxInStateDb(context, txState.hash);
|
|
396
961
|
context.timer?.mark("txstate");
|
|
@@ -449,15 +1014,17 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
449
1014
|
"extra",
|
|
450
1015
|
"logger",
|
|
451
1016
|
"ledgerSequence",
|
|
452
|
-
"height",
|
|
453
1017
|
"timer",
|
|
454
1018
|
"executionId"
|
|
455
1019
|
]);
|
|
1020
|
+
const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
|
|
1021
|
+
if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
|
|
456
1022
|
ctx.txn = txn;
|
|
457
1023
|
if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
|
|
458
1024
|
ctx.timer?.mark("lockWait");
|
|
459
1025
|
try {
|
|
460
1026
|
await execute(ctx, protocols, true);
|
|
1027
|
+
await appendLedgerEntry(ctx);
|
|
461
1028
|
} finally {
|
|
462
1029
|
if (ctx.ledgerSequence && !savedLedgerSequence) {
|
|
463
1030
|
savedLedgerSequence = ctx.ledgerSequence;
|
|
@@ -544,6 +1111,11 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
544
1111
|
try {
|
|
545
1112
|
await ensureGasFeePaid(ctx);
|
|
546
1113
|
await attachSecurityStrikeToError(err, ctx);
|
|
1114
|
+
await appendLedgerEntry(ctx);
|
|
1115
|
+
if (ctx.ledgerSequence && !savedLedgerSequence) {
|
|
1116
|
+
savedLedgerSequence = ctx.ledgerSequence;
|
|
1117
|
+
context.ledgerSequence = ctx.ledgerSequence;
|
|
1118
|
+
}
|
|
547
1119
|
const state = getStates(context).tx.create(ctx, txStatus);
|
|
548
1120
|
await ctx.statedb.tx.create(state.hash, state, ctx);
|
|
549
1121
|
await recordUnsignedTxInStateDb(ctx, state.hash);
|
|
@@ -686,4 +1258,4 @@ const createExecute = ({ filter, runAsLambda }) => {
|
|
|
686
1258
|
var execute_default = createExecute;
|
|
687
1259
|
|
|
688
1260
|
//#endregion
|
|
689
|
-
export { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, execute_default as default, toUnsignedEvidenceKey };
|
|
1261
|
+
export { PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, execute_default as default, toUnsignedEvidenceKey, tryApplyPreFlightVerifiedSnapshot };
|