@ocap/tx-protocols 1.30.26 → 1.31.1

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 (122) hide show
  1. package/esm/execute.d.mts +11 -2
  2. package/esm/execute.mjs +724 -80
  3. package/esm/gas-security-guard.d.mts +375 -0
  4. package/esm/gas-security-guard.mjs +1103 -0
  5. package/esm/index.d.mts +36 -6
  6. package/esm/index.mjs +4 -2
  7. package/esm/pipes/ensure-cost.mjs +335 -59
  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 +115 -11
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  31. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  32. package/esm/protocols/governance/revoke-stake.mjs +25 -5
  33. package/esm/protocols/governance/slash-stake.mjs +72 -25
  34. package/esm/protocols/governance/stake.mjs +63 -13
  35. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  36. package/esm/protocols/rollup/close.mjs +1 -1
  37. package/esm/protocols/rollup/create-block.mjs +8 -7
  38. package/esm/protocols/rollup/create.mjs +17 -6
  39. package/esm/protocols/rollup/join.mjs +3 -3
  40. package/esm/protocols/rollup/leave.mjs +1 -1
  41. package/esm/protocols/rollup/migrate.mjs +7 -4
  42. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  43. package/esm/protocols/rollup/update.mjs +6 -1
  44. package/esm/protocols/token/create.mjs +23 -12
  45. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  46. package/esm/protocols/token/deposit-v2.mjs +81 -29
  47. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  48. package/esm/protocols/token-factory/burn.mjs +43 -10
  49. package/esm/protocols/token-factory/create.mjs +23 -14
  50. package/esm/protocols/token-factory/mint.mjs +54 -21
  51. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  52. package/esm/protocols/token-factory/update.mjs +16 -6
  53. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  54. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  55. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  56. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  57. package/esm/util.d.mts +3 -1
  58. package/esm/util.mjs +26 -17
  59. package/lib/execute.cjs +724 -76
  60. package/lib/execute.d.cts +11 -2
  61. package/lib/gas-security-guard.cjs +1142 -0
  62. package/lib/gas-security-guard.d.cts +375 -0
  63. package/lib/index.cjs +124 -1
  64. package/lib/index.d.cts +37 -7
  65. package/lib/pipes/ensure-cost.cjs +334 -58
  66. package/lib/protocols/account/delegate.cjs +64 -16
  67. package/lib/protocols/account/migrate.cjs +235 -35
  68. package/lib/protocols/account/migrate.d.cts +3 -0
  69. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  70. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  71. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  72. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  73. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  74. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  75. package/lib/protocols/asset/consume.cjs +11 -3
  76. package/lib/protocols/asset/create.cjs +19 -6
  77. package/lib/protocols/asset/mint.cjs +23 -1
  78. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  79. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  80. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  81. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  82. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  83. package/lib/protocols/asset/update.cjs +131 -12
  84. package/lib/protocols/asset/update.d.cts +13 -2
  85. package/lib/protocols/factory/create.cjs +14 -6
  86. package/lib/protocols/governance/claim-stake.cjs +115 -10
  87. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  88. package/lib/protocols/governance/return-stake.cjs +44 -11
  89. package/lib/protocols/governance/return-stake.d.cts +1 -1
  90. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  91. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  92. package/lib/protocols/governance/revoke-stake.cjs +25 -5
  93. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  94. package/lib/protocols/governance/slash-stake.cjs +72 -24
  95. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  96. package/lib/protocols/governance/stake.cjs +65 -14
  97. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  98. package/lib/protocols/rollup/close.cjs +1 -1
  99. package/lib/protocols/rollup/create-block.cjs +9 -8
  100. package/lib/protocols/rollup/create-block.d.cts +1 -1
  101. package/lib/protocols/rollup/create.cjs +18 -7
  102. package/lib/protocols/rollup/join.cjs +3 -3
  103. package/lib/protocols/rollup/leave.cjs +1 -1
  104. package/lib/protocols/rollup/migrate.cjs +7 -4
  105. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  106. package/lib/protocols/rollup/update.cjs +6 -1
  107. package/lib/protocols/token/create.cjs +24 -13
  108. package/lib/protocols/token/deposit-v2.cjs +80 -28
  109. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  110. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  111. package/lib/protocols/token-factory/burn.cjs +42 -9
  112. package/lib/protocols/token-factory/create.cjs +24 -15
  113. package/lib/protocols/token-factory/mint.cjs +53 -20
  114. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  115. package/lib/protocols/token-factory/update.cjs +16 -6
  116. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  117. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  118. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  119. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  120. package/lib/util.cjs +26 -17
  121. package/lib/util.d.cts +4 -2
  122. package/package.json +16 -16
@@ -92,11 +92,16 @@ runner.use(pipes.TakeStateSnapshot());
92
92
  runner.use(async (context, next) => {
93
93
  const { tx: tx$1, itx, rollupState, statedb, senderState, senderUpdates, updateVaults } = context;
94
94
  const data = decodeAnySafe(itx.data ?? null);
95
+ const sanitizedItx = { ...itx };
96
+ delete sanitizedItx.reserves;
97
+ delete sanitizedItx.targetType;
98
+ delete sanitizedItx.targetChainId;
99
+ delete sanitizedItx.enforceReserveWatermark;
95
100
  const [newSenderState, newRollupState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
96
101
  nonce: tx$1.nonce,
97
102
  ...senderUpdates
98
103
  }, context), context), statedb.rollup.update(itx.rollup, rollup.update(rollupState, {
99
- ...itx,
104
+ ...sanitizedItx,
100
105
  data
101
106
  }, context), context)]);
102
107
  if (updateVaults) await updateVaults();
@@ -1,13 +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 { toTokenAddress } from "@arcblock/did-util";
4
5
  import { account, delegation, token } from "@ocap/state";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
7
  import { BN, fromTokenToUnit } from "@ocap/util";
7
8
  import { CustomError } from "@ocap/util/lib/error";
