@ocap/tx-protocols 1.30.26 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/esm/execute.d.mts +7 -0
  2. package/esm/execute.mjs +196 -71
  3. package/esm/gas-security-guard.d.mts +374 -0
  4. package/esm/gas-security-guard.mjs +1101 -0
  5. package/esm/index.d.mts +35 -5
  6. package/esm/index.mjs +3 -1
  7. package/esm/pipes/ensure-cost.mjs +314 -58
  8. package/esm/protocols/account/delegate.mjs +64 -16
  9. package/esm/protocols/account/migrate.d.mts +3 -0
  10. package/esm/protocols/account/migrate.mjs +235 -35
  11. package/esm/protocols/account/revoke-delegate.d.mts +3 -3
  12. package/esm/protocols/account/revoke-delegate.mjs +70 -38
  13. package/esm/protocols/asset/acquire-v2.mjs +29 -12
  14. package/esm/protocols/asset/acquire-v3.mjs +78 -22
  15. package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
  16. package/esm/protocols/asset/calls/transfer.mjs +1 -0
  17. package/esm/protocols/asset/consume.mjs +12 -4
  18. package/esm/protocols/asset/create.mjs +18 -5
  19. package/esm/protocols/asset/mint.mjs +23 -1
  20. package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
  21. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
  22. package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
  23. package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
  24. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
  25. package/esm/protocols/asset/update.d.mts +13 -2
  26. package/esm/protocols/asset/update.mjs +133 -14
  27. package/esm/protocols/factory/create.mjs +14 -6
  28. package/esm/protocols/governance/claim-stake.mjs +92 -10
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-stake.mjs +17 -5
  31. package/esm/protocols/governance/slash-stake.mjs +64 -25
  32. package/esm/protocols/governance/stake.mjs +63 -13
  33. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  34. package/esm/protocols/rollup/close.mjs +1 -1
  35. package/esm/protocols/rollup/create-block.mjs +8 -7
  36. package/esm/protocols/rollup/create.mjs +17 -6
  37. package/esm/protocols/rollup/join.mjs +3 -3
  38. package/esm/protocols/rollup/leave.mjs +1 -1
  39. package/esm/protocols/rollup/migrate.mjs +7 -4
  40. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  41. package/esm/protocols/rollup/update.mjs +6 -1
  42. package/esm/protocols/token/create.mjs +23 -12
  43. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  44. package/esm/protocols/token/deposit-v2.mjs +81 -29
  45. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  46. package/esm/protocols/token-factory/burn.mjs +43 -10
  47. package/esm/protocols/token-factory/create.mjs +23 -14
  48. package/esm/protocols/token-factory/mint.mjs +54 -21
  49. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  50. package/esm/protocols/token-factory/update.mjs +16 -6
  51. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  52. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  53. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  54. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  55. package/esm/util.d.mts +3 -1
  56. package/esm/util.mjs +26 -17
  57. package/lib/execute.cjs +193 -67
  58. package/lib/execute.d.cts +7 -0
  59. package/lib/gas-security-guard.cjs +1140 -0
  60. package/lib/gas-security-guard.d.cts +374 -0
  61. package/lib/index.cjs +122 -1
  62. package/lib/index.d.cts +36 -6
  63. package/lib/pipes/ensure-cost.cjs +313 -57
  64. package/lib/protocols/account/delegate.cjs +64 -16
  65. package/lib/protocols/account/migrate.cjs +235 -35
  66. package/lib/protocols/account/migrate.d.cts +3 -0
  67. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  68. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  69. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  70. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  71. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  72. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  73. package/lib/protocols/asset/consume.cjs +11 -3
  74. package/lib/protocols/asset/create.cjs +19 -6
  75. package/lib/protocols/asset/mint.cjs +23 -1
  76. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  77. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  78. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  79. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  80. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  81. package/lib/protocols/asset/update.cjs +131 -12
  82. package/lib/protocols/asset/update.d.cts +13 -2
  83. package/lib/protocols/factory/create.cjs +14 -6
  84. package/lib/protocols/governance/claim-stake.cjs +92 -9
  85. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  86. package/lib/protocols/governance/return-stake.cjs +44 -11
  87. package/lib/protocols/governance/return-stake.d.cts +1 -1
  88. package/lib/protocols/governance/revoke-stake.cjs +17 -5
  89. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  90. package/lib/protocols/governance/slash-stake.cjs +64 -24
  91. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  92. package/lib/protocols/governance/stake.cjs +65 -14
  93. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  94. package/lib/protocols/rollup/close.cjs +1 -1
  95. package/lib/protocols/rollup/create-block.cjs +9 -8
  96. package/lib/protocols/rollup/create-block.d.cts +1 -1
  97. package/lib/protocols/rollup/create.cjs +18 -7
  98. package/lib/protocols/rollup/join.cjs +3 -3
  99. package/lib/protocols/rollup/leave.cjs +1 -1
  100. package/lib/protocols/rollup/migrate.cjs +7 -4
  101. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  102. package/lib/protocols/rollup/update.cjs +6 -1
  103. package/lib/protocols/token/create.cjs +24 -13
  104. package/lib/protocols/token/deposit-v2.cjs +80 -28
  105. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  106. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  107. package/lib/protocols/token-factory/burn.cjs +42 -9
  108. package/lib/protocols/token-factory/create.cjs +24 -15
  109. package/lib/protocols/token-factory/mint.cjs +53 -20
  110. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  111. package/lib/protocols/token-factory/update.cjs +16 -6
  112. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  113. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  114. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  115. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  116. package/lib/util.cjs +26 -17
  117. package/lib/util.d.cts +4 -2
  118. package/package.json +16 -16
