@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.
Files changed (164) hide show
  1. package/esm/bridge-release-crypto.d.mts +39 -0
  2. package/esm/bridge-release-crypto.mjs +88 -0
  3. package/esm/bridge-release-window.d.mts +47 -0
  4. package/esm/bridge-release-window.mjs +62 -0
  5. package/esm/bridge-reserve.d.mts +24 -0
  6. package/esm/bridge-reserve.mjs +41 -0
  7. package/esm/execute.d.mts +5 -3
  8. package/esm/execute.mjs +593 -21
  9. package/esm/gas-security-guard.d.mts +7 -2
  10. package/esm/gas-security-guard.mjs +25 -16
  11. package/esm/index.d.mts +38 -19
  12. package/esm/index.mjs +7 -3
  13. package/esm/pipes/ensure-cost.mjs +36 -10
  14. package/esm/pipes/write-ledger.d.mts +2 -2
  15. package/esm/pipes/write-ledger.mjs +6 -3
  16. package/esm/protocols/account/delegate.mjs +6 -4
  17. package/esm/protocols/account/migrate.mjs +5 -3
  18. package/esm/protocols/account/revoke-delegate.mjs +5 -3
  19. package/esm/protocols/asset/acquire-v2.mjs +3 -1
  20. package/esm/protocols/asset/acquire-v3.mjs +4 -2
  21. package/esm/protocols/asset/consume.mjs +3 -1
  22. package/esm/protocols/asset/create.mjs +4 -2
  23. package/esm/protocols/asset/mint.mjs +4 -2
  24. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
  25. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  26. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
  27. package/esm/protocols/asset/update.mjs +4 -2
  28. package/esm/protocols/bridge/release.d.mts +34 -0
  29. package/esm/protocols/bridge/release.mjs +385 -0
  30. package/esm/protocols/factory/create.mjs +4 -2
  31. package/esm/protocols/governance/claim-stake.mjs +35 -11
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  34. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  35. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  36. package/esm/protocols/governance/revoke-stake.mjs +58 -29
  37. package/esm/protocols/governance/slash-stake.mjs +14 -4
  38. package/esm/protocols/governance/stake.mjs +6 -4
  39. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  40. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  41. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  42. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  43. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  44. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  45. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  46. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  47. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  48. package/esm/protocols/rollup/close.d.mts +2 -1
  49. package/esm/protocols/rollup/close.mjs +59 -6
  50. package/esm/protocols/rollup/create-block.mjs +4 -2
  51. package/esm/protocols/rollup/create.d.mts +3 -0
  52. package/esm/protocols/rollup/create.mjs +45 -6
  53. package/esm/protocols/rollup/join.d.mts +2 -1
  54. package/esm/protocols/rollup/join.mjs +31 -23
  55. package/esm/protocols/rollup/leave.d.mts +2 -1
  56. package/esm/protocols/rollup/leave.mjs +32 -24
  57. package/esm/protocols/rollup/migrate.d.mts +2 -1
  58. package/esm/protocols/rollup/migrate.mjs +19 -10
  59. package/esm/protocols/rollup/pause.d.mts +4 -1
  60. package/esm/protocols/rollup/pause.mjs +50 -6
  61. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  62. package/esm/protocols/rollup/resume.d.mts +2 -1
  63. package/esm/protocols/rollup/resume.mjs +26 -6
  64. package/esm/protocols/rollup/update.d.mts +5 -1
  65. package/esm/protocols/rollup/update.mjs +56 -9
  66. package/esm/protocols/token/create.mjs +4 -2
  67. package/esm/protocols/token/deposit-v2.mjs +5 -3
  68. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  69. package/esm/protocols/token-factory/burn.mjs +4 -2
  70. package/esm/protocols/token-factory/create.mjs +8 -4
  71. package/esm/protocols/token-factory/mint.mjs +4 -2
  72. package/esm/protocols/token-factory/update.mjs +20 -5
  73. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  74. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  75. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  76. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  77. package/esm/stateless-prefix.d.mts +16 -0
  78. package/esm/stateless-prefix.mjs +82 -0
  79. package/esm/tx-timer.d.mts +1 -1
  80. package/esm/tx-timer.mjs +1 -1
  81. package/esm/util.mjs +2 -2
  82. package/lib/bridge-release-crypto.cjs +93 -0
  83. package/lib/bridge-release-crypto.d.cts +39 -0
  84. package/lib/bridge-release-window.cjs +69 -0
  85. package/lib/bridge-release-window.d.cts +47 -0
  86. package/lib/bridge-reserve.cjs +45 -0
  87. package/lib/bridge-reserve.d.cts +24 -0
  88. package/lib/execute.cjs +594 -19
  89. package/lib/execute.d.cts +4 -2
  90. package/lib/gas-security-guard.cjs +25 -16
  91. package/lib/gas-security-guard.d.cts +7 -2
  92. package/lib/index.cjs +10 -1
  93. package/lib/index.d.cts +37 -18
  94. package/lib/pipes/ensure-cost.cjs +37 -11
  95. package/lib/pipes/write-ledger.cjs +6 -3
  96. package/lib/pipes/write-ledger.d.cts +2 -2
  97. package/lib/protocols/account/delegate.cjs +6 -4
  98. package/lib/protocols/account/migrate.cjs +5 -3
  99. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  100. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  101. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  102. package/lib/protocols/asset/consume.cjs +3 -1
  103. package/lib/protocols/asset/create.cjs +4 -2
  104. package/lib/protocols/asset/mint.cjs +4 -2
  105. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  106. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  107. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  108. package/lib/protocols/asset/update.cjs +4 -2
  109. package/lib/protocols/bridge/release.cjs +390 -0
  110. package/lib/protocols/bridge/release.d.cts +34 -0
  111. package/lib/protocols/factory/create.cjs +4 -2
  112. package/lib/protocols/governance/claim-stake.cjs +35 -11
  113. package/lib/protocols/governance/return-stake.cjs +4 -2
  114. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  115. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  116. package/lib/protocols/governance/revoke-stake.cjs +58 -29
  117. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  118. package/lib/protocols/governance/slash-stake.cjs +14 -4
  119. package/lib/protocols/governance/stake.cjs +6 -4
  120. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  121. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  122. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  123. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  124. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  125. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  126. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  127. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  128. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  129. package/lib/protocols/rollup/close.cjs +59 -6
  130. package/lib/protocols/rollup/close.d.cts +2 -1
  131. package/lib/protocols/rollup/create-block.cjs +4 -2
  132. package/lib/protocols/rollup/create.cjs +45 -6
  133. package/lib/protocols/rollup/create.d.cts +3 -0
  134. package/lib/protocols/rollup/join.cjs +31 -23
  135. package/lib/protocols/rollup/join.d.cts +2 -1
  136. package/lib/protocols/rollup/leave.cjs +32 -24
  137. package/lib/protocols/rollup/leave.d.cts +2 -1
  138. package/lib/protocols/rollup/migrate.cjs +19 -10
  139. package/lib/protocols/rollup/migrate.d.cts +2 -1
  140. package/lib/protocols/rollup/pause.cjs +50 -6
  141. package/lib/protocols/rollup/pause.d.cts +4 -1
  142. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  143. package/lib/protocols/rollup/resume.cjs +26 -6
  144. package/lib/protocols/rollup/resume.d.cts +2 -1
  145. package/lib/protocols/rollup/update.cjs +56 -9
  146. package/lib/protocols/rollup/update.d.cts +5 -1
  147. package/lib/protocols/token/create.cjs +4 -2
  148. package/lib/protocols/token/deposit-v2.cjs +5 -3
  149. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  150. package/lib/protocols/token-factory/burn.cjs +4 -2
  151. package/lib/protocols/token-factory/create.cjs +8 -4
  152. package/lib/protocols/token-factory/mint.cjs +4 -2
  153. package/lib/protocols/token-factory/update.cjs +20 -5
  154. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  155. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  156. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  157. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  158. package/lib/stateless-prefix.cjs +88 -0
  159. package/lib/stateless-prefix.d.cts +16 -0
  160. package/lib/tx-timer.cjs +1 -1
  161. package/lib/tx-timer.d.cts +1 -1
  162. package/lib/util.cjs +2 -2
  163. package/package.json +16 -16
  164. package/tools/fixtures.ts +9 -4