8
- import { toTokenAddress } from "@arcblock/did-util";
9
- import Debug from "debug";
10
9
  import cloneDeep from "lodash/cloneDeep.js";
10
+ import Debug from "debug";
11
11
  import { schemas, v, vBN, vBNGreater, vBNMax, vDID, vForbidden, vStripUnknown, vValidate } from "@arcblock/validator";
12
12
  import uniq from "lodash/uniq.js";
13
13
  import isEmpty from "lodash/isEmpty.js";
@@ -27,11 +27,11 @@ const schema = v.pipe(v.object({
27
27
  symbol: v.pipe(v.string(), v.minLength(2), v.maxLength(6), v.toUpperCase()),
28
28
  unit: v.pipe(v.string(), v.minLength(1), v.maxLength(6), v.toLowerCase()),
29
29
  decimal: v.pipe(v.number(), v.minValue(2), v.maxValue(18)),
30
- icon: v.optional(v.nullable(v.literal(""))),
30
+ icon: v.optional(v.nullable(v.string())),
31
31
  totalSupply: vBN(vBNGreater(0), vBNMax(MAX_TOTAL_SUPPLY)),
32
32
  initialSupply: vBN(vBNGreater(0)),
33
33
  maxTotalSupply: v.optional(v.nullable(v.union([vBN(vBNGreater(0)), v.literal("")]))),
34
- foreignToken: v.optional(v.nullable(schemas.foreignToken)),
34
+ foreignToken: v.optional(v.nullable(token.multiChainForeignTokenSchema ?? schemas.foreignToken)),
35
35
  spendersList: v.optional(v.nullable(v.pipe(v.array(vDID({ prefix: true })), v.maxLength(30)))),
36
36
  tokenFactoryAddress: v.optional(vForbidden("tokenFactoryAddress is forbidden")),
37
37
  data: v.optional(v.nullable(v.any()))
@@ -45,6 +45,13 @@ runner.use(({ itx }, next) => {
45
45
  const spendersList = value.spendersList;
46
46
  itx.spenders = spendersList?.length ? uniq(spendersList) : null;
47
47
  delete itx.spendersList;
48
+ if (typeof itx.icon === "string" && itx.icon.trim()) {
49
+ const trimmedIcon = itx.icon.trim();
50
+ if (trimmedIcon.startsWith("<svg")) {
51
+ if (Buffer.byteLength(trimmedIcon, "utf8") > 16 * 1024) return next(new CustomError("INVALID_ICON", "Token Icon must be less than 16k"));
52
+ if (token.sanitizeTokenSvg(trimmedIcon) !== trimmedIcon) return next(new CustomError("INVALID_ICON", "Token Icon contains unsafe SVG elements or attributes"));
53
+ } else if (/^data:/i.test(trimmedIcon) && !token.iconToNftDisplay(trimmedIcon)) return next(new CustomError("INVALID_ICON", "Token Icon data URI must be a safe image format"));
54
+ }
48
55
  return next();
49
56
  });
50
57
  runner.use(pipes.VerifyInfo([{
@@ -78,6 +85,7 @@ runner.use(pipes.VerifyAccountMigration({
78
85
  stateKey: "delegatorState",
79
86
  addressKey: "tx.delegator"
80
87
  }));
88
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "delegatorState"] }));
81
89
  runner.use(pipes.VerifyDelegation({
82
90
  type: "signature",
83
91
  signerKey: "senderState",
@@ -123,20 +131,23 @@ runner.use(async (context, next) => {
123
131
  delegatorUpdates.tokens = delegatorState.tokens || {};
124
132
  delegatorUpdates.tokens[itx.address] = itx.initialSupply;
125
133
  } else updates.tokens[itx.address] = itx.initialSupply;
134
+ const initialTokenState = token.create({
135
+ ...cloneDeep(itx),
136
+ data,
137
+ issuer: owner,
138
+ type: "Token"
139
+ }, context);
140
+ const charterAsset = token.buildTokenCharterAssetState(initialTokenState, context, owner);
126
141
  const [newSenderState, tokenState, newDelegatorState, newDelegationState] = await Promise.all([
127
142
  statedb.account.update(senderState.address, account.update(senderState, {
128
143
  nonce: tx$1.nonce,
129
- pk: tx$1.pk,
144
+ pk: tx$1.delegator ? senderState.pk : tx$1.pk,
130
145
  ...senderUpdates
131
146
  }, context), context),
132
- statedb.token.create(itx.address, token.create({
133
- ...cloneDeep(itx),
134
- data,
135
- issuer: owner,
136
- type: "Token"
137
- }, context), context),
147
+ statedb.token.create(itx.address, initialTokenState, context),
138
148
  delegatorState ? statedb.account.update(delegatorState.address, account.update(delegatorState, delegatorUpdates, context), context) : null,
139
- context.isDelegationChanged ? statedb.delegation.update(delegationState.address, delegation.update(delegationState, {}, context), context) : delegationState
149
+ context.isDelegationChanged ? statedb.delegation.update(delegationState.address, delegation.update(delegationState, {}, context), context) : delegationState,
150
+ statedb.asset?.create ? Promise.resolve(statedb.asset.get?.(charterAsset.address, context)).then((existing) => existing && statedb.asset.update ? statedb.asset.update(charterAsset.address, charterAsset, context) : statedb.asset.create(charterAsset.address, charterAsset, context)) : null
140
151
  ]);
141
152
  if (updateVaults) await updateVaults();
142
153
  context.senderState = newSenderState;
@@ -1,5 +1,5 @@
1
1
  import { Runner } from "@ocap/tx-pipeline";
2
- import { IReadyContext, IStakeState, IWithEvidence, IWithRollup, IWithSender, IWithSigners, IWithStake, IWithToken, TDepositTokenV2Tx } from "@ocap/types";
2
+ import { IAccountState, IReadyContext, IStakeState, IWithEvidence, IWithRollup, IWithSender, IWithSigners, IWithStake, IWithToken, TDepositTokenV2Tx } from "@ocap/types";
3
3
 
4
4
  //#region src/protocols/token/deposit-v2.d.ts
5
5
  /** Token change for updates */
@@ -21,6 +21,10 @@ type Context = IReadyContext<TDepositTokenV2Tx> & Partial<IWithSender> & Partial
21
21
  lockerAddress?: string;
22
22
  /** Locker stake state */
23
23
  lockerState?: IStakeState;
24
+ /** Recipient account state when proposer-sponsored (itx.to !== tx.from) */
25
+ receiverState?: IAccountState | null;
26
+ /** Whether deposit is submitted by proposer on behalf of itx.to */
27
+ isProposerSponsor?: boolean;
24
28
  /** Signer addresses */
25
29
  signers?: string[];
26
30
  /** All updated stake states */
@@ -3,27 +3,21 @@ import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
4
  import verify_signers_default from "../rollup/pipes/verify-signers.mjs";
5
5
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
6
- import { account, evidence, stake } from "@ocap/state";
6
+ import { toStakeAddress } from "@arcblock/did-util";
7
+ import { account, evidence, rollup, stake } from "@ocap/state";
7
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
9
  import { BN, fromUnitToToken } from "@ocap/util";
9
10
  import { CustomError } from "@ocap/util/lib/error";
10
- import { toStakeAddress } from "@arcblock/did-util";
11
- import Debug from "debug";
12
11
  import { getListField } from "@ocap/util/lib/get-list-field";
12
+ import Debug from "debug";
13
13
  import { patterns, schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
14
 
15
15
  //#region src/protocols/token/deposit-v2.ts
16
16
  const debug = Debug("@ocap/tx-protocols:deposit-token");
17
17
  const schema = v.pipe(v.object({
18
18
  token: schemas.tokenInput,
19
- to: vDID({
20
- prefix: true,
21
- wallet: "ethereum"
22
- }),
23
- proposer: vDID({
24
- prefix: true,
25
- wallet: "ethereum"
26
- }),
19
+ to: vDID({ prefix: true }),
20
+ proposer: vDID({ prefix: true }),
27
21
  evidence: v.object({ hash: v.pipe(v.string(), v.regex(patterns.txHash)) }),
28
22
  rollup: vDID({
29
23
  prefix: true,
@@ -33,13 +27,9 @@ const schema = v.pipe(v.object({
33
27
  data: v.optional(v.nullable(v.any()))
34
28
  }), vStripUnknown());
35
29
  const runner = new Runner("deposit_token_v2");
36
- runner.use(({ tx: tx$1, itx }, next) => {
30
+ runner.use(({ itx }, next) => {
37
31
  const { error } = vValidate(schema, itx);
38
32
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
39
- if (itx.to !== tx$1.from) return next(new CustomError("INVALID_TX", "You can only deposit to tx sender account"));
40
- const signatures = getListField(tx$1, "signatures");
41
- if (signatures.some((x) => x.signer === itx.proposer) === false) return next(new CustomError("INVALID_TX", "itx.proposer must exist in signatures"));
42
- if (signatures.some((x) => x.signer === tx$1.from)) return next(new CustomError("INVALID_TX", "tx.from should not exist in signatures"));
43
33
  return next();
44
34
  });
45
35
  runner.use(pipes.ExtractState({
@@ -48,10 +38,31 @@ runner.use(pipes.ExtractState({
48
38
  status: "INVALID_ROLLUP",
49
39
  table: "rollup"
50
40
  }));
41
+ runner.use((context, next) => {
42
+ const { tx: tx$1, itx, rollupState } = context;
43
+ if (rollup.getRollupTargetType(rollupState) === "EVM") {
44
+ if (vValidate(vDID({
45
+ prefix: true,
46
+ wallet: "ethereum"
47
+ }), itx.to).error) return next(new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\""));
48
+ if (vValidate(vDID({
49
+ prefix: true,
50
+ wallet: "ethereum"
51
+ }), itx.proposer).error) return next(new CustomError("INVALID_TX", "Invalid itx: \"proposer\" Expected wallet type to be \"ethereum\""));
52
+ }
53
+ const isProposerSponsor = rollup.isProposerSponsoredDepositAllowed(rollupState) && tx$1.from === itx.proposer && itx.to !== tx$1.from;
54
+ context.isProposerSponsor = isProposerSponsor;
55
+ if (itx.to !== tx$1.from && !isProposerSponsor) return next(new CustomError("INVALID_TX", "You can only deposit to tx sender account"));
56
+ const signatures = getListField(tx$1, "signatures");
57
+ if (signatures.some((x) => x.signer === itx.proposer) === false) return next(new CustomError("INVALID_TX", "itx.proposer must exist in signatures"));
58
+ if (!isProposerSponsor && signatures.some((x) => x.signer === tx$1.from)) return next(new CustomError("INVALID_TX", "tx.from should not exist in signatures"));
59
+ if (isProposerSponsor && signatures.some((x) => x.signer === itx.to)) return next(new CustomError("INVALID_TX", "itx.to should not exist in signatures"));
60
+ return next();
61
+ });
51
62
  runner.use(verify_status_default({ paused: false }));
52
63
  runner.use((context, next) => {
53
64
  const { itx, rollupState } = context;
54
- if (rollupState.tokenAddress !== itx.token.address) return next(new CustomError("INVALID_TX", "Deposit token address does not match with rollup state"));
65
+ if (!rollup.isTokenSupportedByRollup(rollupState, itx.token.address)) return next(new CustomError("INVALID_TX", "Deposit token address does not match with rollup state"));
55
66
  if (rollupState.validators.some((x) => x.address === itx.proposer) === false) return next(new CustomError("INVALID_TX", "itx.proposer does not exist in validators"));
56
67
  return next();
57
68
  });
@@ -102,7 +113,7 @@ runner.use((context, next) => {
102
113
  const maxDepositAmount = new BN(rollupState.maxDepositAmount);
103
114
  if (depositAmount.lt(minDepositAmount)) return next(new CustomError("INVALID_TX", `Deposit amount must be greater than minDepositAmount: ${fromUnitToToken(minDepositAmount, tokenState.decimal)}`));
104
115
  if (depositAmount.gt(maxDepositAmount)) return next(new CustomError("INVALID_TX", `Deposit amount must be less than maxDepositAmount: ${fromUnitToToken(maxDepositAmount, tokenState.decimal)}`));
105
- const stakedAmount = new BN(stakeState.tokens[rollupState.tokenAddress] || 0);
116
+ const stakedAmount = new BN(stakeState.tokens[itx.token.address] || 0);
106
117
  if (depositAmount.gt(stakedAmount)) return next(new CustomError("INSUFFICIENT_STAKE", `Deposit amount must be less than available stake: ${fromUnitToToken(stakedAmount, tokenState.decimal)}`));
107
118
  return next();
108
119
  });
@@ -124,6 +135,13 @@ runner.use(pipes.ExtractState({
124
135
  status: "OK",
125
136
  table: "account"
126
137
  }));
138
+ runner.use(async (context, next) => {
139
+ if (context.isProposerSponsor) {
140
+ context.receiverState = await context.statedb.account.get(context.itx.to, context);
141
+ if (context.receiverState && (context.receiverState.address !== context.itx.to || account.isMigrated(context.receiverState))) return next(new CustomError("ACCOUNT_MIGRATED", `Recipient account is already migrated: ${context.itx.to}`));
142
+ }
143
+ return next();
144
+ });
127
145
  runner.use(pipes.ExtractState({
128
146
  from: "signers",
129
147
  to: "signerStates",
@@ -135,6 +153,11 @@ runner.use(pipes.VerifyAccountMigration({
135
153
  stateKey: "senderState",
136
154
  addressKey: "tx.from"
137
155
  }));
156
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
157
+ "senderState",
158
+ "receiverState",
159
+ "signerStates"
160
+ ] }));
138
161
  runner.use(ensure_gas_default((context) => {
139
162
  const result = {
140
163
  create: 1,
@@ -143,6 +166,8 @@ runner.use(ensure_gas_default((context) => {
143
166
  };
144
167
  if (context.senderState) result.update += 1;
145
168
  else result.create += 1;
169
+ if (context.isProposerSponsor) if (context.receiverState) result.update += 1;
170
+ else result.create += 1;
146
171
  if (context.lockerState) result.update += 1;
147
172
  else result.create += 1;
148
173
  return result;
@@ -150,7 +175,7 @@ runner.use(ensure_gas_default((context) => {
150
175
  runner.use(ensure_cost_default({ attachSenderChanges: true }));
151
176
  runner.use(pipes.TakeStateSnapshot());
152
177
  runner.use(async (context, next) => {
153
- const { tx: tx$1, itx, statedb, senderState, stakeState, stakeAddress, lockerState, lockerAddress, senderChange, updateVaults } = context;
178
+ const { tx: tx$1, itx, statedb, rollupState, senderState, receiverState, isProposerSponsor, stakeState, stakeAddress, lockerState, lockerAddress, senderChange, updateVaults } = context;
154
179
  const user = itx.token.value;
155
180
  const fee = itx.actualFee;
156
181
  const total = getBNSum(user, fee);
@@ -158,23 +183,43 @@ runner.use(async (context, next) => {
158
183
  address: itx.token.address,
159
184
  value: total
160
185
  }], stakeState, "sub");
161
- let senderUpdates = applyTokenUpdates([{
162
- address: itx.token.address,
163
- value: user
164
- }], senderState || {}, "add");
165
186
  const lockerUpdates = applyTokenUpdates([{
166
187
  address: itx.token.address,
167
188
  value: fee
168
189
  }], lockerState || { tokens: {} }, "add");
169
- if (senderChange && senderState) senderUpdates = applyTokenChange(senderUpdates, senderChange);
170
190
  const sender = senderState ? senderState.address : tx$1.from;
171
- const [newSenderState, newStakeState, newLockerState, evidenceState] = await Promise.all([
172
- statedb.account.updateOrCreate(senderState ?? null, account.updateOrCreate(senderState ?? null, {
191
+ let newSenderState;
192
+ let newReceiverState;
193
+ if (isProposerSponsor) {
194
+ let proposerUpdates = {};
195
+ if (senderChange && senderState) proposerUpdates = applyTokenChange(senderState, senderChange);
196
+ const recipientUpdates = applyTokenUpdates([{
197
+ address: itx.token.address,
198
+ value: user
199
+ }], receiverState || {}, "add");
200
+ [newSenderState, newReceiverState] = await Promise.all([statedb.account.updateOrCreate(senderState ?? null, account.updateOrCreate(senderState ?? null, {
201
+ address: sender,
202
+ nonce: tx$1.nonce,
203
+ pk: tx$1.pk,
204
+ ...proposerUpdates
205
+ }, context), context), statedb.account.updateOrCreate(receiverState ?? null, account.updateOrCreate(receiverState ?? null, {
206
+ address: itx.to,
207
+ ...recipientUpdates
208
+ }, context), context)]);
209
+ } else {
210
+ let senderUpdates = applyTokenUpdates([{
211
+ address: itx.token.address,
212
+ value: user
213
+ }], senderState || {}, "add");
214
+ if (senderChange && senderState) senderUpdates = applyTokenChange(senderUpdates, senderChange);
215
+ newSenderState = await statedb.account.updateOrCreate(senderState ?? null, account.updateOrCreate(senderState ?? null, {
173
216
  address: sender,
174
217
  nonce: tx$1.nonce,
175
218
  pk: tx$1.pk,
176
219
  ...senderUpdates
177
- }, context), context),
220
+ }, context), context);
221
+ }
222
+ const [newStakeState, newLockerState, evidenceState, newRollupState] = await Promise.all([
178
223
  statedb.stake.update(stakeAddress, stake.update(stakeState, stakeUpdates, context), context),
179
224
  lockerState ? statedb.stake.update(lockerState.address, stake.update(lockerState, lockerUpdates, context), context) : statedb.stake.create(lockerAddress, stake.create({
180
225
  address: lockerAddress,
@@ -188,13 +233,20 @@ runner.use(async (context, next) => {
188
233
  statedb.evidence.create(itx.evidence.hash, evidence.create({
189
234
  hash: itx.evidence.hash,
190
235
  data: "rollup-deposit"
191
- }, context), context)
236
+ }, context), context),
237
+ rollup.hasRollupReserveTracking(rollupState) ? statedb.rollup.update(itx.rollup, rollup.recordRollupDeposit(rollupState, itx.token.address, itx.token.value, context), context) : Promise.resolve(rollupState)
192
238
  ]);
193
239
  if (updateVaults) await updateVaults();
194
240
  context.senderState = newSenderState;
241
+ if (isProposerSponsor && newReceiverState) {
242
+ context.receiverState = newReceiverState;
243
+ context.signerStates = (context.signerStates || []).map((s) => s.address === newSenderState.address ? newSenderState : s);
244
+ }
245
+ context.rollupState = newRollupState;
195
246
  context.stakeState = newStakeState;
196
247
  context.evidenceState = evidenceState;
197
248
  context.stakeStates = [newStakeState, newLockerState];
249
+ const recipientAddress = isProposerSponsor ? itx.to : sender;
198
250
  context.updatedAccounts = context.updatedAccounts || [];
199
251
  context.updatedAccounts.push({
200
252
  address: stakeAddress,
@@ -202,7 +254,7 @@ runner.use(async (context, next) => {
202
254
  delta: `-${total}`,
203
255
  action: "unlock"
204
256
  }, {
205
- address: sender,
257
+ address: recipientAddress,
206
258
  token: itx.token.address,
207
259
  delta: user,
208
260
  action: "unlock"
@@ -2,13 +2,13 @@ import { applyTokenChange, applyTokenUpdates, getBNSum, getRewardLocker, getTxFe
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
4
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
5
- import { account, stake } from "@ocap/state";
5
+ import { toStakeAddress } from "@arcblock/did-util";
6
+ import { account, rollup, stake } from "@ocap/state";
6
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
7
8
  import { BN, fromUnitToToken } from "@ocap/util";
8
9
  import { CustomError } from "@ocap/util/lib/error";
9
- import { toStakeAddress } from "@arcblock/did-util";
10
- import Debug from "debug";
11
10
  import { getListField } from "@ocap/util/lib/get-list-field";
11
+ import Debug from "debug";
12
12
  import { schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
13
13
 
14
14
  //#region src/protocols/token/withdraw-v2.ts
@@ -16,27 +16,20 @@ const debug = Debug("@ocap/tx-protocols:withdraw-token");
16
16
  const verifyMultiSigV2 = pipes.VerifyMultiSigV2({ signersKey: "signers" });
17
17
  const schema = v.pipe(v.object({
18
18
  token: schemas.tokenInput,
19
- to: vDID({
20
- prefix: true,
21
- wallet: "ethereum"
22
- }),
19
+ to: vDID({ prefix: true }),
23
20
  rollup: vDID({
24
21
  prefix: true,
25
22
  role: "ROLE_ROLLUP"
26
23
  }),
27
- proposer: v.optional(v.nullable(v.union([v.literal(""), vDID({
28
- prefix: true,
29
- wallet: "ethereum"
30
- })])), ""),
24
+ proposer: v.optional(v.nullable(v.union([v.literal(""), vDID({ prefix: true })])), ""),
31
25
  actualFee: vBN(vBNMin(0)),
32
26
  maxFee: vBN(vBNMin(0)),
33
27
  data: v.optional(v.nullable(v.any()))
34
28
  }), vStripUnknown());
35
29
  const runner = new Runner("withdraw_token_v2");
36
- runner.use(({ tx: tx$1, itx }, next) => {
30
+ runner.use(({ itx }, next) => {
37
31
  const { error } = vValidate(schema, itx);
38
32
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
39
- if (itx.to !== tx$1.from) return next(new CustomError("INVALID_TX", "You can only withdraw to tx sender account"));
40
33
  return next();
41
34
  });
42
35
  runner.use(pipes.ExtractState({
@@ -45,10 +38,31 @@ runner.use(pipes.ExtractState({
45
38
  status: "INVALID_ROLLUP",
46
39
  table: "rollup"
47
40
  }));
41
+ runner.use((context, next) => {
42
+ const { tx: tx$1, itx, rollupState } = context;
43
+ if (rollup.getRollupTargetType(rollupState) === "EVM") {
44
+ if (vValidate(vDID({
45
+ prefix: true,
46
+ wallet: "ethereum"
47
+ }), itx.to).error) return next(new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\""));
48
+ if (itx.proposer && vValidate(vDID({
49
+ prefix: true,
50
+ wallet: "ethereum"
51
+ }), itx.proposer).error) return next(new CustomError("INVALID_TX", "Invalid itx: \"proposer\" Expected wallet type to be \"ethereum\""));
52
+ }
53
+ if (itx.to !== tx$1.from) return next(new CustomError("INVALID_TX", "You can only withdraw to tx sender account"));
54
+ return next();
55
+ });
48
56
  runner.use(verify_status_default({ paused: false }));
49
57
  runner.use((context, next) => {
50
58
  const { itx, rollupState } = context;
51
- if (rollupState.tokenAddress !== itx.token.address) return next(new CustomError("INVALID_TX", "Withdraw token address does not match with rollup"));
59
+ if (!rollup.isTokenSupportedByRollup(rollupState, itx.token.address)) return next(new CustomError("INVALID_TX", "Withdraw token address does not match with rollup"));
60
+ if (rollup.hasRollupReserveTracking(rollupState)) {
61
+ const reserve = rollup.getRollupTokenReserve(rollupState, itx.token.address);
62
+ const nextWithdrawn = new BN(reserve.totalWithdrawn).add(new BN(itx.token.value));
63
+ const totalDeposited = new BN(reserve.totalDeposited);
64
+ if (nextWithdrawn.gt(totalDeposited)) return next(new CustomError("INVALID_TX", `Withdraw amount (${itx.token.value}) exceeds rollup net inflow reserve watermark: cumulativeWithdrawn (${nextWithdrawn.toString(10)}) > cumulativeDeposited (${totalDeposited.toString(10)})`));
65
+ }
52
66
  return next();
53
67
  });
54
68
  runner.use(pipes.ExtractState({
@@ -122,6 +136,7 @@ runner.use(pipes.VerifyAccountMigration({
122
136
  stateKey: "senderState",
123
137
  addressKey: "tx.from"
124
138
  }));
139
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "signerStates"] }));
125
140
  runner.use((context, next) => {
126
141
  const { itx, senderState } = context;
127
142
  context.stakeAddress = toStakeAddress(senderState.address, itx.rollup);
@@ -176,7 +191,7 @@ runner.use(async (context, next) => {
176
191
  address: itx.token.address,
177
192
  value: fee
178
193
  }], lockerState || { tokens: {} }, "add");
179
- const [newSenderState, newStakeState, newLockerState] = await Promise.all([
194
+ const [newSenderState, newStakeState, newLockerState, newRollupState] = await Promise.all([
180
195
  statedb.account.update(senderState.address, account.update(senderState, {
181
196
  nonce: tx$1.nonce,
182
197
  ...senderUpdates
@@ -198,10 +213,12 @@ runner.use(async (context, next) => {
198
213
  message: "pending-block-reward",
199
214
  revokeWaitingPeriod: 0,
200
215
  ...lockerUpdates
201
- }, context), context)
216
+ }, context), context),
217
+ rollup.hasRollupReserveTracking(context.rollupState) ? statedb.rollup.update(itx.rollup, rollup.recordRollupWithdraw(context.rollupState, itx.token.address, itx.token.value, context), context) : Promise.resolve(context.rollupState)
202
218
  ]);
203
219
  if (updateVaults) await updateVaults();
204
220
  context.senderState = newSenderState;
221
+ context.rollupState = newRollupState;
205
222
  context.stakeState = newStakeState;
206
223
  context.lockerState = newLockerState;
207
224
  context.stakeStates = [newStakeState, newLockerState];
@@ -4,11 +4,13 @@ import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
4
  import calc_reserve_default from "./pipes/calc-reserve.mjs";
5
5
  import { account, token, tokenFactory } from "@ocap/state";
6
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
7
- import { BN, fromUnitToToken } from "@ocap/util";
7
+ import { BN, fromUnitToToken, isSameDid, toAddress } from "@ocap/util";
8
8
  import { CustomError } from "@ocap/util/lib/error";
9
- import pick from "lodash/pick.js";
10
9
  import { getListField } from "@ocap/util/lib/get-list-field";
10
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
11
+ import pick from "lodash/pick.js";
11
12
  import { schemas, v, vBN, vBNGreater, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
13
+ import { calcFee } from "@ocap/util/lib/curve";
12
14
 
13
15
  //#region src/protocols/token-factory/burn.ts
14
16
  const runner = new Runner("burn_token");
@@ -33,6 +35,11 @@ runner.use(pipes.ExtractState({
33
35
  status: "INVALID_TOKEN_FACTORY",
34
36
  table: "tokenFactory"
35
37
  }));
38
+ runner.use((context, next) => {
39
+ const { tokenFactoryState } = context;
40
+ if (tokenFactoryState?.status && tokenFactoryState.status !== "ACTIVE") return next(new CustomError("INVALID_TOKEN_FACTORY", `Token factory is ${tokenFactoryState.status} and cannot burn tokens`));
41
+ return next();
42
+ });
36
43
  runner.use(pipes.ExtractState({
37
44
  from: "tokenFactoryState.tokenAddress",
38
45
  to: "tokenState",
@@ -93,7 +100,11 @@ runner.use(pipes.VerifyAccountMigration({
93
100
  stateKey: "receiverState",
94
101
  addressKey: "itx.receiver"
95
102
  }));
96
- runner.use(pipes.VerifyBlocked({ stateKeys: ["signerStates", "receiverState"] }));
103
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
104
+ "senderState",
105
+ "signerStates",
106
+ "receiverState"
107
+ ] }));
97
108
  runner.use(pipes.ExtractState({
98
109
  from: "tokenFactoryState.owner",
99
110
  to: "ownerState",
@@ -106,6 +117,15 @@ runner.use(pipes.verifyTokenAccess({
106
117
  accountKeys: ["senderState"],
107
118
  errorMessage: "Account {address} is not allowed to burn token {tokenAddress}"
108
119
  }));
120
+ runner.use((context, next) => {
121
+ const { tokenFactoryState, tokenState, senderState, ownerState, tx: tx$1 } = context;
122
+ if (!tokenFactoryState?.curve && (!tokenState?.minters || tokenState.minters.length === 0)) {
123
+ const senderAddrs = senderState ? getRelatedAddresses(senderState) : [tx$1.from];
124
+ const ownerAddrs = ownerState ? getRelatedAddresses(ownerState) : [tokenFactoryState.owner];
125
+ if (!senderAddrs.some((s) => ownerAddrs.some((o) => isSameDid(s, o)))) return next(new CustomError("FORBIDDEN", `verify-token-access: Account ${senderState?.address || tx$1.from} is not allowed to burn token ${tokenState.address}`, { persist: true }));
126
+ }
127
+ return next();
128
+ });
109
129
  runner.use((context, next) => {
110
130
  const { inputs = [], tokenFactoryState } = context;
111
131
  let amount = new BN("0");
@@ -125,6 +145,18 @@ runner.use(calc_reserve_default({
125
145
  amountKey: "burnAmount",
126
146
  direction: "burn"
127
147
  }), { shouldSkip: (ctx) => !ctx.tokenFactoryState?.curve });
148
+ runner.use((context, next) => {
149
+ const { tokenFactoryState, burnAmount = "0", reserveAmount = "0" } = context;
150
+ const reserveBalance = new BN(tokenFactoryState.reserveBalance || "0");
151
+ if (new BN(burnAmount).eq(new BN(tokenFactoryState.currentSupply)) && new BN(reserveAmount).gt(reserveBalance)) {
152
+ context.reserveAmount = reserveBalance.toString(10);
153
+ context.reserveFee = calcFee({
154
+ reserveAmount: context.reserveAmount,
155
+ feeRate: String(tokenFactoryState.feeRate)
156
+ })?.toString();
157
+ }
158
+ return next();
159
+ }, { shouldSkip: (ctx) => !ctx.tokenFactoryState?.curve });
128
160
  runner.use((context, next) => {
129
161
  const { reserveAmount = "0", reserveFee } = context;
130
162
  const { minReserve } = context.itx;
@@ -192,6 +224,7 @@ runner.use(async (context, next) => {
192
224
  delta: new BN(reserveAmount).sub(new BN(reserveFee || "0")).toString()
193
225
  });
194
226
  if (senderChange) accountUpdates[senderChange.address] = applyTokenChange(accountUpdates[senderChange.address] || senderState, senderChange);
227
+ const isSameAddr = (a, b) => Boolean(a && b && (a === b || toAddress(a) === toAddress(b)));
195
228
  const [newAccountStates, newTokenFactoryState, newTokenState] = await Promise.all([
196
229
  Promise.all(Object.entries(accountUpdates).map(([address, updates]) => {
197
230
  const state = [
@@ -199,13 +232,13 @@ runner.use(async (context, next) => {
199
232
  receiverState,
200
233
  ownerState,
201
234
  ...signerStates
202
- ].find((x) => x?.address === address);
235
+ ].find((x) => isSameAddr(x?.address, address));
203
236
  const actualUpdates = state ? pick(updates, ["tokens"]) : {
204
237
  ...updates,
205
238
  address
206
239
  };
207
- if (address === tx$1.from) {
208
- actualUpdates.pk = tx$1.pk;
240
+ if (isSameAddr(address, tx$1.from)) {
241
+ actualUpdates.pk = tx$1.delegator ? state?.pk || tx$1.pk : tx$1.pk;
209
242
  actualUpdates.nonce = tx$1.nonce;
210
243
  }
211
244
  return statedb.account.updateOrCreate(state ?? null, account.updateOrCreate(state ?? null, actualUpdates, context), context);
@@ -216,10 +249,10 @@ runner.use(async (context, next) => {
216
249
  }, context), context),
217
250
  statedb.token.update(tokenAddress, token.update(tokenState, { totalSupply: new BN(tokenState.totalSupply).sub(new BN(burnAmount)).toString() }), context)
218
251
  ]);
219
- context.senderState = newAccountStates.find((x) => x.address === tx$1.from);
220
- context.receiverState = newAccountStates.find((x) => x.address === receiver);
221
- context.ownerState = newAccountStates.find((x) => x.address === ownerState.address) || ownerState;
222
- context.signerStates = newAccountStates.filter((x) => signerStates.find((s) => s.address === x.address));
252
+ context.senderState = newAccountStates.find((x) => isSameAddr(x.address, tx$1.from));
253
+ context.receiverState = newAccountStates.find((x) => isSameAddr(x.address, receiver));
254
+ context.ownerState = newAccountStates.find((x) => isSameAddr(x.address, ownerState.address)) || ownerState;
255
+ context.signerStates = newAccountStates.filter((x) => signerStates.find((s) => isSameAddr(s.address, x.address)));
223
256
  context.tokenFactoryState = newTokenFactoryState;
224
257
  context.tokenState = newTokenState;
225
258
  context.inputChanges = inputChanges;
@@ -1,18 +1,18 @@
1
1
  import { applyTokenChange, decodeAnySafe, getDelegationRequirements, isHttpUrl, isHttpsUrl } 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 { any, array, check, literal, maxLength, maxValue, minLength, minValue, nullable, number, object, optional, picklist, pipe, safeParse, string, toLowerCase, toUpperCase, union } from "../../node_modules/valibot/dist/index.mjs";
5
- import verify_icon_default from "./pipes/verify-icon.mjs";
6
4
  import verify_ownership_default from "./pipes/verify-ownership.mjs";
7
5
  import verify_url_default from "./pipes/verify-url.mjs";
6
+ import { any, array, check, literal, maxLength, maxValue, minLength, minValue, nullable, number, object, optional, picklist, pipe, safeParse, string, toLowerCase, toUpperCase, union } from "../../node_modules/valibot/dist/index.mjs";
7
+ import verify_icon_default from "./pipes/verify-icon.mjs";
8
+ import { toStakeAddress, toTokenAddress, toTokenFactoryAddress } from "@arcblock/did-util";
8
9
  import { account, delegation, stake, token, tokenFactory } from "@ocap/state";
9
10
  import { Runner, pipes } from "@ocap/tx-pipeline";
10
11
  import { BN, fromTokenToUnit, fromUnitToToken } from "@ocap/util";
11
12
  import { CustomError } from "@ocap/util/lib/error";
12
- import { toStakeAddress, toTokenAddress, toTokenFactoryAddress } from "@arcblock/did-util";
13
- import Debug from "debug";
14
13
  import { getListField } from "@ocap/util/lib/get-list-field";
15
14
  import cloneDeep from "lodash/cloneDeep.js";
15
+ import Debug from "debug";
16
16
  import { vBN, vBNGreater, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
17
17
  import uniq from "lodash/uniq.js";
18
18
  import isEmpty from "lodash/isEmpty.js";
@@ -38,7 +38,7 @@ const schema = pipe(object({
38
38
  description: pipe(string(), minLength(16), maxLength(128)),
39
39
  symbol: pipe(string(), minLength(2), maxLength(6), toUpperCase()),
40
40
  unit: pipe(string(), minLength(1), maxLength(6), toLowerCase()),
41
- decimal: pipe(number(), minValue(2), maxValue(18)),
41
+ decimal: union([literal(0), pipe(number(), minValue(2), maxValue(18))]),
42
42
  icon: optional(nullable(string())),
43
43
  maxTotalSupply: optional(nullable(union([vBN(vBNGreater(0)), literal("")]))),
44
44
  website: optional(nullable(union([literal(""), pipe(string(), maxLength(256), check(isValidUrl, "Must be a valid URL"))]))),
@@ -53,6 +53,7 @@ runner.use((context, next) => {
53
53
  const { error, value } = vValidate(schema, context.itx);
54
54
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
55
55
  if (context.itx.token?.type === "CreditToken") {
56
+ if (context.itx.token?.decimal === 0) return next(new CustomError("INVALID_TX", "Invalid itx: CreditToken decimal must be between 2 and 18"));
56
57
  if (context.itx.curve != null) return next(new CustomError("INVALID_TX", "Invalid itx: Should not provide curve for CreditToken"));
57
58
  context.itx.curve = value.curve;
58
59
  } else {
@@ -178,6 +179,9 @@ runner.use(pipes.ExtractState({
178
179
  runner.use((context, next) => {
179
180
  const { stakeState, config, itx } = context;
180
181
  if (stakeState.revocable === false) return next(new CustomError("INVALID_STAKE_STATE", `Staking for token creating already locked: ${stakeState.address}`));
182
+ if (Array.isArray(stakeState.slashers) && stakeState.slashers.length > 0) return next(new CustomError("INVALID_STAKE_STATE", "Staking for token creation cannot have slashers"));
183
+ if (stakeState.revokedTokens && Object.values(stakeState.revokedTokens).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)))) return next(new CustomError("INVALID_STAKE_STATE", "Staking for token creation cannot have pending revoked tokens"));
184
+ if (Array.isArray(stakeState.assets) && stakeState.assets.length > 0 || Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0) return next(new CustomError("INVALID_STAKE_STATE", "Staking for token creation cannot contain assets"));
181
185
  const actualStake = new BN(stakeState.tokens[config.token.address] || 0);
182
186
  const requiredStake = fromTokenToUnit(itx.token.type === "CreditToken" ? config.transaction.txStake.createCreditToken : config.transaction.txStake.createToken, config.token.decimal);
183
187
  if (actualStake.lt(requiredStake)) return next(new CustomError("INVALID_STAKE_STATE", `Insufficient stake amount: required ${fromUnitToToken(requiredStake, config.token.decimal)} ${config.token.symbol}`));
@@ -193,6 +197,7 @@ runner.use(pipes.VerifyAccountMigration({
193
197
  stateKey: "delegatorState",
194
198
  addressKey: "tx.delegator"
195
199
  }));
200
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["delegatorState"] }));
196
201
  runner.use(pipes.VerifyDelegation({
197
202
  type: "signature",
198
203
  signerKey: "senderState",
@@ -222,19 +227,21 @@ runner.use(async (context, next) => {
222
227
  const itxToken = itx.token;
223
228
  const { tokens: senderTokens = {} } = senderState;
224
229
  const senderUpdates = senderChange ? applyTokenChange({ tokens: senderTokens }, senderChange) : { tokens: senderTokens };
230
+ const initialTokenState = token.create({
231
+ ...cloneDeep(itxToken),
232
+ totalSupply: "0",
233
+ initialSupply: "0",
234
+ issuer: owner,
235
+ tokenFactoryAddress: itx.address
236
+ }, context);
237
+ const charterAsset = token.buildTokenCharterAssetState(initialTokenState, context, owner);
225
238
  const [newSenderState, newTokenState, newTokenFactoryState, newDelegationState, newStakeState] = await Promise.all([
226
239
  statedb.account.update(senderState.address, account.update(senderState, {
227
240
  nonce: tx$1.nonce,
228
- pk: tx$1.pk,
241
+ pk: tx$1.delegator ? senderState.pk : tx$1.pk,
229
242
  ...senderUpdates
230
243
  }, context), context),
231
- statedb.token.create(itxToken.address, token.create({
232
- ...cloneDeep(itxToken),
233
- totalSupply: "0",
234
- initialSupply: "0",
235
- issuer: owner,
236
- tokenFactoryAddress: itx.address
237
- }, context), context),
244
+ statedb.token.create(itxToken.address, initialTokenState, context),
238
245
  statedb.tokenFactory.create(itx.address, tokenFactory.create({
239
246
  ...cloneDeep(itx),
240
247
  owner,
@@ -244,8 +251,10 @@ runner.use(async (context, next) => {
244
251
  context.isDelegationChanged ? statedb.delegation.update(delegationState.address, delegation.update(delegationState, {}, context), context) : delegationState,
245
252
  statedb.stake.update(stakeAddress, stake.update(stakeState, {
246
253
  revocable: false,
254
+ slashers: [],
247
255
  revokeWaitingPeriod: config.transaction.txStake.createTokenLockPeriod
248
- }, context), context)
256
+ }, context), context),
257
+ statedb.asset?.create ? Promise.resolve(statedb.asset.get?.(charterAsset.address, context)).then((existing) => existing && statedb.asset.update ? statedb.asset.update(charterAsset.address, charterAsset, context) : statedb.asset.create(charterAsset.address, charterAsset, context)) : null
249
258
  ]);
250
259
  if (updateVaults) await updateVaults();
251
260
  context.senderState = newSenderState;