@@ -1,18 +1,25 @@
1
1
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
+ import { toDelegateAddress } from "@arcblock/did-util";
3
4
  import { account, delegation } from "@ocap/state";
4
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
+ import { scopeMatch, scopeMatchAny } from "@ocap/util";
5
7
  import { CustomError } from "@ocap/util/lib/error";
6
- import get from "lodash/get.js";
7
- import { toDelegateAddress } from "@arcblock/did-util";
8
- import Debug from "debug";
9
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
10
  import cloneDeep from "lodash/cloneDeep.js";
11
+ import get from "lodash/get.js";
12
+ import Debug from "debug";
11
13
  import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
12
14
 
13
15
  //#region src/protocols/account/revoke-delegate.ts
14
16
  const debug = Debug("@ocap/tx-protocols:delegate");
15
17
  const runner = new Runner("revoke_delegate");
18
+ runner.use((context, next) => {
19
+ const signatures = getListField(context.tx, "signatures");
20
+ if (context.tx?.delegator || signatures.some((s) => Boolean(s?.delegator))) return next(new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false }));
21
+ return next();
22
+ });
16
23
  runner.use(pipes.VerifyMultiSig(0));
17
24
  const schema = v.pipe(v.object({
18
25
  address: vDID({
@@ -20,7 +27,7 @@ const schema = v.pipe(v.object({
20
27
  role: "ROLE_DELEGATION"
21
28
  }),
22
29
  to: vDID({ prefix: true }),
23
- typeUrlsList: v.pipe(v.array(v.string()), v.minLength(1)),
30
+ typeUrlsList: v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(256))), v.minLength(1), v.maxLength(128), v.check((arr) => new Set(arr).size === arr.length, "typeUrlsList must not contain duplicates")),
24
31
  data: v.optional(v.nullable(v.any()))
25
32
  }), vStripUnknown());
26
33
  runner.use((context, next) => {
@@ -28,39 +35,51 @@ runner.use((context, next) => {
28
35
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
29
36
  return next();
30
37
  });
31
- runner.use(pipes.VerifyInfo([
32
- {
33
- error: "OK",
34
- fn: (ctx) => {
35
- const context = ctx;
36
- context.typeUrls = getListField(context, "itx.typeUrls");
37
- return true;
38
- }
39
- },
40
- {
41
- error: "INVALID_TX",
42
- message: "Delegation address does not match",
43
- fn: (ctx) => {
44
- const context = ctx;
45
- return toDelegateAddress(context.tx.from, context.itx.to) === context.itx.address;
46
- }
47
- },
48
- {
49
- error: "INVALID_DELEGATION_TYPE_URL",
50
- message: "Delegation type url is not allowed",
51
- fn: (ctx) => {
52
- const context = ctx;
53
- const allowed = get(context.config, "transaction.delegate.typeUrls", []);
54
- return (context.typeUrls || []).every((x) => allowed.includes(x));
55
- }
56
- }
57
- ]));
58
38
  runner.use(pipes.ExtractState({
59
- from: "itx.address",
60
- to: "delegationState",
61
- status: "INVALID_DELEGATION",
62
- table: "delegation"
39
+ from: "itx.to",
40
+ to: "receiverState",
41
+ status: "OK",
42
+ table: "account"
63
43
  }));
44
+ runner.use(pipes.VerifyInfo([{
45
+ error: "OK",
46
+ fn: (ctx) => {
47
+ const context = ctx;
48
+ context.typeUrls = getListField(context, "itx.typeUrls");
49
+ return true;
50
+ }
51
+ }, {
52
+ error: "INVALID_TX",
53
+ message: "Delegation address does not match",
54
+ fn: (ctx) => {
55
+ const context = ctx;
56
+ if (toDelegateAddress(context.tx.from, context.itx.to) === context.itx.address) return true;
57
+ if (context.receiverState) return getRelatedAddresses(context.receiverState).some((addr) => toDelegateAddress(context.tx.from, addr) === context.itx.address);
58
+ return false;
59
+ }
60
+ }]));
61
+ runner.use(async (context, next) => {
62
+ const { statedb, tx: tx$1, itx, receiverState } = context;
63
+ let delegationState = await statedb.delegation.get(itx.address, context);
64
+ if (!delegationState && receiverState) {
65
+ const related = getRelatedAddresses(receiverState);
66
+ for (const addr of related) {
67
+ const candidateAddr = toDelegateAddress(tx$1.from, addr);
68
+ const candidate = await statedb.delegation.get(candidateAddr, context);
69
+ if (candidate) {
70
+ delegationState = candidate;
71
+ break;
72
+ }
73
+ }
74
+ }
75
+ const allowed = get(context.config, "transaction.delegate.typeUrls", []);
76
+ const typeUrls = context.typeUrls || [];
77
+ const existingOps = delegationState?.ops || {};
78
+ if (!typeUrls.every((x) => Boolean(existingOps[x]) || scopeMatchAny(x, allowed))) return next(new CustomError("INVALID_DELEGATION_TYPE_URL", "Delegation type url is not allowed"));
79
+ if (!delegationState) return next(new CustomError("INVALID_DELEGATION", `Invalid delegation state: ${itx.address}`));
80
+ context.delegationState = delegationState;
81
+ return next();
82
+ });
64
83
  runner.use(pipes.ExtractState({
65
84
  from: "tx.from",
66
85
  to: "senderState",
@@ -85,11 +104,24 @@ runner.use(async (context, next) => {
85
104
  typeUrls
86
105
  });
87
106
  const newOps = cloneDeep(delegationState.ops);
88
- (typeUrls || []).forEach((x) => delete newOps[x]);
107
+ const deniedSubScopes = [];
108
+ (typeUrls || []).forEach((x) => {
109
+ delete newOps[x];
110
+ });
111
+ const remainingOpKeys = Object.keys(newOps);
112
+ (typeUrls || []).forEach((x) => {
113
+ if (remainingOpKeys.some((k) => scopeMatch(x, k))) deniedSubScopes.push(x);
114
+ });
115
+ const newDeny = Array.from(new Set([...delegationState.deny || [], ...deniedSubScopes]));
116
+ const targetDelegationAddress = delegationState.address || itx.address;
89
117
  const [newSenderState, newDelegationState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
90
118
  ...senderUpdates,
91
- nonce: tx$1.nonce
92
- }, context), context), statedb.delegation.update(itx.address, delegation.update(delegationState, { ops: newOps }, context), context)]);
119
+ nonce: tx$1.nonce,
120
+ pk: tx$1.delegator ? senderState.pk : senderState.pk || tx$1.pk
121
+ }, context), context), statedb.delegation.update(targetDelegationAddress, delegation.update(delegationState, {
122
+ ops: newOps,
123
+ deny: newDeny
124
+ }, context), context)]);
93
125
  if (updateVaults) await updateVaults();
