@ocap/tx-protocols 1.31.1 → 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 +1 -1
- package/esm/execute.mjs +58 -5
- package/esm/gas-security-guard.d.mts +6 -2
- package/esm/gas-security-guard.mjs +16 -9
- package/esm/index.d.mts +37 -18
- package/esm/index.mjs +6 -2
- package/esm/pipes/ensure-cost.mjs +7 -1
- 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 +4 -2
- package/esm/protocols/governance/return-stake.mjs +4 -2
- package/esm/protocols/governance/revoke-ledger.mjs +1 -1
- package/esm/protocols/governance/revoke-stake.d.mts +7 -2
- package/esm/protocols/governance/revoke-stake.mjs +49 -28
- package/esm/protocols/governance/slash-stake.mjs +5 -3
- 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 +58 -5
- package/lib/gas-security-guard.cjs +16 -9
- package/lib/gas-security-guard.d.cts +6 -2
- package/lib/index.cjs +8 -1
- package/lib/index.d.cts +36 -17
- package/lib/pipes/ensure-cost.cjs +7 -1
- 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 +4 -2
- package/lib/protocols/governance/return-stake.cjs +4 -2
- package/lib/protocols/governance/revoke-ledger.cjs +1 -1
- package/lib/protocols/governance/revoke-stake.cjs +49 -28
- package/lib/protocols/governance/revoke-stake.d.cts +7 -2
- package/lib/protocols/governance/slash-stake.cjs +5 -3
- 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
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { ZERO_ETH_ADDRESS, getDepositClaimDigest, getOcapReleaseDigest, isEthAddress, recoverEthSigner } from "../../bridge-release-crypto.mjs";
|
|
2
|
+
import { MAX_RING_SKEW_HOURS, evaluateRing, formatRingSlot, parseRingSlot } from "../../bridge-release-window.mjs";
|
|
3
|
+
import { applyTokenChange } from "../../util.mjs";
|
|
4
|
+
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
5
|
+
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
6
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
7
|
+
import { RELEASE_RING_SLOTS, Runner, formatBucketData, getReleaseBucketKey, getReleaseTombstoneKey, isBridgeReserveRole, normalizeEntityKey, parseBucketData, pipes, resolveBridgeForRelease } from "@ocap/tx-pipeline";
|
|
8
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
9
|
+
import { account, evidence, rollup } from "@ocap/state";
|
|
10
|
+
import { BN } from "@ocap/util";
|
|
11
|
+
import { schemas, v, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
12
|
+
|
|
13
|
+
//#region src/protocols/bridge/release.ts
|
|
14
|
+
/**
|
|
15
|
+
* `release_bridge_token` (#1466): moves the token of an on-chain bridge out of that bridge's reserve, for a credited
|
|
16
|
+
* deposit or a refunded withdraw. Design: bridge/docs/ocap-protocols.md §3 (checks 1-10) on the v2 model (§v2.2, §v2.4):
|
|
17
|
+
* every parameter comes from the bridge named by `itx.bridge`, and every key carries that bridge.
|
|
18
|
+
*
|
|
19
|
+
* The validity of a release is its itx content: the validator quorum signs it and the signatures travel inside the itx,
|
|
20
|
+
* so the coordinator or any validator can submit it, and the sender only pays gas.
|
|
21
|
+
*
|
|
22
|
+
* Lifecycle per kind (§v2.2 `pause_rollup` / `close_rollup`, decided here and documented in the design doc):
|
|
23
|
+
* - not closing: a pause of any kind (lone or quorum) refuses every kind, REFUND included;
|
|
24
|
+
* - closing (`close_rollup` has run; the bridge is quorum-paused for good): DEPOSIT / DEPOSIT_B are accepted until
|
|
25
|
+
* `finalAt` (validators must release the backlog before finality), REFUND is accepted for as long as it is due,
|
|
26
|
+
* also after finality, and also from the reserve of a successor once the funds were migrated.
|
|
27
|
+
*/
|
|
28
|
+
const RELEASE_KIND = {
|
|
29
|
+
DEPOSIT: 1,
|
|
30
|
+
REFUND: 2,
|
|
31
|
+
DEPOSIT_B: 3
|
|
32
|
+
};
|
|
33
|
+
/** `resolveMigrated` follows at most this many `migratedTo` links of an ACCOUNT (check 6) */
|
|
34
|
+
const MAX_MIGRATION_HOPS = 8;
|
|
35
|
+
const UINT256_MAX = (1n << 256n) - 1n;
|
|
36
|
+
const invalid = (message) => new CustomError("INVALID_TX", message);
|
|
37
|
+
const forbidden = (message) => new CustomError("FORBIDDEN", message);
|
|
38
|
+
const runner = new Runner("release_bridge_token");
|
|
39
|
+
runner.use(pipes.VerifyMultiSig(0));
|
|
40
|
+
const schema = v.pipe(v.object({
|
|
41
|
+
kind: v.picklist([
|
|
42
|
+
RELEASE_KIND.DEPOSIT,
|
|
43
|
+
RELEASE_KIND.REFUND,
|
|
44
|
+
RELEASE_KIND.DEPOSIT_B
|
|
45
|
+
]),
|
|
46
|
+
bridge: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
|
|
47
|
+
evidence: v.pipe(v.string(), v.regex(/^0x[0-9a-f]{64}$/)),
|
|
48
|
+
ordinal: v.pipe(v.number(), v.integer(), v.minValue(0)),
|
|
49
|
+
to: schemas.tokenHolder,
|
|
50
|
+
amount: v.pipe(v.string(), v.regex(/^[1-9]\d{0,77}$/)),
|
|
51
|
+
ethChainId: v.pipe(v.string(), v.regex(/^[1-9]\d{0,18}$/)),
|
|
52
|
+
epoch: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
|
|
53
|
+
ethSender: v.optional(v.string(), ""),
|
|
54
|
+
claimSignature: v.optional(v.string(), ""),
|
|
55
|
+
signaturesList: v.pipe(v.array(v.string()), v.maxLength(16)),
|
|
56
|
+
data: v.optional(v.nullable(v.any()))
|
|
57
|
+
}), vStripUnknown());
|
|
58
|
+
runner.use((context, next) => {
|
|
59
|
+
const { error } = vValidate(schema, context.itx);
|
|
60
|
+
if (error) return next(invalid(`Invalid itx: ${error.message}`));
|
|
61
|
+
next();
|
|
62
|
+
});
|
|
63
|
+
runner.use((context, next) => {
|
|
64
|
+
const { itx } = context;
|
|
65
|
+
if (itx.ordinal !== 0) return next(invalid("Release ordinal must be 0 in v1"));
|
|
66
|
+
if (BigInt(itx.amount) > UINT256_MAX) return next(invalid("Release amount exceeds uint256"));
|
|
67
|
+
if (itx.kind === RELEASE_KIND.DEPOSIT_B) {
|
|
68
|
+
if (!isEthAddress(itx.ethSender) || itx.ethSender.toLowerCase() === ZERO_ETH_ADDRESS) return next(invalid("DEPOSIT_B release requires a non-zero ethSender"));
|
|
69
|
+
if (!/^0x[0-9a-fA-F]{130}$/.test(itx.claimSignature)) return next(invalid("DEPOSIT_B release requires a 65-byte claimSignature"));
|
|
70
|
+
} else if (itx.ethSender !== "" || itx.claimSignature !== "") return next(invalid("ethSender and claimSignature are only valid for DEPOSIT_B"));
|
|
71
|
+
next();
|
|
72
|
+
});
|
|
73
|
+
markStatelessPrefix(runner);
|
|
74
|
+
runner.use((context, next) => {
|
|
75
|
+
if (context.tx.delegator) return next(invalid("A release can not be delegated"));
|
|
76
|
+
next();
|
|
77
|
+
});
|
|
78
|
+
runner.use((context, next) => {
|
|
79
|
+
const { txTime } = context;
|
|
80
|
+
const ms = typeof txTime === "string" ? new Date(txTime).getTime() : NaN;
|
|
81
|
+
if (!Number.isFinite(ms) || ms <= 0) return next(invalid("Release requires a valid tx time"));
|
|
82
|
+
context.releaseTimeMs = ms;
|
|
83
|
+
next();
|
|
84
|
+
});
|
|
85
|
+
runner.use(async (context, next) => {
|
|
86
|
+
const { itx, config } = context;
|
|
87
|
+
if (!config?.transaction?.bridge?.enabled) return next(forbidden("Bridges are not enabled on this chain"));
|
|
88
|
+
let release;
|
|
89
|
+
try {
|
|
90
|
+
release = await resolveBridgeForRelease(context, itx);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
return next(err);
|
|
93
|
+
}
|
|
94
|
+
if (!release) return next(invalid("itx.bridge is not the canonical address of an existing bridge"));
|
|
95
|
+
const { bridge } = release;
|
|
96
|
+
context.release = release;
|
|
97
|
+
context.releaseAmount = BigInt(itx.amount);
|
|
98
|
+
const isRefund = itx.kind === RELEASE_KIND.REFUND;
|
|
99
|
+
if (bridge.closing) {
|
|
100
|
+
if (!isRefund && bridge.final) return next(forbidden("The bridge is final: deposits can no longer be released"));
|
|
101
|
+
} else if (bridge.paused) return next(forbidden("The bridge is paused"));
|
|
102
|
+
if (bridge.migrated && !isRefund) return next(forbidden("The bridge has migrated its reserve"));
|
|
103
|
+
const signing = isRefund ? release.debitable.get(release.fundsReserve) : bridge;
|
|
104
|
+
if (!signing) return next(invalid("The reserve that holds the funds of this bridge could not be resolved"));
|
|
105
|
+
if (signing !== bridge && !signing.closing && signing.paused) return next(forbidden(`Bridge ${signing.address}, which holds the funds, is paused`));
|
|
106
|
+
context.signingBridge = signing;
|
|
107
|
+
if (itx.ethChainId !== signing.body.ethChainId) return next(invalid(`Release ethChainId ${itx.ethChainId} does not match the bridge`));
|
|
108
|
+
next();
|
|
109
|
+
});
|
|
110
|
+
runner.use((context, next) => {
|
|
111
|
+
const { itx, release, releaseAmount } = context;
|
|
112
|
+
const min = BigInt(release.bridge.body.minDeposit);
|
|
113
|
+
if (itx.kind !== RELEASE_KIND.REFUND && releaseAmount < min) return next(invalid(`Release amount is below the minimum deposit ${min}`));
|
|
114
|
+
next();
|
|
115
|
+
});
|
|
116
|
+
runner.use((context, next) => {
|
|
117
|
+
const { config, itx } = context;
|
|
118
|
+
const to = normalizeEntityKey(itx.to);
|
|
119
|
+
if (typeof itx.to !== "string" || itx.to.startsWith("did:abt:") || account.ensureChecksumAddress(itx.to) !== itx.to) return next(invalid("Release recipient is not in canonical form (bare address, EIP-55 checksum for 0x)"));
|
|
120
|
+
if (isBridgeReserveRole(itx.to)) return next(invalid("A release can not pay a bridge reserve"));
|
|
121
|
+
const vaults = config.vaults || {};
|
|
122
|
+
const list = (x) => Array.isArray(x) ? x : [];
|
|
123
|
+
if ([
|
|
124
|
+
vaults.slashedStake,
|
|
125
|
+
vaults.txFee,
|
|
126
|
+
...list(vaults.txFees),
|
|
127
|
+
...list(vaults.txGas)
|
|
128
|
+
].filter((x) => typeof x === "string" && !!x).map((x) => normalizeEntityKey(x)).includes(to)) return next(invalid("A release can not pay a vault"));
|
|
129
|
+
next();
|
|
130
|
+
});
|
|
131
|
+
runner.use(async (context, next) => {
|
|
132
|
+
const { itx, statedb, release } = context;
|
|
133
|
+
const key = getReleaseTombstoneKey(release.bridge.address, itx.kind, itx.evidence, itx.ordinal);
|
|
134
|
+
context.tombstoneKey = key;
|
|
135
|
+
if (await statedb.evidence.get(key, context)) return next(invalid("Release already executed for this evidence"));
|
|
136
|
+
next();
|
|
137
|
+
});
|
|
138
|
+
runner.use((context, next) => {
|
|
139
|
+
const { itx, release, releaseTimeMs } = context;
|
|
140
|
+
const bridge = release.bridge;
|
|
141
|
+
const body = context.signingBridge.body;
|
|
142
|
+
const epochs = body.epochs;
|
|
143
|
+
const index = epochs.findIndex((e) => e.epoch === itx.epoch);
|
|
144
|
+
const epoch = epochs[index];
|
|
145
|
+
if (!epoch) return next(invalid(`Release epoch ${itx.epoch} is not configured`));
|
|
146
|
+
const nowSec = Math.floor(releaseTimeMs / 1e3);
|
|
147
|
+
if (epoch.activeFrom > nowSec) return next(invalid(`Release epoch ${itx.epoch} is not active yet`));
|
|
148
|
+
const following = epochs[index + 1];
|
|
149
|
+
if (following && nowSec >= following.activeFrom + body.releaseGrace) return next(invalid(`Release epoch ${itx.epoch} has been replaced for longer than the release grace period`));
|
|
150
|
+
const signatures = itx.signaturesList;
|
|
151
|
+
if (signatures.length < epoch.threshold) return next(invalid(`Release has ${signatures.length} signatures, epoch ${epoch.epoch} needs ${epoch.threshold}`));
|
|
152
|
+
if (signatures.length > epoch.validators.length) return next(invalid("Release has more signatures than the epoch has validators"));
|
|
153
|
+
const digest = getOcapReleaseDigest({
|
|
154
|
+
ethChainId: body.ethChainId,
|
|
155
|
+
gateway: body.gateway
|
|
156
|
+
}, {
|
|
157
|
+
kind: itx.kind,
|
|
158
|
+
evidence: itx.evidence,
|
|
159
|
+
ordinal: itx.ordinal,
|
|
160
|
+
ocapChainId: context.config.chainId,
|
|
161
|
+
bridge: bridge.address,
|
|
162
|
+
to: itx.to,
|
|
163
|
+
amount: itx.amount,
|
|
164
|
+
epoch: itx.epoch,
|
|
165
|
+
ethSender: itx.kind === RELEASE_KIND.DEPOSIT_B ? itx.ethSender : ZERO_ETH_ADDRESS
|
|
166
|
+
});
|
|
167
|
+
const validators = new Set(epoch.validators.map((x) => x.toLowerCase()));
|
|
168
|
+
let previous = -1n;
|
|
169
|
+
for (const signature of signatures) {
|
|
170
|
+
const signer = recoverEthSigner(digest, signature);
|
|
171
|
+
if (!signer) return next(invalid("Release carries a malformed or non-canonical signature"));
|
|
172
|
+
if (!validators.has(signer)) return next(invalid(`Release signer ${signer} is not a validator of the epoch`));
|
|
173
|
+
const value = BigInt(signer);
|
|
174
|
+
if (value <= previous) return next(invalid("Release signatures must be sorted by signer, without duplicates"));
|
|
175
|
+
previous = value;
|
|
176
|
+
}
|
|
177
|
+
next();
|
|
178
|
+
});
|
|
179
|
+
runner.use((context, next) => {
|
|
180
|
+
const { itx } = context;
|
|
181
|
+
if (itx.kind !== RELEASE_KIND.DEPOSIT_B) return next();
|
|
182
|
+
const body = context.signingBridge.body;
|
|
183
|
+
const signer = recoverEthSigner(getDepositClaimDigest({
|
|
184
|
+
ethChainId: body.ethChainId,
|
|
185
|
+
gateway: body.gateway
|
|
186
|
+
}, {
|
|
187
|
+
ethTxHash: itx.evidence,
|
|
188
|
+
ocapChainId: context.config.chainId,
|
|
189
|
+
recipient: itx.to,
|
|
190
|
+
amount: itx.amount
|
|
191
|
+
}), itx.claimSignature);
|
|
192
|
+
if (!signer || signer !== itx.ethSender.toLowerCase()) return next(invalid("DEPOSIT_B claimSignature does not recover to ethSender"));
|
|
193
|
+
next();
|
|
194
|
+
});
|
|
195
|
+
const rawRead = (context) => ({
|
|
196
|
+
txn: context.txn,
|
|
197
|
+
traceMigration: false
|
|
198
|
+
});
|
|
199
|
+
async function resolveMigrated(context, address) {
|
|
200
|
+
const seen = /* @__PURE__ */ new Set();
|
|
201
|
+
let current = address;
|
|
202
|
+
for (let hops = 0;; hops++) {
|
|
203
|
+
const key = normalizeEntityKey(current);
|
|
204
|
+
if (seen.has(key)) return null;
|
|
205
|
+
seen.add(key);
|
|
206
|
+
const migratedTo = (await context.statedb.account.get(current, rawRead(context)))?.migratedTo || [];
|
|
207
|
+
if (!migratedTo.length) return current;
|
|
208
|
+
if (migratedTo.length !== 1 || hops >= MAX_MIGRATION_HOPS) return null;
|
|
209
|
+
current = migratedTo[0];
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
runner.use(async (context, next) => {
|
|
213
|
+
const { itx, release, statedb, releaseTimeMs, releaseAmount } = context;
|
|
214
|
+
if (itx.kind !== RELEASE_KIND.REFUND) return next();
|
|
215
|
+
const bridge = release.bridge;
|
|
216
|
+
const body = bridge.body;
|
|
217
|
+
const token$1 = normalizeEntityKey(bridge.token);
|
|
218
|
+
const withdraw = await statedb.tx.get(itx.evidence.replace(/^0x/i, "").toUpperCase(), context) || await statedb.tx.get(itx.evidence, context);
|
|
219
|
+
if (!withdraw || withdraw.code !== "OK" || withdraw.type !== "transfer_v2") return next(invalid("Refund evidence is not a successful transfer_v2"));
|
|
220
|
+
const withdrawTx = withdraw.tx || {};
|
|
221
|
+
const itxJson = withdrawTx.itxJson || {};
|
|
222
|
+
if (normalizeEntityKey(itxJson.to) !== normalizeEntityKey(bridge.reserve)) return next(invalid("Refund evidence is not a transfer into the reserve of this bridge"));
|
|
223
|
+
if (withdrawTx.delegator) return next(invalid("A delegated withdraw can not be refunded"));
|
|
224
|
+
if ((itxJson.assets || []).length > 0) return next(invalid("Refund evidence moved assets"));
|
|
225
|
+
let paid = new BN(itxJson.value || "0");
|
|
226
|
+
for (const entry of itxJson.tokens || []) {
|
|
227
|
+
if (normalizeEntityKey(entry.address) !== token$1) return next(invalid("Refund evidence moved a token other than the bridge token"));
|
|
228
|
+
paid = paid.add(new BN(entry.value));
|
|
229
|
+
}
|
|
230
|
+
if (BigInt(paid.toString(10)) !== releaseAmount) return next(invalid("Refund amount does not match the withdraw"));
|
|
231
|
+
const withdrawMs = new Date(withdraw.time).getTime();
|
|
232
|
+
if (!Number.isFinite(withdrawMs)) return next(invalid("Refund evidence has no valid time"));
|
|
233
|
+
const withdrawSec = Math.floor(withdrawMs / 1e3);
|
|
234
|
+
const withdrawEpoch = rollup.activeEpochAt(body, withdrawSec);
|
|
235
|
+
if (!withdrawEpoch) return next(invalid("The withdraw predates the first epoch of the bridge"));
|
|
236
|
+
const refundableAt = withdrawMs + (withdrawEpoch.voucherValidity + body.refundDelay) * 1e3;
|
|
237
|
+
if (releaseTimeMs < refundableAt) return next(invalid(`Refund is not due before ${new Date(refundableAt).toISOString()}`));
|
|
238
|
+
const resolved = await resolveMigrated(context, withdrawTx.from);
|
|
239
|
+
if (!resolved) return next(invalid("The withdraw sender has an unresolvable migration chain"));
|
|
240
|
+
if (normalizeEntityKey(resolved) !== normalizeEntityKey(itx.to)) return next(invalid("Refund recipient is not the sender of the withdraw"));
|
|
241
|
+
const chain = [...release.debitable.values()];
|
|
242
|
+
const ledger = [];
|
|
243
|
+
for (const b of chain) {
|
|
244
|
+
if (b.reserve === release.fundsReserve) continue;
|
|
245
|
+
const recorded = b.body.migratedAmount;
|
|
246
|
+
if (typeof recorded !== "string" || !/^(0|[1-9]\d*)$/.test(recorded)) return next(invalid(`Bridge ${b.address} migrated its reserve without a refund ledger: refunds are refused`));
|
|
247
|
+
if (BigInt(recorded) < releaseAmount) return next(invalid(`Refund exceeds the refund ledger of migrated bridge ${b.address} (${recorded})`));
|
|
248
|
+
ledger.push({
|
|
249
|
+
address: b.address,
|
|
250
|
+
state: b.state,
|
|
251
|
+
amount: BigInt(recorded)
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
context.refundLedger = ledger;
|
|
255
|
+
next();
|
|
256
|
+
});
|
|
257
|
+
runner.use(async (context, next) => {
|
|
258
|
+
const state = await context.statedb.account.get(context.itx.to, rawRead(context));
|
|
259
|
+
if (state?.migratedTo?.length) return next(invalid("Release recipient has been migrated"));
|
|
260
|
+
context.receiverState = state ?? void 0;
|
|
261
|
+
next();
|
|
262
|
+
});
|
|
263
|
+
runner.use(async (context, next) => {
|
|
264
|
+
const { itx, release, statedb, releaseTimeMs, releaseAmount } = context;
|
|
265
|
+
const bridge = release.bridge;
|
|
266
|
+
const ring = itx.kind === RELEASE_KIND.REFUND ? "refund" : "deposit";
|
|
267
|
+
const cap = BigInt(ring === "refund" ? bridge.body.refundDailyCap : bridge.body.releaseDailyCap);
|
|
268
|
+
const states = await Promise.all(Array.from({ length: RELEASE_RING_SLOTS }, (_, slot) => statedb.evidence.get(getReleaseBucketKey(bridge.address, ring, slot), context)));
|
|
269
|
+
let slots;
|
|
270
|
+
try {
|
|
271
|
+
slots = states.map((state, slot) => {
|
|
272
|
+
if (!state) return null;
|
|
273
|
+
const row = parseBucketData(state.data);
|
|
274
|
+
if (!row || row.bridge !== bridge.address || row.ring !== ring || row.slot !== slot) throw new globalThis.Error("row does not belong to this slot");
|
|
275
|
+
const parsed = parseRingSlot(row.window);
|
|
276
|
+
if (parsed.hourIndex % RELEASE_RING_SLOTS !== slot) throw new globalThis.Error("slot index mismatch");
|
|
277
|
+
return parsed;
|
|
278
|
+
});
|
|
279
|
+
} catch (err) {
|
|
280
|
+
return next(invalid(`Release window of ring ${ring} is corrupt: ${err.message}`));
|
|
281
|
+
}
|
|
282
|
+
const result = evaluateRing(slots, releaseTimeMs, releaseAmount, cap);
|
|
283
|
+
if (result.skew > MAX_RING_SKEW_HOURS) return next(forbidden(`The ${ring} release window is ${result.skew} h ahead of the tx time (more than ${MAX_RING_SKEW_HOURS} h): refused until the tx time catches up`));
|
|
284
|
+
if (!result.allowed) return next(forbidden(`Release exceeds the ${ring} daily cap ${cap.toString(10)}: ${result.used.toString(10)} already used in the last 24h`));
|
|
285
|
+
context.releaseRing = {
|
|
286
|
+
key: getReleaseBucketKey(bridge.address, ring, result.slot),
|
|
287
|
+
exists: slots[result.slot] !== null,
|
|
288
|
+
data: formatBucketData(bridge.address, ring, result.slot, formatRingSlot(result.next))
|
|
289
|
+
};
|
|
290
|
+
next();
|
|
291
|
+
});
|
|
292
|
+
runner.use(async (context, next) => {
|
|
293
|
+
const { itx, release, statedb, releaseAmount } = context;
|
|
294
|
+
const reserveAddress = itx.kind === RELEASE_KIND.REFUND ? release.fundsReserve : release.reserve;
|
|
295
|
+
const reserveState = await statedb.account.get(reserveAddress, context);
|
|
296
|
+
if (!reserveState) return next(invalid("The bridge reserve account does not exist"));
|
|
297
|
+
const token$1 = release.debitable.get(reserveAddress).token;
|
|
298
|
+
if (BigInt(reserveState.tokens?.[token$1] || "0") < releaseAmount) return next(new CustomError("INSUFFICIENT_FUND", "The bridge reserve does not hold enough to release this amount"));
|
|
299
|
+
context.reserveState = reserveState;
|
|
300
|
+
context.releaseToken = token$1;
|
|
301
|
+
next();
|
|
302
|
+
});
|
|
303
|
+
runner.use(ensure_gas_default((context) => {
|
|
304
|
+
const ledger = (context.refundLedger || []).length;
|
|
305
|
+
return {
|
|
306
|
+
create: 1 + (context.receiverState ? 0 : 1) + (context.releaseRing?.exists ? 0 : 1),
|
|
307
|
+
update: 3 + (context.releaseRing?.exists ? 1 : 0) + ledger,
|
|
308
|
+
payment: 0
|
|
309
|
+
};
|
|
310
|
+
}));
|
|
311
|
+
runner.use(pipes.ExtractState({
|
|
312
|
+
from: "tx.from",
|
|
313
|
+
to: "senderState",
|
|
314
|
+
status: "INVALID_SENDER_STATE",
|
|
315
|
+
table: "account"
|
|
316
|
+
}));
|
|
317
|
+
runner.use(pipes.VerifyAccountMigration({
|
|
318
|
+
stateKey: "senderState",
|
|
319
|
+
addressKey: "tx.from"
|
|
320
|
+
}));
|
|
321
|
+
runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "receiverState"] }));
|
|
322
|
+
runner.use(ensure_cost_default({ attachSenderChanges: true }));
|
|
323
|
+
runner.use(pipes.TakeStateSnapshot());
|
|
324
|
+
runner.use(async (context, next) => {
|
|
325
|
+
const { itx, tx: tx$1, statedb, senderState, receiverState, reserveState, senderChange, releaseAmount, releaseRing, releaseToken, tombstoneKey, updateVaults, refundLedger } = context;
|
|
326
|
+
const amount = new BN(releaseAmount.toString(10));
|
|
327
|
+
const selfRelease = normalizeEntityKey(senderState.address) === normalizeEntityKey(itx.to);
|
|
328
|
+
await statedb.evidence.create(tombstoneKey, evidence.create({
|
|
329
|
+
hash: tombstoneKey,
|
|
330
|
+
data: context.txHash
|
|
331
|
+
}, context), context);
|
|
332
|
+
if (releaseRing.exists) await statedb.evidence.update(releaseRing.key, { data: releaseRing.data }, context);
|
|
333
|
+
else await statedb.evidence.create(releaseRing.key, evidence.create({
|
|
334
|
+
hash: releaseRing.key,
|
|
335
|
+
data: releaseRing.data
|
|
336
|
+
}, context), context);
|
|
337
|
+
for (const entry of refundLedger || []) {
|
|
338
|
+
const body = entry.state.data.value;
|
|
339
|
+
const next$1 = {
|
|
340
|
+
...entry.state,
|
|
341
|
+
data: {
|
|
342
|
+
...entry.state.data,
|
|
343
|
+
value: {
|
|
344
|
+
...body,
|
|
345
|
+
migratedAmount: (entry.amount - releaseAmount).toString(10)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
await statedb.rollup.update(entry.address, rollup.updateBridge(entry.state, next$1, context), context);
|
|
350
|
+
}
|
|
351
|
+
const reserveTokens = { ...reserveState.tokens || {} };
|
|
352
|
+
reserveTokens[releaseToken] = new BN(reserveTokens[releaseToken] || "0").sub(amount).toString(10);
|
|
353
|
+
const newReserveState = await statedb.account.updateOrCreate(reserveState, account.update(reserveState, { tokens: reserveTokens }, context), context);
|
|
354
|
+
const senderTokens = { ...senderState.tokens || {} };
|
|
355
|
+
if (selfRelease) senderTokens[releaseToken] = new BN(senderTokens[releaseToken] || "0").add(amount).toString(10);
|
|
356
|
+
const senderUpdates = senderChange ? applyTokenChange({ tokens: senderTokens }, senderChange) : { tokens: senderTokens };
|
|
357
|
+
const existingSender = await statedb.account.get(senderState.address, context);
|
|
358
|
+
const newSenderState = await statedb.account.updateOrCreate(existingSender ?? null, account.updateOrCreate(existingSender ?? null, {
|
|
359
|
+
address: senderState.address,
|
|
360
|
+
nonce: tx$1.nonce,
|
|
361
|
+
pk: tx$1.pk,
|
|
362
|
+
...senderUpdates
|
|
363
|
+
}, context), context);
|
|
364
|
+
let newReceiverState = newSenderState;
|
|
365
|
+
if (!selfRelease) {
|
|
366
|
+
const receiverTokens = { ...receiverState?.tokens || {} };
|
|
367
|
+
receiverTokens[releaseToken] = new BN(receiverTokens[releaseToken] || "0").add(amount).toString(10);
|
|
368
|
+
newReceiverState = await statedb.account.updateOrCreate(receiverState ?? null, account.updateOrCreate(receiverState ?? null, {
|
|
369
|
+
address: receiverState?.address || itx.to,
|
|
370
|
+
tokens: receiverTokens
|
|
371
|
+
}, context), context);
|
|
372
|
+
}
|
|
373
|
+
context.reserveState = newReserveState;
|
|
374
|
+
context.senderState = newSenderState;
|
|
375
|
+
context.receiverState = newReceiverState;
|
|
376
|
+
context.bridgeReserve = newReserveState.address;
|
|
377
|
+
context.bridgeToken = releaseToken;
|
|
378
|
+
if (updateVaults) await updateVaults();
|
|
379
|
+
next();
|
|
380
|
+
}, { persistError: true });
|
|
381
|
+
runner.use(pipes.VerifyStateDiff());
|
|
382
|
+
var release_default = runner;
|
|
383
|
+
|
|
384
|
+
//#endregion
|
|
385
|
+
export { MAX_MIGRATION_HOPS, RELEASE_KIND, release_default as default, resolveMigrated };
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { decodeAnySafe, getDelegationRequirements } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
5
|
+
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
6
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
4
7
|
import { toFactoryAddress } from "@arcblock/did-util";
|
|
5
8
|
import { account, delegation, factory, token } from "@ocap/state";
|
|
6
|
-
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
7
9
|
import { BN } from "@ocap/util";
|
|
8
|
-
import { CustomError } from "@ocap/util/lib/error";
|
|
9
10
|
import cloneDeep from "lodash/cloneDeep.js";
|
|
10
11
|
import get from "lodash/get.js";
|
|
11
12
|
import Debug from "debug";
|
|
@@ -47,6 +48,7 @@ runner.use((context, next) => {
|
|
|
47
48
|
context.factoryProps = factoryProps;
|
|
48
49
|
return next();
|
|
49
50
|
});
|
|
51
|
+
markStatelessPrefix(runner);
|
|
50
52
|
runner.use(pipes.ExtractState({
|
|
51
53
|
from: "itx.address",
|
|
52
54
|
to: "factoryState",
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
4
5
|
import { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes } from "./revoke-ledger.mjs";
|
|
5
|
-
import { account, asset, evidence, stake, token } from "@ocap/state";
|
|
6
6
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
7
|
-
import { BN } from "@ocap/util";
|
|
8
7
|
import { CustomError } from "@ocap/util/lib/error";
|
|
8
|
+
import { account, asset, evidence, stake, token } from "@ocap/state";
|
|
9
|
+
import { BN } from "@ocap/util";
|
|
9
10
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
10
11
|
import Debug from "debug";
|
|
11
12
|
import { patterns, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
@@ -27,6 +28,7 @@ runner.use(({ itx }, next) => {
|
|
|
27
28
|
const { error } = vValidate(schema, itx);
|
|
28
29
|
return next(error ? new CustomError("INVALID_TX", `Invalid itx: ${error.message}`) : void 0);
|
|
29
30
|
});
|
|
31
|
+
markStatelessPrefix(runner);
|
|
30
32
|
runner.use(pipes.ExtractState({
|
|
31
33
|
from: "tx.from",
|
|
32
34
|
to: "senderState",
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
5
5
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
6
|
-
import { BN } from "@ocap/util";
|
|
7
6
|
import { CustomError } from "@ocap/util/lib/error";
|
|
8
7
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
8
|
+
import { account, asset, stake, token } from "@ocap/state";
|
|
9
|
+
import { BN } from "@ocap/util";
|
|
9
10
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
10
11
|
import Debug from "debug";
|
|
11
12
|
import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
@@ -50,6 +51,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
|
|
|
50
51
|
"tokens",
|
|
51
52
|
"assets"
|
|
52
53
|
] }));
|
|
54
|
+
markStatelessPrefix(runner);
|
|
53
55
|
runner.use(pipes.ExtractState({
|
|
54
56
|
from: "tx.from",
|
|
55
57
|
to: "senderState",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Runner } from "@ocap/tx-pipeline";
|
|
2
2
|
import { BN } from "@ocap/util";
|
|
3
|
-
import { IReadyContext, IWithAssets, IWithReceivers, IWithSender, IWithStake, IWithTokens, TRevokeStakeTx } from "@ocap/types";
|
|
3
|
+
import { IReadyContext, IWithAssets, IWithReceivers, IWithSender, IWithStake, IWithToken, IWithTokenFactory, IWithTokens, TRevokeStakeTx } from "@ocap/types";
|
|
4
4
|
|
|
5
5
|
//#region src/protocols/governance/revoke-stake.d.ts
|
|
6
6
|
/** Token input type */
|
|
@@ -29,7 +29,12 @@ interface TokenCondition {
|
|
|
29
29
|
* Phase: IReadyContext (after TakeStateSnapshot)
|
|
30
30
|
* Mixins: IWithSender, IWithStake, IWithReceivers, IWithTokens, IWithAssets
|
|
31
31
|
*/
|
|
32
|
-
type Context = IReadyContext<TRevokeStakeTx> & IWithSender & IWithStake & Partial<IWithReceivers> & Partial<IWithTokens> & Partial<IWithAssets> & {
|
|
32
|
+
type Context = IReadyContext<TRevokeStakeTx> & IWithSender & IWithStake & Partial<IWithReceivers> & Partial<IWithTokens> & Partial<IWithAssets> & Partial<Pick<IWithToken, 'tokenState'>> & Partial<IWithTokenFactory> & {
|
|
33
|
+
/**
|
|
34
|
+
* Set when a locked Stake-for-Token may be released (#1422): `retire` when this tx also retires the factory,
|
|
35
|
+
* `retired` when the factory was retired before.
|
|
36
|
+
*/
|
|
37
|
+
tokenStakeRelease?: 'retire' | 'retired';
|
|
33
38
|
/** Parsed outputs from itx */
|
|
34
39
|
outputs?: MultiOutput[];
|
|
35
40
|
/** Receiver addresses from outputs */
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { applyTokenUpdates } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
4
5
|
import { recordStakeRevoke } from "./revoke-ledger.mjs";
|
|
5
|
-
import { account, stake } from "@ocap/state";
|
|
6
6
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
7
|
-
import { BN } from "@ocap/util";
|
|
8
7
|
import { CustomError } from "@ocap/util/lib/error";
|
|
9
8
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
9
|
+
import { account, stake, tokenFactory } from "@ocap/state";
|
|
10
|
+
import { BN, isSameDid } from "@ocap/util";
|
|
10
11
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
11
12
|
import Debug from "debug";
|
|
12
13
|
import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
13
14
|
import isEmpty from "lodash/isEmpty.js";
|
|
15
|
+
import { isTokenFullyRedeemed, isTokenIssuanceStakeOf } from "@ocap/tx-pipeline/lib/pipes/post-execution-invariant-gate";
|
|
14
16
|
|
|
15
17
|
//#region src/protocols/governance/revoke-stake.ts
|
|
16
18
|
const debug = Debug("@ocap/tx-protocols:revoke-stake");
|
|
@@ -49,6 +51,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
|
|
|
49
51
|
"tokens",
|
|
50
52
|
"assets"
|
|
51
53
|
] }));
|
|
54
|
+
markStatelessPrefix(runner);
|
|
52
55
|
runner.use(pipes.ExtractState({
|
|
53
56
|
from: "tx.from",
|
|
54
57
|
to: "senderState",
|
|
@@ -76,31 +79,46 @@ runner.use(pipes.ExtractState({
|
|
|
76
79
|
status: "INVALID_STAKE_STATE",
|
|
77
80
|
table: "stake"
|
|
78
81
|
}));
|
|
79
|
-
runner.use(pipes.VerifyInfo([
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return getRelatedAddresses(context.senderState).includes(context.stakeState.sender);
|
|
86
|
-
}
|
|
87
|
-
},
|
|
88
|
-
{
|
|
89
|
-
error: "STAKE_NOT_REVOCABLE",
|
|
90
|
-
message: "This stake address is not revocable",
|
|
91
|
-
fn: (ctx) => {
|
|
92
|
-
return ctx.stakeState.revocable;
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
error: "INVALID_TX",
|
|
97
|
-
message: "Can not revoke assets that are not locked in the stake",
|
|
98
|
-
fn: (ctx) => {
|
|
99
|
-
const context = ctx;
|
|
100
|
-
return (context.assets || []).every((x) => (context.stakeState.assets || []).includes(x));
|
|
101
|
-
}
|
|
82
|
+
runner.use(pipes.VerifyInfo([{
|
|
83
|
+
error: "SENDER_NOT_MATCH",
|
|
84
|
+
message: "You are not allowed to revoke stake from this address",
|
|
85
|
+
fn: (ctx) => {
|
|
86
|
+
const context = ctx;
|
|
87
|
+
return getRelatedAddresses(context.senderState).includes(context.stakeState.sender);
|
|
102
88
|
}
|
|
103
|
-
]));
|
|
89
|
+
}]));
|
|
90
|
+
runner.use(async (context, next) => {
|
|
91
|
+
const { stakeState, senderState, statedb, config } = context;
|
|
92
|
+
if (stakeState.revocable !== false) return next();
|
|
93
|
+
const notRevocable = (reason = "") => next(new CustomError("STAKE_NOT_REVOCABLE", `This stake address is not revocable${reason ? `: ${reason}` : ""}`));
|
|
94
|
+
const officialToken = config.token?.address || "";
|
|
95
|
+
const symbol = stakeState.nonce;
|
|
96
|
+
if (!officialToken || typeof symbol !== "string" || !symbol || !isSameDid(stakeState.receiver, officialToken)) return notRevocable();
|
|
97
|
+
const tokenAddress = await statedb.token.getAddressBySymbol(symbol.toUpperCase(), context);
|
|
98
|
+
const tokenState = tokenAddress ? await statedb.token.get(tokenAddress, context) : null;
|
|
99
|
+
if (!tokenState || !isTokenIssuanceStakeOf(stakeState, tokenState, officialToken)) return notRevocable();
|
|
100
|
+
const tokenFactoryState = await statedb.tokenFactory.get(tokenState.tokenFactoryAddress, context);
|
|
101
|
+
if (!tokenFactoryState) return notRevocable();
|
|
102
|
+
const label = `token ${tokenState.symbol} (${tokenState.address})`;
|
|
103
|
+
if (!isTokenFullyRedeemed(tokenState, tokenFactoryState)) return notRevocable(`the stake for ${label} stays locked until 100% of its supply is burned`);
|
|
104
|
+
const factoryStatus = tokenFactoryState.status || "ACTIVE";
|
|
105
|
+
if (factoryStatus === "ACTIVE") {
|
|
106
|
+
if (!getRelatedAddresses(senderState).some((x) => isSameDid(x, tokenFactoryState.owner))) return notRevocable(`only the current owner of the token factory can retire ${label}`);
|
|
107
|
+
context.tokenStakeRelease = "retire";
|
|
108
|
+
} else if (factoryStatus === "RETIRED") context.tokenStakeRelease = "retired";
|
|
109
|
+
else return notRevocable(`token factory of ${label} is ${factoryStatus}`);
|
|
110
|
+
context.tokenState = tokenState;
|
|
111
|
+
context.tokenFactoryState = tokenFactoryState;
|
|
112
|
+
return next();
|
|
113
|
+
});
|
|
114
|
+
runner.use(pipes.VerifyInfo([{
|
|
115
|
+
error: "INVALID_TX",
|
|
116
|
+
message: "Can not revoke assets that are not locked in the stake",
|
|
117
|
+
fn: (ctx) => {
|
|
118
|
+
const context = ctx;
|
|
119
|
+
return (context.assets || []).every((x) => (context.stakeState.assets || []).includes(x));
|
|
120
|
+
}
|
|
121
|
+
}]));
|
|
104
122
|
runner.use(pipes.ExtractState({
|
|
105
123
|
from: "tokens",
|
|
106
124
|
to: "tokenStates",
|
|
@@ -140,15 +158,16 @@ runner.use(pipes.VerifyUpdater({
|
|
|
140
158
|
assetKey: "assetStates",
|
|
141
159
|
ownerKey: "stakeState"
|
|
142
160
|
}));
|
|
143
|
-
runner.use(ensure_gas_default(() => ({
|
|
161
|
+
runner.use(ensure_gas_default((context) => ({
|
|
144
162
|
create: 0,
|
|
145
|
-
update: 2,
|
|
163
|
+
update: context.tokenStakeRelease === "retire" ? 3 : 2,
|
|
146
164
|
payment: 0
|
|
147
165
|
})));
|
|
148
166
|
runner.use(ensure_cost_default({ attachSenderChanges: true }));
|
|
149
167
|
runner.use(pipes.TakeStateSnapshot());
|
|
150
168
|
runner.use(async (context, next) => {
|
|
151
169
|
const { tx: tx$1, itx, outputs = [], statedb, senderState, senderUpdates, stakeState, updateVaults } = context;
|
|
170
|
+
const { tokenStakeRelease, tokenFactoryState } = context;
|
|
152
171
|
const stakeUpdates = {
|
|
153
172
|
tokens: stakeState.tokens || {},
|
|
154
173
|
assets: stakeState.assets || [],
|
|
@@ -163,6 +182,7 @@ runner.use(async (context, next) => {
|
|
|
163
182
|
stakeUpdates.revokedTokens = applyTokenUpdates(tokensList, { tokens: stakeUpdates.revokedTokens }, "add").tokens;
|
|
164
183
|
stakeUpdates.revokedAssets = stakeUpdates.revokedAssets.concat(...assetsList);
|
|
165
184
|
});
|
|
185
|
+
if (tokenStakeRelease === "retire") context.tokenFactoryState = await statedb.tokenFactory.update(tokenFactoryState.address, tokenFactory.update(tokenFactoryState, { status: "RETIRED" }, context), context);
|
|
166
186
|
const [newSenderState, newStakeState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
|
|
167
187
|
nonce: tx$1.nonce,
|
|
168
188
|
...senderUpdates
|
|
@@ -173,6 +193,7 @@ runner.use(async (context, next) => {
|
|
|
173
193
|
const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState.context?.renaissanceTime;
|
|
174
194
|
return statedb.stake.update(stakeState.address, stake.update(stakeState, {
|
|
175
195
|
...stakeUpdates,
|
|
196
|
+
...tokenStakeRelease ? { revocable: true } : {},
|
|
176
197
|
context: {
|
|
177
198
|
...stakeState.context,
|
|
178
199
|
revokes: nextRevokes
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
+
import { markStatelessPrefix } from "../../stateless-prefix.mjs";
|
|
4
5
|
import { slashStakeRevokes } from "./revoke-ledger.mjs";
|
|
5
|
-
import { toTypeInfo } from "@arcblock/did";
|
|
6
6
|
import { types } from "@ocap/mcrypto";
|
|
7
|
-
import { account, asset, stake, token } from "@ocap/state";
|
|
8
7
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
9
|
-
import { BN } from "@ocap/util";
|
|
10
8
|
import { CustomError } from "@ocap/util/lib/error";
|
|
11
9
|
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
10
|
+
import { toTypeInfo } from "@arcblock/did";
|
|
11
|
+
import { account, asset, stake, token } from "@ocap/state";
|
|
12
|
+
import { BN } from "@ocap/util";
|
|
12
13
|
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
13
14
|
import Debug from "debug";
|
|
14
15
|
import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
@@ -53,6 +54,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
|
|
|
53
54
|
"tokens",
|
|
54
55
|
"assets"
|
|
55
56
|
] }));
|
|
57
|
+
markStatelessPrefix(runner);
|
|
56
58
|
runner.use(pipes.ExtractState({
|
|
57
59
|
from: "tx.from",
|
|
58
60
|
to: "senderState",
|