@@ -1,17 +1,18 @@
1
1
  import { applyTokenChange, applyTokenUpdates, 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";
4
5
  import exec_mint_hook_default, { getMintTokenPayLegs, verifyMintHook } from "./pipes/exec-mint-hook.mjs";
5
6
  import extract_factory_tokens_default from "./pipes/extract-factory-tokens.mjs";
6
7
  import verify_itx_address_default from "./pipes/verify-itx-address.mjs";
7
8
  import verify_itx_assets_default from "./pipes/verify-itx-assets.mjs";
8
9
  import verify_itx_variables_default from "./pipes/verify-itx-variables.mjs";
9
10
  import verify_mint_limit_default from "./pipes/verify-mint-limit.mjs";
10
- import { account, asset, delegation, factory } from "@ocap/state";
11
11
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
12
- import { BN, isSameDid } from "@ocap/util";
13
12
  import { CustomError } from "@ocap/util/lib/error";
14
13
  import { getListField } from "@ocap/util/lib/get-list-field";
14
+ import { account, asset, delegation, factory } from "@ocap/state";
15
+ import { BN, isSameDid } from "@ocap/util";
15
16
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
16
17
  import Debug from "debug";
17
18
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -46,6 +47,7 @@ runner.use(({ itx }, next) => {
46
47
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
47
48
  return next();
48
49
  });
50
+ markStatelessPrefix(runner);
49
51
  runner.use(pipes.ExtractState({
50
52
  from: "itx.address",
51
53
  to: "duplicateAsset",
@@ -1,8 +1,9 @@
1
1
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
- import { account, asset, token } from "@ocap/state";
3
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
4
4
  import { Runner, pipes } from "@ocap/tx-pipeline";
5
5
  import { CustomError } from "@ocap/util/lib/error";
6
+ import { account, asset, token } from "@ocap/state";
6
7
  import Debug from "debug";
7
8
  import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
8
9
 
@@ -22,6 +23,7 @@ runner.use((context, next) => {
22
23
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
23
24
  return next();
24
25
  });
26
+ markStatelessPrefix(runner);
25
27
  runner.use(pipes.ExtractState({
26
28
  from: "itx.address",
27
29
  to: "assetState",
@@ -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 { toAssetAddress } from "@arcblock/did-util";
5
- import { account, asset, delegation } from "@ocap/state";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
6
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
7
6
  import { CustomError } from "@ocap/util/lib/error";
8
7
  import { getListField } from "@ocap/util/lib/get-list-field";
8
+ import { toAssetAddress } from "@arcblock/did-util";
9
+ import { account, asset, delegation } from "@ocap/state";
9
10
  import cloneDeep from "lodash/cloneDeep.js";
10
11
  import Debug from "debug";
11
12
  import { formatMessage } from "@ocap/message";
@@ -34,6 +35,7 @@ runner.use(pipes.VerifyInfo([{
34
35
  return toAssetAddress(itx, context.txEncoding) === context.itx.address;
35
36
  }
36
37
  }]));
38
+ markStatelessPrefix(runner);
37
39
  runner.use(pipes.VerifyMultiSigV2({ signersKey: "signers" }));
38
40
  runner.use(pipes.ExtractState({
39
41
  from: "itx.address",
@@ -1,13 +1,14 @@
1
1
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
3
4
  import verify_itx_address_default from "./pipes/verify-itx-address.mjs";
4
5
  import verify_itx_assets_default from "./pipes/verify-itx-assets.mjs";
5
6
  import verify_itx_variables_default from "./pipes/verify-itx-variables.mjs";
6
7
  import verify_mint_limit_default from "./pipes/verify-mint-limit.mjs";
7
- import { account, asset, factory } from "@ocap/state";
8
8
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
9
- import { isSameDid } from "@ocap/util";
10
9
  import { CustomError } from "@ocap/util/lib/error";
10
+ import { account, asset, factory } from "@ocap/state";
11
+ import { isSameDid } from "@ocap/util";
11
12
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
13
  import Debug from "debug";
13
14
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -38,6 +39,7 @@ runner.use(({ itx }, next) => {
38
39
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
39
40
  return next();
40
41
  });
42
+ markStatelessPrefix(runner);
41
43
  runner.use(pipes.ExtractState({
42
44
  from: "itx.address",
43
45
  to: "duplicateAsset",
@@ -1,7 +1,7 @@
1
1
  import transfer_default from "../calls/transfer.mjs";
2
2
  import transfer_token_default from "../calls/transfer-token.mjs";
3
- import { BN } from "@ocap/util";
4
3
  import { CustomError } from "@ocap/util/lib/error";
4
+ import { BN } from "@ocap/util";
5
5
  import cloneDeep from "lodash/cloneDeep.js";
6
6
 
7
7
  //#region src/protocols/asset/pipes/exec-mint-hook.ts
@@ -1,5 +1,5 @@
1
- import { isFromPublicKey, normalizePublicKeyHex } from "@arcblock/did";
2
1
  import { CustomError } from "@ocap/util/lib/error";
2
+ import { isFromPublicKey, normalizePublicKeyHex } from "@arcblock/did";
3
3
  import Debug from "debug";
4
4
  import { mintFromFactory } from "@ocap/asset";
5
5
 
@@ -1,6 +1,6 @@
1
- import { token } from "@ocap/state";
2
1
  import { CustomError } from "@ocap/util/lib/error";
3
2
  import { getListField } from "@ocap/util/lib/get-list-field";
3
+ import { token } from "@ocap/state";
4
4
 
5
5
  //#region src/protocols/asset/pipes/verify-itx-assets.ts
6
6
  const verify_itx_assets = (context, next) => {
@@ -1,12 +1,13 @@
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";
4
5
  import verify_ownership_default from "../token-factory/pipes/verify-ownership.mjs";
5
6
  import verify_url_default from "../token-factory/pipes/verify-url.mjs";
6
- import { account, asset, delegation, token } from "@ocap/state";
7
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
- import { isSameDid } from "@ocap/util";
9
8
  import { CustomError } from "@ocap/util/lib/error";
9
+ import { account, asset, delegation, token } from "@ocap/state";
10
+ import { isSameDid } from "@ocap/util";
10
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
11
12
  import Debug from "debug";
12
13
  import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -34,6 +35,7 @@ runner.use((context, next) => {
34
35
  context.newData = decodeAnySafe(itx.data ?? null);
35
36
  return next();
36
37
  });
38
+ markStatelessPrefix(runner);
37
39
  runner.use(pipes.ExtractState({
38
40
  from: "itx.address",
39
41
  to: "assetState",
@@ -0,0 +1,34 @@
1
+ import { ReleaseResolution, Runner } from "@ocap/tx-pipeline";
2
+
3
+ //#region src/protocols/bridge/release.d.ts
4
+ declare const RELEASE_KIND: {
5
+ readonly DEPOSIT: 1;
6
+ readonly REFUND: 2;
7
+ readonly DEPOSIT_B: 3;
8
+ };
9
+ /** `resolveMigrated` follows at most this many `migratedTo` links of an ACCOUNT (check 6) */
10
+ declare const MAX_MIGRATION_HOPS = 8;
11
+ interface ReleaseItx {
12
+ kind: number;
13
+ bridge: string;
14
+ evidence: string;
15
+ ordinal: number;
16
+ to: string;
17
+ amount: string;
18
+ ethChainId: string;
19
+ epoch: number;
20
+ ethSender: string;
21
+ claimSignature: string;
22
+ signaturesList: string[];
23
+ }
24
+ type Context = Record<string, any> & {
25
+ itx: ReleaseItx;
26
+ /** what `resolveBridgeForRelease` found: the bridge, its reserve and the reserves a refund may draw on */
27
+ release?: ReleaseResolution;
28
+ releaseAmount?: bigint;
29
+ releaseTimeMs?: number;
30
+ };
31
+ declare const runner: Runner<Context>;
32
+ declare function resolveMigrated(context: Context, address: string): Promise<string | null>;
33
+ //#endregion
34
+ export { Context, MAX_MIGRATION_HOPS, RELEASE_KIND, ReleaseItx, runner as default, resolveMigrated };
@@ -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",