94
126
  context.senderState = newSenderState;
95
127
  context.delegationState = newDelegationState;
@@ -1,7 +1,7 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
- import exec_mint_hook_default from "./pipes/exec-mint-hook.mjs";
4
+ import exec_mint_hook_default, { getMintTokenPayLegs, verifyMintHook } from "./pipes/exec-mint-hook.mjs";
5
5
  import extract_factory_tokens_default from "./pipes/extract-factory-tokens.mjs";
6
6
  import verify_itx_address_default from "./pipes/verify-itx-address.mjs";
7
7
  import verify_itx_assets_default from "./pipes/verify-itx-assets.mjs";
@@ -10,8 +10,9 @@ import verify_mint_limit_default from "./pipes/verify-mint-limit.mjs";
10
10
  import { account, asset, delegation, factory } from "@ocap/state";
11
11
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
12
12
  import { CustomError } from "@ocap/util/lib/error";
13
- import Debug from "debug";
14
13
  import { getListField } from "@ocap/util/lib/get-list-field";
14
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
15
+ import Debug from "debug";
15
16
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
16
17
  import { promisify } from "node:util";
17
18
 
@@ -74,6 +75,10 @@ runner.use(pipes.ExtractState({
74
75
  to: "delegatorState",
75
76
  status: "OK"
76
77
  }));
78
+ runner.use(pipes.VerifyAccountMigration({
79
+ stateKey: "delegatorState",
80
+ addressKey: "tx.delegator"
81
+ }));
77
82
  runner.use(pipes.ExtractState({
78
83
  from: "itx.factory",
79
84
  to: "factoryState",
@@ -89,13 +94,14 @@ runner.use(pipes.VerifyDelegation({
89
94
  const ctx = context;
90
95
  const tokens = ctx.factoryTokens || [];
91
96
  const assets = getListField(ctx.itx, "assets") || [];
92
- return [...tokens.map((x) => ({
97
+ const to = ctx.itx?.factory ? [ctx.itx.factory] : [];
98
+ return [...getMintTokenPayLegs(ctx.factoryState, tokens, ctx.config?.token?.address).map((x) => ({
93
99
  type: "token",
94
- address: x.address,
95
- value: String(x.value)
100
+ ...x
96
101
  })), ...assets.map((x) => ({
97
102
  type: "asset",
98
- address: x
103
+ address: x,
104
+ to
99
105
  }))];
100
106
  }
101
107
  }));
@@ -157,7 +163,14 @@ runner.use(pipes.verifyTokenAccess({
157
163
  runner.use(verify_mint_limit_default);
158
164
  runner.use(verify_itx_variables_default);
159
165
  runner.use(verify_itx_address_default("acquire-v2"));
160
- runner.use(pipes.VerifyBlocked({ stateKeys: ["assetOwner"] }));
166
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
167
+ "senderState",
168
+ "delegatorState",
169
+ "factoryOwnerState",
170
+ "issuerStates",
171
+ "issuerState",
172
+ "assetOwner"
173
+ ] }));
161
174
  runner.use(async (context, next) => {
162
175
  const { factoryTokens = [], senderState } = context;
163
176
  const condition = {
@@ -174,16 +187,20 @@ runner.use(async (context, next) => {
174
187
  return next(err);
175
188
  }
176
189
  });
177
- runner.use(pipes.VerifyUpdater({
178
- assetKey: "assetStates",
179
- ownerKey: "assetOwner"
180
- }));
190
+ runner.use((context, next) => {
191
+ const ownerKey = context.assetStates?.length && context.senderState && context.assetStates.every((a) => getRelatedAddresses(context.senderState).includes(a.owner)) ? "senderState" : "assetOwner";
192
+ return pipes.VerifyUpdater({
193
+ assetKey: "assetStates",
194
+ ownerKey
195
+ })(context, next);
196
+ });
181
197
  runner.use(verify_itx_assets_default);
182
198
  runner.use(async (context, next) => {
183
199
  const { itx, assetOwner, assetStates = [] } = context;
184
200
  const consumedAssets = assetStates.map((x) => x.address);
185
201
  return next(await verifyAssetHierarchy([itx.address], assetOwner?.address, context, void 0, consumedAssets) || void 0);
186
202
  });
203
+ runner.use(verifyMintHook);
187
204
  runner.use(ensure_gas_default((context) => {
188
205
  const result = {
189
206
  create: 1,
@@ -200,7 +217,7 @@ runner.use(async (context, next) => {
200
217
  const { tx: tx$1, itx, txTime, statedb, senderState, assetOwner, factoryState, factoryTokens = [], delegationState, mintedAsset, mintedAddress, senderChange, updateVaults, assetStates = [] } = context;
201
218
  const senderUpdates = {
202
219
  nonce: tx$1.nonce,
203
- pk: tx$1.pk,
220
+ pk: tx$1.delegator ? senderState.pk : tx$1.pk,
204
221
  ...applyTokenUpdates(factoryTokens, senderChange ? applyTokenChange(senderState, senderChange) : senderState, "sub")
205
222
  };
206
223
  const ownerUpdates = {};
@@ -1,7 +1,7 @@
1
- import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
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 exec_mint_hook_default from "./pipes/exec-mint-hook.mjs";
4
+ import exec_mint_hook_default, { getMintTokenPayLegs, verifyMintHook } from "./pipes/exec-mint-hook.mjs";
5
5
  import extract_factory_tokens_default from "./pipes/extract-factory-tokens.mjs";
6
6
  import verify_itx_address_default from "./pipes/verify-itx-address.mjs";
7
7
  import verify_itx_assets_default from "./pipes/verify-itx-assets.mjs";
@@ -11,11 +11,13 @@ import { account, asset, delegation, factory } from "@ocap/state";
11
11
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
12
12
  import { BN, isSameDid } from "@ocap/util";
13
13
  import { CustomError } from "@ocap/util/lib/error";
14
- import Debug from "debug";
15
14
  import { getListField } from "@ocap/util/lib/get-list-field";
15
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
16
+ import Debug from "debug";
16
17
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
17
18
  import { promisify } from "node:util";
18
19
  import isEqual from "lodash/isEqual.js";
20
+ import uniqBy from "lodash/uniqBy.js";
19
21
 
20
22
  //#region src/protocols/asset/acquire-v3.ts
21
23
  const debug = Debug("@ocap/tx-protocols:acquire-asset-v3");
@@ -163,21 +165,65 @@ runner.use(pipes.VerifyAccountMigration({
163
165
  stateKey: "senderState",
164
166
  addressKey: "tx.from"
165
167
  }));
166
- runner.use(pipes.VerifyBlocked({ stateKeys: ["signerStates", "ownerState"] }));
168
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
169
+ "senderState",
170
+ "signerStates",
171
+ "ownerState",
172
+ "itx.owner",
173
+ "factoryOwnerState",
174
+ "issuerState"
175
+ ] }));
176
+ /**
177
+ * Attribute the factory payment legs (factory / mint hook recipients) to the matched inputs.
178
+ * Legs are consumed in input order across ALL inputs so the attribution is deterministic; each matched
179
+ * input only gets the slices it funds, each pinned to a single payee.
180
+ */
181
+ function allocatePayLegs(ctx, matched) {
182
+ const { inputs = [], factoryState, config } = ctx;
183
+ const legs = getMintTokenPayLegs(factoryState, ctx.factoryTokens || [], config?.token?.address).map((l) => ({
184
+ ...l,
185
+ left: new BN(l.value)
186
+ }));
187
+ const result = [];
188
+ const matchedSet = new Set(matched);
189
+ const factoryTo = factoryState?.address ? [factoryState.address] : [];
190
+ for (const input of inputs) for (const t of getListField(input, "tokens") || []) {
191
+ let need = new BN(t.value || "0");
192
+ for (const leg of legs) {
193
+ if (need.lte(new BN(0))) break;
194
+ if (leg.address !== t.address || leg.left.lte(new BN(0))) continue;
195
+ const take = BN.min(need, leg.left);
196
+ leg.left = leg.left.sub(take);
197
+ need = need.sub(take);
198
+ if (matchedSet.has(input)) result.push({
199
+ address: t.address,
200
+ value: take.toString(10),
201
+ to: leg.to
202
+ });
203
+ }
204
+ if (need.gt(new BN(0)) && matchedSet.has(input)) result.push({
205
+ address: t.address,
206
+ value: need.toString(10),
207
+ to: factoryTo
208
+ });
209
+ }
210
+ return result;
211
+ }
167
212
  const getAcquireAssetV3Requirements = (ctx, index, signature) => {
168
- const { tx: tx$1, itx, inputs = [] } = ctx;
213
+ const { tx: tx$1, itx, inputs = [], senderState, signerStates = [] } = ctx;
169
214
  const signatures = getListField(tx$1, "signatures");
215
+ const isMultiSigCall = typeof index === "number" || Boolean(signature);
170
216
  const targetOwner = signature?.signer || (typeof index === "number" ? signatures?.[index]?.signer : tx$1?.from);
171
217
  if (!targetOwner) return [];
172
- const input = inputs.find((x) => isSameDid(x.owner, targetOwner));
173
- if (!input) return [];
174
- const tokensList = getListField(input, "tokens");
175
- const assetsList = getListField(input, "assets");
176
- return [...tokensList.map((t) => ({
218
+ if (isMultiSigCall && tx$1?.delegator && signature?.delegator && isSameDid(targetOwner, tx$1.from) && isSameDid(signature.delegator, tx$1.delegator)) return [];
219
+ const targetOwnerState = (isSameDid(targetOwner, tx$1?.from) ? senderState : void 0) || signerStates.find((s) => getRelatedAddresses(s).some((addr) => isSameDid(addr, targetOwner)));
220
+ const ownerRelated = targetOwnerState ? getRelatedAddresses(targetOwnerState) : [targetOwner];
221
+ const matchedInputs = inputs.filter((x) => ownerRelated.some((addr) => isSameDid(x.owner, addr)));
222
+ if (matchedInputs.length === 0) return isMultiSigCall ? [] : getDelegationRequirements(ctx);
223
+ const assetsList = matchedInputs.flatMap((inp) => getListField(inp, "assets") || []);
224
+ return [...allocatePayLegs(ctx, matchedInputs).map((x) => ({
177
225
  type: "token",
178
- address: t.address,
179
- value: t.value,
180
- to: itx?.factory ? [itx.factory] : []
226
+ ...x
181
227
  })), ...assetsList.map((a) => ({
182
228
  type: "asset",
183
229
  address: a,
@@ -204,6 +250,11 @@ runner.use(pipes.ExtractSigner({
204
250
  signerKey: "msSignerStates",
205
251
  delegatorKey: "delegatorStates"
206
252
  }));
253
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
254
+ "delegatorState",
255
+ "msSignerStates",
256
+ "delegatorStates"
257
+ ] }));
207
258
  runner.use(pipes.VerifyDelegation({
208
259
  type: "multisig",
209
260
  signerKey: "msSignerStates",
@@ -239,7 +290,7 @@ runner.use(async (context, next) => {
239
290
  const { owner } = input;
240
291
  const assetsList = getListField(input, "assets");
241
292
  const states = assetStates.filter((x) => assetsList.includes(x.address));
242
- const signer = signerStates.find((x) => x.address === owner);
293
+ const signer = signerStates.find((x) => getRelatedAddresses(x).includes(owner));
243
294
  try {
244
295
  await verifyAssetOwner({
245
296
  assets: states,
@@ -264,6 +315,7 @@ runner.use(async (context, next) => {
264
315
  const owner = ownerState ? ownerState.address : itx.owner;
265
316
  return next(await verifyAssetHierarchy([itx.address], owner, context, void 0, assets) || void 0);
266
317
  });
318
+ runner.use(verifyMintHook);
267
319
  runner.use(ensure_gas_default((context) => {
268
320
  const result = {
269
321
  create: 1,
@@ -279,13 +331,17 @@ runner.use(ensure_cost_default({ attachSenderChanges: true }));
279
331
  runner.use(pipes.TakeStateSnapshot());
280
332
  runner.use(async (context, next) => {
281
333
  const { tx: tx$1, itx, txTime, inputs = [], statedb, senderState, ownerState, factoryState, factoryTokens = [], mintedAsset, mintedAddress, signerStates = [], senderChange, updateVaults, assetStates = [], delegationState, delegationStates = [] } = context;
334
+ const sender = senderState ? senderState.address : tx$1.from;
282
335
  const signerUpdates = {};
283
336
  inputs.forEach((x) => {
284
337
  const { owner: owner$1 } = x;
285
- signerUpdates[owner$1] = applyTokenUpdates(getListField(x, "tokens"), signerStates.find((s) => s.address === owner$1), "sub");
286
- if (senderChange && owner$1 === senderChange.address) signerUpdates[owner$1] = applyTokenChange(signerUpdates[owner$1], senderChange);
338
+ const tokensList = getListField(x, "tokens");
339
+ const signerState = signerStates.find((s) => getRelatedAddresses(s).includes(owner$1));
340
+ const canonicalOwner = signerState ? signerState.address : owner$1;
341
+ signerUpdates[canonicalOwner] = applyTokenUpdates(tokensList, signerUpdates[canonicalOwner] || signerState, "sub");
287
342
  });
288
- const isAlsoSigner = !!signerUpdates[tx$1.from];
343
+ if (senderChange && signerUpdates[senderChange.address]) signerUpdates[senderChange.address] = applyTokenChange(signerUpdates[senderChange.address], senderChange);
344
+ const isAlsoSigner = !!signerUpdates[sender];
289
345
  const owner = ownerState ? ownerState.address : itx.owner;
290
346
  const factoryUpdates = { numMinted: factoryState.numMinted + 1 };
291
347
  if (factoryState.settlement !== "instant") {
@@ -295,17 +351,17 @@ runner.use(async (context, next) => {
295
351
  const existingSenderState = senderState ? await statedb.account.get(senderState.address, context) : null;
296
352
  const [newSenderState, newReceiverState, assetState, newSignerStates, newFactoryState, newAssetStates, newDelegationState, newDelegationStates] = await Promise.all([
297
353
  statedb.account.updateOrCreate(existingSenderState ?? null, account.updateOrCreate(existingSenderState ?? null, Object.assign({
298
- address: tx$1.from,
354
+ address: sender,
299
355
  nonce: tx$1.nonce,
300
356
  pk: tx$1.delegator ? senderState?.pk : tx$1.pk
301
- }, signerUpdates[tx$1.from] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
302
- ownerState || owner === tx$1.from ? Promise.resolve(ownerState) : statedb.account.create(owner, account.create({ address: owner }, context), context),
357
+ }, signerUpdates[sender] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
358
+ ownerState || owner === sender ? Promise.resolve(ownerState) : statedb.account.create(owner, account.create({ address: owner }, context), context),
303
359
  statedb.asset.create(itx.address, asset.create({
304
360
  ...mintedAsset,
305
361
  owner,
306
362
  address: mintedAddress
307
363
  }, context), context),
308
- Promise.all(signerStates.filter((x) => x.address !== tx$1.from).map(async (x) => {
364
+ Promise.all(uniqBy(signerStates, "address").filter((x) => x.address !== sender).map(async (x) => {
309
365
  const existing = await statedb.account.get(x.address, context);
310
366
  return statedb.account.updateOrCreate(existing ?? null, account.updateOrCreate(existing ?? null, {
311
367
  address: x.address,
@@ -315,7 +371,7 @@ runner.use(async (context, next) => {
315
371
  statedb.factory.update(factoryState.address, factory.update(factoryState, factoryUpdates, context), context),
316
372
  Promise.all(assetStates.map((x) => statedb.asset.update(x.address, asset.update(x, { consumedTime: txTime }, context), context))),
317
373
  context.isDelegationChanged && delegationState ? statedb.delegation.update(delegationState.address, delegation.update(delegationState, {}, context), context) : delegationState,
318
- context.isDelegationChanged && delegationStates.length ? Promise.all(delegationStates.map((x) => statedb.delegation.update(x.address, delegation.update(x, {}, context), context))) : delegationStates
374
+ context.isDelegationChanged && delegationStates.length ? Promise.all(uniqBy(delegationStates, "address").filter((x) => !delegationState || !isSameDid(x.address, delegationState.address)).map((x) => statedb.delegation.update(x.address, delegation.update(x, {}, context), context))) : delegationStates
319
375
  ]);
320
376
  if (updateVaults) await updateVaults();
321
377
  context.senderState = newSenderState;
@@ -1,7 +1,7 @@
1
1
  import { Runner, pipes } from "@ocap/tx-pipeline";
2
2
  import { BN } from "@ocap/util";
3
- import Debug from "debug";
4
3
  import cloneDeep from "lodash/cloneDeep.js";
4
+ import Debug from "debug";
5
5
 
6
6
  //#region src/protocols/asset/calls/transfer-token.ts
7
7
  const debug = Debug("@ocap/tx-protocols:acquire-asset:transfer-token");
@@ -11,6 +11,7 @@ runner.use(pipes.ExtractState({
11
11
  to: "receiverState",
12
12
  status: "INVALID_RECEIVER_STATE"
13
13
  }));
14
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverState"] }));
14
15
  runner.use((context, next) => {
15
16
  const { receiverState, args } = context;
16
17
  const receiver = receiverState;
@@ -10,6 +10,7 @@ runner.use(pipes.ExtractState({
10
10
  to: "receiverState",
11
11
  status: "INVALID_RECEIVER_STATE"
12
12
  }));
13
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverState"] }));
13
14
  runner.use((context, next) => {
14
15
  const { receiverState, args } = context;
15
16
  const receiver = receiverState;
@@ -1,6 +1,6 @@
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 } from "@ocap/state";
3
+ import { account, asset, token } from "@ocap/state";
4
4
  import { Runner, pipes } from "@ocap/tx-pipeline";
5
5
  import { CustomError } from "@ocap/util/lib/error";
6
6
  import Debug from "debug";
@@ -31,6 +31,7 @@ runner.use(pipes.ExtractState({
31
31
  runner.use((context, next) => {
32
32
  const { assetState } = context;
33
33
  if (!assetState) return next(new CustomError("INVALID_TX", "Asset state not found"));
34
+ if (token.isTokenCharterAsset(assetState)) return next(new CustomError("FORBIDDEN", "Token charter asset cannot be consumed"));
34
35
  const { issuer, consumedTime } = assetState;
35
36
  if (!issuer) return next(new CustomError("INVALID_TX", "Asset without issuer can not be consumed"));
36
37
  if (consumedTime) return next(new CustomError("INVALID_TX", `Asset already consumed on ${consumedTime}`));
@@ -59,12 +60,19 @@ runner.use(pipes.ExtractState({
59
60
  table: "account"
60
61
  }));
61
62
  runner.use((context, next) => {
62
- context.signerStates = [context.ownerState, context.issuerState];
63
- context.signers = [context.ownerState.address, context.issuerState.address];
63
+ const isSameOwnerIssuer = context.ownerState.address === context.issuerState.address;
64
+ context.signerStates = isSameOwnerIssuer ? [context.ownerState] : [context.ownerState, context.issuerState];
65
+ context.signers = isSameOwnerIssuer ? [context.ownerState.address] : [context.ownerState.address, context.issuerState.address];
64
66
  return next();
65
67
  });
66
68
  runner.use(pipes.VerifyMultiSigV2({ signersKey: "signers" }));
67
69
  runner.use(pipes.VerifyAccountMigration({ signerKey: "signerStates" }));
70
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
71
+ "senderState",
72
+ "signerStates",
73
+ "ownerState",
74
+ "issuerState"
75
+ ] }));
68
76
  runner.use(ensure_gas_default(() => ({
69
77
  create: 0,
70
78
  update: 2,
@@ -76,7 +84,7 @@ runner.use(async (context, next) => {
76
84
  const { tx: tx$1, itx, txTime, statedb, senderState, senderUpdates, assetState, updateVaults } = context;
77
85
  const [newSenderState, newAssetState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
78
86
  nonce: tx$1.nonce,
79
- pk: tx$1.pk,
87
+ pk: tx$1.delegator ? senderState.pk || tx$1.pk : tx$1.pk,
80
88
  ...senderUpdates
81
89
  }, context), context), statedb.asset.update(itx.address, asset.update(assetState, { consumedTime: txTime }, context), context)]);
82
90
  if (updateVaults) await updateVaults();
@@ -1,14 +1,14 @@
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";
4
5
  import { account, asset, delegation } from "@ocap/state";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
7
  import { CustomError } from "@ocap/util/lib/error";
7
- import { toAssetAddress } from "@arcblock/did-util";
8
- import Debug from "debug";
9
- import { formatMessage } from "@ocap/message";
10
8
  import { getListField } from "@ocap/util/lib/get-list-field";
11
9
  import cloneDeep from "lodash/cloneDeep.js";
10
+ import Debug from "debug";
11
+ import { formatMessage } from "@ocap/message";
12
12
  import { schemas, vValidate } from "@arcblock/validator";
13
13
 
14
14
  //#region src/protocols/asset/create.ts
@@ -51,7 +51,11 @@ runner.use(pipes.ExtractState({
51
51
  status: "INVALID_ISSUER_STATE",
52
52
  table: "account"
53
53
  }));
54
- runner.use(pipes.VerifyAccountMigration({ signerKey: "issuerState" }));
54
+ runner.use(pipes.VerifyAccountMigration({
55
+ stateKey: "issuerState",
56
+ addressKey: "itx.issuer",
57
+ signerKey: "issuerState"
58
+ }));
55
59
  runner.use(pipes.ExtractState({
56
60
  from: "tx.from",
57
61
  to: "senderState",
@@ -78,6 +82,11 @@ runner.use(pipes.VerifyDelegation({
78
82
  delegatorKey: "delegatorState",
79
83
  getRequirements: getDelegationRequirements
80
84
  }));
85
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
86
+ "senderState",
87
+ "delegatorState",
88
+ "issuerState"
89
+ ] }));
81
90
  runner.use(pipes.ExtractState({
82
91
  from: "itx.parent",
83
92
  to: "factoryState",
@@ -99,6 +108,10 @@ runner.use(pipes.ExtractState({
99
108
  status: "INVALID_ASSET",
100
109
  table: "asset"
101
110
  }));
111
+ runner.use((context, next) => {
112
+ if (context.parentAsset?.consumedTime) return next(new CustomError("INVALID_ASSET", "Parent asset is already consumed"));
113
+ return next();
114
+ });
102
115
  runner.use(ensure_gas_default(() => ({
103
116
  create: 1,
104
117
  update: 2,
@@ -112,7 +125,7 @@ runner.use(async (context, next) => {
112
125
  const [newSenderState, assetState, newDelegationState] = await Promise.all([
113
126
  statedb.account.update(senderState.address, account.update(senderState, {
114
127
  nonce: tx$1.nonce,
115
- pk: tx$1.pk,
128
+ pk: tx$1.delegator ? senderState.pk : tx$1.pk,
116
129
  ...senderUpdates
117
130
  }, context), context),
118
131
  statedb.asset.create(itx.address, asset.create({
@@ -6,7 +6,9 @@ import verify_itx_variables_default from "./pipes/verify-itx-variables.mjs";
6
6
  import verify_mint_limit_default from "./pipes/verify-mint-limit.mjs";
7
7
  import { account, asset, factory } from "@ocap/state";
8
8
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
9
+ import { isSameDid } from "@ocap/util";
9
10
  import { CustomError } from "@ocap/util/lib/error";
11
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
12
  import Debug from "debug";
11
13
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
12
14
 
@@ -84,7 +86,13 @@ runner.use(pipes.ExtractState({
84
86
  status: "OK",
85
87
  table: "account"
86
88
  }));
87
- runner.use(pipes.VerifyBlocked({ stateKeys: ["ownerState"] }));
89
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
90
+ "senderState",
91
+ "factoryOwnerState",
92
+ "issuerStates",
93
+ "ownerState",
94
+ "itx.owner"
95
+ ] }));
88
96
  runner.use(pipes.VerifyInfo([{
89
97
  error: "FORBIDDEN",
90
98
  message: "Only factory owner and trusted issuers are allowed to mint",
@@ -116,6 +124,20 @@ runner.use(pipes.VerifyUpdater({
116
124
  ownerKey: "ownerState"
117
125
  }));
118
126
  runner.use(verify_itx_assets_default);
127
+ runner.use((context, next) => {
128
+ const { itx, senderState, factoryOwnerState, assetStates = [], expectedFactoryStates = [], ownerAddress } = context;
129
+ const targetOwner = ownerAddress || itx.owner;
130
+ if (assetStates.length > 0 && senderState && !isSameDid(targetOwner, senderState.address)) {
131
+ const allowedIssuers = new Set([...getRelatedAddresses(senderState), ...factoryOwnerState ? getRelatedAddresses(factoryOwnerState) : []]);
132
+ for (const st of assetStates) {
133
+ if (allowedIssuers.has(st.owner)) continue;
134
+ const isIssuedByFactoryEcosystem = Boolean(st.issuer && allowedIssuers.has(st.issuer));
135
+ const isParentedByFactoryEcosystem = Boolean(st.parent && expectedFactoryStates.some((f) => f.address === st.parent && allowedIssuers.has(f.owner)));
136
+ if (!isIssuedByFactoryEcosystem && !isParentedByFactoryEcosystem) return next(new CustomError("FORBIDDEN", "Cannot consume third-party input asset not issued by this factory or its trusted issuers without owner signature", { persist: true }));
137
+ }
138
+ }
139
+ return next();
140
+ });
119
141
  runner.use(async (context, next) => {
120
142
  const { itx, ownerAddress, assetStates = [] } = context;
121
143
  const owner = ownerAddress || itx.owner;
@@ -19,6 +19,26 @@ type ExecMintHookContext = IDecodedContext & {
19
19
  states?: unknown;
20
20
  txn?: unknown;
21
21
  };
22
+ interface TokenPayLeg {
23
+ address: string;
24
+ value: string;
25
+ to: string[];
26
+ }
27
+ /**
28
+ * Break the tokens paid into a factory into payee legs, for delegation requirements.
29
+ *
30
+ * - non-instant settlement: all tokens are credited to the factory itself
31
+ * - instant settlement with a contract mint hook: each hook call credits its own `to` account
32
+ * (one leg per call, exact amount); whatever is not forwarded by the hook is attributed to the factory
33
+ *
34
+ * One leg per payee (instead of one requirement with a union payee set) keeps delegation `limit.to`
35
+ * pinning strict: a delegation pinned to payee X can not be used to also pay Y.
36
+ */
37
+ declare function getMintTokenPayLegs(factory: IAssetFactoryState | undefined, factoryTokens: Array<{
38
+ address: string;
39
+ value: string;
40
+ }>, officialTokenAddress?: string): TokenPayLeg[];
41
+ declare const verifyMintHook: PipeFunction<ExecMintHookContext>;
22
42
  declare const execMintHook: PipeFunction<ExecMintHookContext>;
23
43
  //#endregion
24
- export { execMintHook as default };
44
+ export { TokenPayLeg, execMintHook as default, getMintTokenPayLegs, verifyMintHook };