@ocap/state 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.
- package/esm/index.d.mts +4 -4
- package/esm/index.mjs +4 -4
- package/esm/states/account.d.mts +2 -8
- package/esm/states/account.mjs +2 -64
- package/esm/states/asset.mjs +5 -1
- package/esm/states/chain.mjs +1 -3
- package/esm/states/delegation.mjs +2 -0
- package/esm/states/rollup-block.mjs +1 -4
- package/esm/states/rollup.d.mts +37 -10
- package/esm/states/rollup.mjs +193 -19
- package/esm/states/stake.mjs +2 -1
- package/esm/states/token-factory.mjs +28 -9
- package/esm/states/token.d.mts +111 -7
- package/esm/states/token.mjs +365 -6
- package/esm/states/tx.mjs +1 -1
- package/lib/index.cjs +28 -8
- package/lib/index.d.cts +4 -4
- package/lib/states/account.cjs +1 -70
- package/lib/states/account.d.cts +2 -8
- package/lib/states/asset.cjs +5 -1
- package/lib/states/chain.cjs +2 -4
- package/lib/states/delegation.cjs +2 -0
- package/lib/states/rollup-block.cjs +1 -4
- package/lib/states/rollup.cjs +205 -17
- package/lib/states/rollup.d.cts +37 -10
- package/lib/states/stake.cjs +2 -1
- package/lib/states/token-factory.cjs +28 -9
- package/lib/states/token.cjs +380 -6
- package/lib/states/token.d.cts +111 -7
- package/lib/states/tx.cjs +2 -2
- package/package.json +9 -9
package/lib/states/stake.cjs
CHANGED
|
@@ -81,12 +81,13 @@ const update = (state, attrs, context) => {
|
|
|
81
81
|
...(0, lodash_pick.default)(attrs, [
|
|
82
82
|
"tokens",
|
|
83
83
|
"assets",
|
|
84
|
+
"slashers",
|
|
84
85
|
"revocable",
|
|
85
|
-
"data",
|
|
86
86
|
"revokeWaitingPeriod",
|
|
87
87
|
"revokedTokens",
|
|
88
88
|
"revokedAssets"
|
|
89
89
|
]),
|
|
90
|
+
...attrs.data !== void 0 ? { data: attrs.data } : {},
|
|
90
91
|
message: state.message || "empty",
|
|
91
92
|
context: require_contexts_state.update(state.context, context)
|
|
92
93
|
});
|
|
@@ -32,13 +32,24 @@ const stateSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
|
32
32
|
prefix: true,
|
|
33
33
|
role: "ROLE_TOKEN_FACTORY"
|
|
34
34
|
}),
|
|
35
|
-
owner: _arcblock_validator.v.union([
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
35
|
+
owner: _arcblock_validator.v.union([
|
|
36
|
+
(0, _arcblock_validator.vDID)({
|
|
37
|
+
prefix: true,
|
|
38
|
+
role: "ROLE_ACCOUNT"
|
|
39
|
+
}),
|
|
40
|
+
(0, _arcblock_validator.vDID)({
|
|
41
|
+
prefix: true,
|
|
42
|
+
role: "ROLE_APPLICATION"
|
|
43
|
+
}),
|
|
44
|
+
(0, _arcblock_validator.vDID)({
|
|
45
|
+
prefix: true,
|
|
46
|
+
role: "ROLE_BLOCKLET"
|
|
47
|
+
}),
|
|
48
|
+
(0, _arcblock_validator.vDID)({
|
|
49
|
+
prefix: true,
|
|
50
|
+
role: "ROLE_ASSET"
|
|
51
|
+
})
|
|
52
|
+
]),
|
|
42
53
|
tokenAddress: (0, _arcblock_validator.vDID)({
|
|
43
54
|
prefix: true,
|
|
44
55
|
role: "ROLE_TOKEN"
|
|
@@ -49,7 +60,11 @@ const stateSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
|
49
60
|
}),
|
|
50
61
|
currentSupply: (0, _arcblock_validator.vBN)((0, _arcblock_validator.vBNMin)(0)),
|
|
51
62
|
reserveBalance: (0, _arcblock_validator.vBN)((0, _arcblock_validator.vBNMin)(0)),
|
|
52
|
-
status: _arcblock_validator.v.picklist([
|
|
63
|
+
status: _arcblock_validator.v.picklist([
|
|
64
|
+
"ACTIVE",
|
|
65
|
+
"PAUSED",
|
|
66
|
+
"GRADUATED"
|
|
67
|
+
]),
|
|
53
68
|
feeRate: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.minValue(0), _arcblock_validator.v.maxValue(2e3)),
|
|
54
69
|
curve: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vCurveSchema)),
|
|
55
70
|
context: _arcblock_validator.schemas.context,
|
|
@@ -68,6 +83,7 @@ const create = (attrs, context) => {
|
|
|
68
83
|
"reserveAddress",
|
|
69
84
|
"curve",
|
|
70
85
|
"feeRate",
|
|
86
|
+
"status",
|
|
71
87
|
"data"
|
|
72
88
|
])
|
|
73
89
|
};
|
|
@@ -77,9 +93,12 @@ const create = (attrs, context) => {
|
|
|
77
93
|
const update = (state, attrs, context) => validate({
|
|
78
94
|
...state,
|
|
79
95
|
...(0, lodash_pick.default)(attrs, [
|
|
96
|
+
"owner",
|
|
80
97
|
"currentSupply",
|
|
81
98
|
"reserveBalance",
|
|
82
|
-
"feeRate"
|
|
99
|
+
"feeRate",
|
|
100
|
+
"status",
|
|
101
|
+
"data"
|
|
83
102
|
]),
|
|
84
103
|
context: require_contexts_state.update(state.context, context)
|
|
85
104
|
});
|
package/lib/states/token.cjs
CHANGED
|
@@ -1,21 +1,41 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_contexts_state = require('../contexts/state.cjs');
|
|
3
|
+
const require_states_asset = require('./asset.cjs');
|
|
4
|
+
const require_states_token_factory = require('./token-factory.cjs');
|
|
5
|
+
let _arcblock_did = require("@arcblock/did");
|
|
3
6
|
let _arcblock_did_lib_type = require("@arcblock/did/lib/type");
|
|
4
7
|
let _ocap_util = require("@ocap/util");
|
|
5
8
|
let lodash_pick = require("lodash/pick");
|
|
6
9
|
lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
|
|
7
10
|
let _arcblock_validator = require("@arcblock/validator");
|
|
11
|
+
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
8
12
|
let lodash_cloneDeep = require("lodash/cloneDeep");
|
|
9
13
|
lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
|
|
10
14
|
|
|
11
15
|
//#region src/states/token.ts
|
|
12
16
|
var token_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
17
|
+
TOKEN_CHARTER_KIND: () => TOKEN_CHARTER_KIND,
|
|
18
|
+
buildTokenCharterAssetData: () => buildTokenCharterAssetData,
|
|
19
|
+
buildTokenCharterAssetState: () => buildTokenCharterAssetState,
|
|
13
20
|
create: () => create,
|
|
21
|
+
extractTokenUpdatesFromCharterAsset: () => extractTokenUpdatesFromCharterAsset,
|
|
22
|
+
iconToNftDisplay: () => iconToNftDisplay,
|
|
23
|
+
isTokenCharterAsset: () => isTokenCharterAsset,
|
|
14
24
|
metadataSchema: () => metadataSchema,
|
|
25
|
+
migrateTokensToCharterAssets: () => migrateTokensToCharterAssets,
|
|
26
|
+
multiChainForeignTokenSchema: () => multiChainForeignTokenSchema,
|
|
27
|
+
normalizeLegacyTokenStateForUpdate: () => normalizeLegacyTokenStateForUpdate,
|
|
28
|
+
resolveCharterMoniker: () => resolveCharterMoniker,
|
|
29
|
+
sanitizeTokenSvg: () => sanitizeTokenSvg,
|
|
15
30
|
stateSchema: () => stateSchema,
|
|
31
|
+
syncCharterAssetWithToken: () => syncCharterAssetWithToken,
|
|
32
|
+
syncTokenCharterOwnership: () => syncTokenCharterOwnership,
|
|
33
|
+
toTokenCharterAssetAddress: () => toTokenCharterAssetAddress,
|
|
16
34
|
update: () => update,
|
|
17
|
-
validate: () => validate
|
|
35
|
+
validate: () => validate,
|
|
36
|
+
websiteToNftEndpoint: () => websiteToNftEndpoint
|
|
18
37
|
});
|
|
38
|
+
const TOKEN_CHARTER_KIND = "TokenCharter";
|
|
19
39
|
const isTest = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || process.env.CI;
|
|
20
40
|
const isValidWebsiteUrl = (s) => {
|
|
21
41
|
try {
|
|
@@ -36,6 +56,22 @@ const metadataSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
|
36
56
|
communityUrl: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.union([_arcblock_validator.v.literal(""), _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.maxLength(256), _arcblock_validator.v.check(isHttpsUrl, "Must be HTTPS URL"))]))),
|
|
37
57
|
issuer: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.maxLength(64))
|
|
38
58
|
}), (0, _arcblock_validator.vStripUnknown)());
|
|
59
|
+
const ethDidSchema = (0, _arcblock_validator.vDID)({
|
|
60
|
+
prefix: true,
|
|
61
|
+
wallet: "ethereum"
|
|
62
|
+
});
|
|
63
|
+
const anyDidSchema = (0, _arcblock_validator.vDID)({ prefix: true });
|
|
64
|
+
const multiChainForeignTokenSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
65
|
+
type: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(1), _arcblock_validator.v.maxLength(32)),
|
|
66
|
+
contractAddress: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(1)),
|
|
67
|
+
chainType: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(1), _arcblock_validator.v.maxLength(32)),
|
|
68
|
+
chainName: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(1), _arcblock_validator.v.maxLength(32)),
|
|
69
|
+
chainId: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.check((n) => n > 0, "Must be positive"))
|
|
70
|
+
}), _arcblock_validator.v.forward(_arcblock_validator.v.check((ft) => {
|
|
71
|
+
const chainType = String(ft.chainType || "").toLowerCase();
|
|
72
|
+
if (chainType === "ocap" || chainType === "abt") return !(0, _arcblock_validator.vValidate)(anyDidSchema, ft.contractAddress).error;
|
|
73
|
+
return !(0, _arcblock_validator.vValidate)(ethDidSchema, ft.contractAddress).error;
|
|
74
|
+
}, "Expected wallet type to be \"ethereum\" or valid foreign chain contract address"), ["contractAddress"]), (0, _arcblock_validator.vStripUnknown)());
|
|
39
75
|
const stateSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
40
76
|
address: (0, _arcblock_validator.vDID)({
|
|
41
77
|
prefix: true,
|
|
@@ -45,12 +81,12 @@ const stateSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
|
|
|
45
81
|
description: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(16), _arcblock_validator.v.maxLength(128)),
|
|
46
82
|
symbol: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(2), _arcblock_validator.v.maxLength(6), _arcblock_validator.v.transform((s) => s.toUpperCase())),
|
|
47
83
|
unit: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.minLength(1), _arcblock_validator.v.maxLength(6), _arcblock_validator.v.transform((s) => s.toLowerCase())),
|
|
48
|
-
decimal: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.minValue(2), _arcblock_validator.v.maxValue(18)),
|
|
84
|
+
decimal: _arcblock_validator.v.union([_arcblock_validator.v.literal(0), _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.minValue(2), _arcblock_validator.v.maxValue(18))]),
|
|
49
85
|
icon: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.string())),
|
|
50
86
|
totalSupply: (0, _arcblock_validator.vBN)((0, _arcblock_validator.vBNMin)(0)),
|
|
51
87
|
initialSupply: (0, _arcblock_validator.vBN)((0, _arcblock_validator.vBNMin)(0)),
|
|
52
88
|
maxTotalSupply: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.union([_arcblock_validator.v.literal(""), (0, _arcblock_validator.vBN)((0, _arcblock_validator.vBNGreater)(0))]))),
|
|
53
|
-
foreignToken: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(
|
|
89
|
+
foreignToken: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(multiChainForeignTokenSchema)),
|
|
54
90
|
issuer: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.union([_arcblock_validator.v.literal(""), (0, _arcblock_validator.vDID)({ prefix: true })]))),
|
|
55
91
|
website: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.union([_arcblock_validator.v.literal(""), _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.maxLength(256), _arcblock_validator.v.check(isValidWebsiteUrl, "Must be valid URL"))]))),
|
|
56
92
|
metadata: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.object({
|
|
@@ -99,7 +135,7 @@ const create = (attrs, context) => {
|
|
|
99
135
|
if (!token.data) token.data = null;
|
|
100
136
|
if (!token.metadata) token.metadata = null;
|
|
101
137
|
if (!token.foreignToken) token.foreignToken = null;
|
|
102
|
-
else token.foreignToken.contractAddress = (0, _arcblock_did_lib_type.toChecksumAddress)(token.foreignToken.contractAddress);
|
|
138
|
+
else if (typeof token.foreignToken.contractAddress === "string" && /^0x[0-9a-fA-F]{40}$/.test(token.foreignToken.contractAddress)) token.foreignToken.contractAddress = (0, _arcblock_did_lib_type.toChecksumAddress)(token.foreignToken.contractAddress);
|
|
103
139
|
token.address = (0, _ocap_util.toAddress)(token.address);
|
|
104
140
|
return validate(token);
|
|
105
141
|
};
|
|
@@ -109,20 +145,357 @@ const update = (state, attrs) => validate({
|
|
|
109
145
|
"totalSupply",
|
|
110
146
|
"metadata",
|
|
111
147
|
"icon",
|
|
112
|
-
"website"
|
|
148
|
+
"website",
|
|
149
|
+
"name",
|
|
150
|
+
"description",
|
|
151
|
+
"issuer",
|
|
152
|
+
"data"
|
|
113
153
|
])
|
|
114
154
|
});
|
|
115
155
|
const validate = (state) => {
|
|
116
156
|
if (state.maxTotalSupply && new _ocap_util.BN(state.maxTotalSupply).lt(new _ocap_util.BN(state.totalSupply))) throw new Error("maxTotalSupply must be greater than or equal to totalSupply");
|
|
157
|
+
if (state.decimal === 0 && state.type !== "BondingCurveToken") throw new Error("Invalid token state: decimal=0 is only supported for BondingCurveToken");
|
|
117
158
|
const { value, error } = (0, _arcblock_validator.vValidate)(stateSchema, (0, lodash_cloneDeep.default)(state));
|
|
118
159
|
if (error) throw new Error(`Invalid token state: ${error.message}`);
|
|
119
160
|
return value;
|
|
120
161
|
};
|
|
162
|
+
/**
|
|
163
|
+
* Deterministically derive the companion Master Charter NFT address (`ROLE_ASSET`)
|
|
164
|
+
* for a given Fungible Token address (`ROLE_TOKEN`).
|
|
165
|
+
*/
|
|
166
|
+
const toTokenCharterAssetAddress = (tokenAddress) => {
|
|
167
|
+
if (typeof tokenAddress !== "string" || !tokenAddress.trim()) throw new Error("tokenAddress must be a non-empty string");
|
|
168
|
+
const normalized = (0, _ocap_util.toAddress)(tokenAddress.trim());
|
|
169
|
+
const buffer = Uint8Array.from(Buffer.from(`token-charter:${normalized}`));
|
|
170
|
+
return (0, _arcblock_did.fromHash)(_ocap_mcrypto.Hasher.SHA3.hash256(buffer), _ocap_mcrypto.types.RoleType.ROLE_ASSET);
|
|
171
|
+
};
|
|
172
|
+
const isSafeImageDataUri = (s) => /^data:image\/(png|jpeg|jpg|gif|webp);base64,[A-Za-z0-9+/=\s]+$/i.test(s);
|
|
173
|
+
const isHttpOrHttpsUrl = (s) => {
|
|
174
|
+
try {
|
|
175
|
+
const url = new URL(s);
|
|
176
|
+
return isTest ? ["http:", "https:"].includes(url.protocol) : url.protocol === "https:";
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const MAX_SVG_ICON_BYTES = 16 * 1024;
|
|
182
|
+
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
|
|
183
|
+
const TX_HASH_RE = /^(0x)?[0-9a-fA-F]{64}$/;
|
|
184
|
+
/**
|
|
185
|
+
* Strip dangerous XSS elements/attributes (`<script>`, `<foreignObject>`, `<iframe>`,
|
|
186
|
+
* inline `on*` event handlers, and `javascript:`/`data:text/html` URIs) from SVG strings.
|
|
187
|
+
*/
|
|
188
|
+
const sanitizeTokenSvg = (svg) => svg.replace(/<\s*(script|foreignObject|iframe|object|embed|applet)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, "").replace(/<\s*(script|foreignObject|iframe|object|embed|applet)\b[^>]*\/?\s*>/gi, "").replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/\b(?:href|xlink:href|src|action|formaction)\s*=\s*(?:"\s*(?:javascript|vbscript|data\s*:\s*text\/html)[^"]*"|'\s*(?:javascript|vbscript|data\s*:\s*text\/html)[^']*')/gi, "");
|
|
189
|
+
const iconToNftDisplay = (icon) => {
|
|
190
|
+
if (!icon || typeof icon !== "string") return void 0;
|
|
191
|
+
const trimmed = icon.trim();
|
|
192
|
+
if (!trimmed) return void 0;
|
|
193
|
+
if (isSafeImageDataUri(trimmed) && trimmed.length <= 20480) return {
|
|
194
|
+
type: "uri",
|
|
195
|
+
content: trimmed
|
|
196
|
+
};
|
|
197
|
+
if (isHttpOrHttpsUrl(trimmed) && trimmed.length <= 2048) return {
|
|
198
|
+
type: "url",
|
|
199
|
+
content: trimmed
|
|
200
|
+
};
|
|
201
|
+
if (trimmed.startsWith("<svg") && Buffer.byteLength(trimmed, "utf8") <= MAX_SVG_ICON_BYTES) {
|
|
202
|
+
const sanitized = sanitizeTokenSvg(trimmed).trim();
|
|
203
|
+
if (sanitized.startsWith("<svg") && sanitized.includes("</svg>")) return {
|
|
204
|
+
type: "svg",
|
|
205
|
+
content: sanitized
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const websiteToNftEndpoint = (website) => {
|
|
210
|
+
if (!website || typeof website !== "string") return void 0;
|
|
211
|
+
const trimmed = website.trim();
|
|
212
|
+
if (!trimmed || trimmed.length > 2048 || !isHttpOrHttpsUrl(trimmed)) return void 0;
|
|
213
|
+
return {
|
|
214
|
+
id: trimmed,
|
|
215
|
+
scope: "public"
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
const buildTokenCharterAssetData = (tokenState) => ({
|
|
219
|
+
type: "json",
|
|
220
|
+
value: {
|
|
221
|
+
kind: TOKEN_CHARTER_KIND,
|
|
222
|
+
tokenAddress: (0, _ocap_util.toAddress)(tokenState.address),
|
|
223
|
+
symbol: tokenState.symbol,
|
|
224
|
+
name: tokenState.name,
|
|
225
|
+
description: tokenState.description,
|
|
226
|
+
unit: tokenState.unit,
|
|
227
|
+
decimal: tokenState.decimal,
|
|
228
|
+
icon: tokenState.icon || "",
|
|
229
|
+
website: tokenState.website || "",
|
|
230
|
+
metadata: tokenState.metadata?.value ?? null,
|
|
231
|
+
tokenFactoryAddress: tokenState.tokenFactoryAddress || ""
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
const resolveCharterOwner = (tokenState, ownerOverride) => {
|
|
235
|
+
const candidates = [
|
|
236
|
+
ownerOverride,
|
|
237
|
+
tokenState.issuer,
|
|
238
|
+
tokenState.tokenFactoryAddress,
|
|
239
|
+
tokenState.address
|
|
240
|
+
];
|
|
241
|
+
for (const candidate of candidates) if (candidate && typeof candidate === "string" && (0, _arcblock_did.isValid)((0, _ocap_util.toAddress)(candidate))) return (0, _ocap_util.toAddress)(candidate);
|
|
242
|
+
return (0, _ocap_util.toAddress)(tokenState.address);
|
|
243
|
+
};
|
|
244
|
+
const resolveCharterMoniker = (tokenState) => {
|
|
245
|
+
const rawName = (tokenState.name || "").trim();
|
|
246
|
+
if (rawName.length >= 2) return rawName.slice(0, 255);
|
|
247
|
+
return `${rawName || tokenState.symbol} (${tokenState.symbol})`.slice(0, 255);
|
|
248
|
+
};
|
|
249
|
+
const buildCharterTags = (tokenState) => {
|
|
250
|
+
return [
|
|
251
|
+
"token:charter",
|
|
252
|
+
`token:symbol:${tokenState.symbol}`,
|
|
253
|
+
`token:type:${tokenState.type || "Token"}`
|
|
254
|
+
].map((t) => t.slice(0, 64)).slice(0, 4);
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Build the companion Master Charter `AssetState` (`ROLE_ASSET`) for a `TokenState`.
|
|
258
|
+
*/
|
|
259
|
+
const buildTokenCharterAssetState = (tokenState, context, ownerOverride) => {
|
|
260
|
+
const charterAddress = toTokenCharterAssetAddress(tokenState.address);
|
|
261
|
+
const owner = resolveCharterOwner(tokenState, ownerOverride);
|
|
262
|
+
const issuer = tokenState.issuer && (0, _arcblock_did.isValid)((0, _ocap_util.toAddress)(tokenState.issuer)) ? (0, _ocap_util.toAddress)(tokenState.issuer) : owner;
|
|
263
|
+
const parent = tokenState.tokenFactoryAddress && (0, _arcblock_did.isValid)((0, _ocap_util.toAddress)(tokenState.tokenFactoryAddress)) ? (0, _ocap_util.toAddress)(tokenState.tokenFactoryAddress) : "";
|
|
264
|
+
const sanitizedIcon = typeof tokenState.icon === "string" && tokenState.icon.trim().startsWith("<svg") ? sanitizeTokenSvg(tokenState.icon.trim()) : tokenState.icon;
|
|
265
|
+
const normalizedTokenState = sanitizedIcon !== tokenState.icon ? {
|
|
266
|
+
...tokenState,
|
|
267
|
+
icon: sanitizedIcon
|
|
268
|
+
} : tokenState;
|
|
269
|
+
const display = iconToNftDisplay(normalizedTokenState.icon);
|
|
270
|
+
const endpoint = websiteToNftEndpoint(normalizedTokenState.website);
|
|
271
|
+
const rawGenesisTx = typeof tokenState.context?.genesisTx === "string" ? tokenState.context.genesisTx : "";
|
|
272
|
+
const validGenesisTx = TX_HASH_RE.test(rawGenesisTx) ? rawGenesisTx : "";
|
|
273
|
+
const rawGenesisTime = typeof tokenState.context?.genesisTime === "string" ? tokenState.context.genesisTime : "";
|
|
274
|
+
const validGenesisTime = ISO_DATE_RE.test(rawGenesisTime) ? rawGenesisTime : "2020-01-15T00:00:00.000Z";
|
|
275
|
+
const fallbackContext = context || {
|
|
276
|
+
txHash: validGenesisTx,
|
|
277
|
+
txTime: validGenesisTime
|
|
278
|
+
};
|
|
279
|
+
const created = require_states_asset.create({
|
|
280
|
+
address: charterAddress,
|
|
281
|
+
owner,
|
|
282
|
+
issuer,
|
|
283
|
+
moniker: resolveCharterMoniker(normalizedTokenState),
|
|
284
|
+
parent,
|
|
285
|
+
readonly: false,
|
|
286
|
+
transferrable: true,
|
|
287
|
+
ttl: 0,
|
|
288
|
+
tags: buildCharterTags(normalizedTokenState),
|
|
289
|
+
data: buildTokenCharterAssetData(normalizedTokenState),
|
|
290
|
+
...display ? { display } : {},
|
|
291
|
+
...endpoint ? { endpoint } : {}
|
|
292
|
+
}, fallbackContext);
|
|
293
|
+
if (!context && tokenState.context) {
|
|
294
|
+
const rawRenTx = typeof tokenState.context.renaissanceTx === "string" ? tokenState.context.renaissanceTx : "";
|
|
295
|
+
const rawRenTime = typeof tokenState.context.renaissanceTime === "string" ? tokenState.context.renaissanceTime : "";
|
|
296
|
+
created.context = {
|
|
297
|
+
genesisTx: validGenesisTx,
|
|
298
|
+
genesisTime: validGenesisTime,
|
|
299
|
+
renaissanceTx: TX_HASH_RE.test(rawRenTx) ? rawRenTx : validGenesisTx,
|
|
300
|
+
renaissanceTime: ISO_DATE_RE.test(rawRenTime) ? rawRenTime : validGenesisTime
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
return created;
|
|
304
|
+
};
|
|
305
|
+
/**
|
|
306
|
+
* Verify whether an `AssetState` is a genuine, cryptographically bound Token Charter NFT.
|
|
307
|
+
* Checks both the `TokenCharter` payload structure and the deterministic 1:1 DID binding
|
|
308
|
+
* (`toTokenCharterAssetAddress(tokenAddress) === assetState.address`) to prevent spoofing.
|
|
309
|
+
*/
|
|
310
|
+
const isTokenCharterAsset = (assetState) => {
|
|
311
|
+
if (!assetState || typeof assetState.address !== "string" || !assetState.address) return false;
|
|
312
|
+
const data = assetState.data;
|
|
313
|
+
if (!data || data.type !== "json" || !data.value || data.value.kind !== TOKEN_CHARTER_KIND) return false;
|
|
314
|
+
const tokenAddress = data.value.tokenAddress;
|
|
315
|
+
if (typeof tokenAddress !== "string" || !tokenAddress.trim()) return false;
|
|
316
|
+
try {
|
|
317
|
+
return toTokenCharterAssetAddress(tokenAddress) === (0, _ocap_util.toAddress)(assetState.address);
|
|
318
|
+
} catch {
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Extract validated `TokenState` field updates when a Token Charter NFT is updated via `UpdateAssetTx`
|
|
324
|
+
* or transferred via `UpdateOwner`.
|
|
325
|
+
*/
|
|
326
|
+
const extractTokenUpdatesFromCharterAsset = (tokenState, charterAsset) => {
|
|
327
|
+
if (!isTokenCharterAsset(charterAsset)) return {};
|
|
328
|
+
if (tokenState?.address && toTokenCharterAssetAddress(tokenState.address) !== (0, _ocap_util.toAddress)(charterAsset.address)) return {};
|
|
329
|
+
const payload = charterAsset.data?.value || {};
|
|
330
|
+
const updates = {};
|
|
331
|
+
const currentMoniker = tokenState ? resolveCharterMoniker(tokenState) : "";
|
|
332
|
+
const monikerTrimmed = typeof charterAsset.moniker === "string" ? charterAsset.moniker.trim() : "";
|
|
333
|
+
const payloadNameTrimmed = typeof payload.name === "string" ? payload.name.trim() : "";
|
|
334
|
+
if (payloadNameTrimmed.length >= 1 && payloadNameTrimmed.length <= 32 && payloadNameTrimmed !== tokenState.name) updates.name = payloadNameTrimmed;
|
|
335
|
+
else if (monikerTrimmed.length >= 1 && monikerTrimmed.length <= 32 && monikerTrimmed !== currentMoniker) updates.name = monikerTrimmed;
|
|
336
|
+
else if (payloadNameTrimmed.length >= 1 && payloadNameTrimmed.length <= 32) updates.name = payloadNameTrimmed;
|
|
337
|
+
if (typeof payload.description === "string" && payload.description.length >= 16 && payload.description.length <= 128) updates.description = payload.description;
|
|
338
|
+
const rawIcon = typeof payload.icon === "string" ? payload.icon : typeof charterAsset.display?.content === "string" ? charterAsset.display.content : void 0;
|
|
339
|
+
if (rawIcon !== void 0) {
|
|
340
|
+
const trimmedIcon = rawIcon.trim();
|
|
341
|
+
if (trimmedIcon === "") updates.icon = "";
|
|
342
|
+
else if (trimmedIcon.startsWith("<svg")) {
|
|
343
|
+
if (Buffer.byteLength(trimmedIcon, "utf8") <= MAX_SVG_ICON_BYTES) {
|
|
344
|
+
const sanitized = sanitizeTokenSvg(trimmedIcon).trim();
|
|
345
|
+
if (sanitized.startsWith("<svg") && sanitized.includes("</svg>")) updates.icon = sanitized;
|
|
346
|
+
}
|
|
347
|
+
} else if (isSafeImageDataUri(trimmedIcon) && trimmedIcon.length <= 20480 || isHttpOrHttpsUrl(trimmedIcon) && trimmedIcon.length <= 2048) updates.icon = trimmedIcon;
|
|
348
|
+
}
|
|
349
|
+
if (typeof payload.website === "string" && (payload.website === "" || isValidWebsiteUrl(payload.website))) updates.website = payload.website;
|
|
350
|
+
else if (charterAsset.endpoint?.id && isValidWebsiteUrl(charterAsset.endpoint.id)) updates.website = charterAsset.endpoint.id;
|
|
351
|
+
if (payload.metadata !== void 0) {
|
|
352
|
+
if (payload.metadata === null) updates.metadata = null;
|
|
353
|
+
else if (typeof payload.metadata === "object") {
|
|
354
|
+
const { value: validMeta, error } = (0, _arcblock_validator.vValidate)(metadataSchema, payload.metadata);
|
|
355
|
+
if (!error) updates.metadata = {
|
|
356
|
+
type: "json",
|
|
357
|
+
value: validMeta
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
if (charterAsset.owner && (0, _arcblock_did.isValid)((0, _ocap_util.toAddress)(charterAsset.owner))) updates.issuer = (0, _ocap_util.toAddress)(charterAsset.owner);
|
|
362
|
+
return updates;
|
|
363
|
+
};
|
|
364
|
+
/**
|
|
365
|
+
* Synchronize an existing Token Charter `AssetState` with updated `TokenState` fields.
|
|
366
|
+
*/
|
|
367
|
+
const syncCharterAssetWithToken = (charterAsset, tokenState, context, ownerOverride) => {
|
|
368
|
+
const display = iconToNftDisplay(tokenState.icon);
|
|
369
|
+
const endpoint = websiteToNftEndpoint(tokenState.website);
|
|
370
|
+
return require_states_asset.update(charterAsset, {
|
|
371
|
+
moniker: resolveCharterMoniker(tokenState),
|
|
372
|
+
owner: ownerOverride ? (0, _ocap_util.toAddress)(ownerOverride) : charterAsset.owner,
|
|
373
|
+
data: buildTokenCharterAssetData(tokenState),
|
|
374
|
+
tags: buildCharterTags(tokenState),
|
|
375
|
+
display: display ?? void 0,
|
|
376
|
+
endpoint: endpoint ?? void 0
|
|
377
|
+
}, context);
|
|
378
|
+
};
|
|
379
|
+
/**
|
|
380
|
+
* Normalize legacy `TokenState` fields (such as short descriptions or non-ISO context dates)
|
|
381
|
+
* before re-validating during ownership transfer or migration so legacy rows never brick updates.
|
|
382
|
+
*/
|
|
383
|
+
const normalizeLegacyTokenStateForUpdate = (existingToken) => {
|
|
384
|
+
const normalized = (0, lodash_cloneDeep.default)(existingToken);
|
|
385
|
+
if (typeof normalized.description !== "string" || normalized.description.length < 16) normalized.description = `${(normalized.description || normalized.name || normalized.symbol || "Token").trim()} - Fungible token charter state`.slice(0, 128);
|
|
386
|
+
else if (normalized.description.length > 128) normalized.description = normalized.description.slice(0, 128);
|
|
387
|
+
if (normalized.context) {
|
|
388
|
+
const gTx = typeof normalized.context.genesisTx === "string" ? normalized.context.genesisTx : "";
|
|
389
|
+
const gTime = typeof normalized.context.genesisTime === "string" ? normalized.context.genesisTime : "";
|
|
390
|
+
const rTx = typeof normalized.context.renaissanceTx === "string" ? normalized.context.renaissanceTx : "";
|
|
391
|
+
const rTime = typeof normalized.context.renaissanceTime === "string" ? normalized.context.renaissanceTime : "";
|
|
392
|
+
const validGTx = TX_HASH_RE.test(gTx) ? gTx : "";
|
|
393
|
+
const validGTime = ISO_DATE_RE.test(gTime) ? gTime : "2020-01-15T00:00:00.000Z";
|
|
394
|
+
normalized.context = {
|
|
395
|
+
genesisTx: validGTx,
|
|
396
|
+
genesisTime: validGTime,
|
|
397
|
+
renaissanceTx: TX_HASH_RE.test(rTx) ? rTx : validGTx,
|
|
398
|
+
renaissanceTime: ISO_DATE_RE.test(rTime) ? rTime : validGTime
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
return normalized;
|
|
402
|
+
};
|
|
403
|
+
/**
|
|
404
|
+
* Atomically synchronize `TokenState.issuer` and `TokenFactoryState.owner` whenever
|
|
405
|
+
* a Token Charter NFT changes owner (via `UpdateOwner`, `TransferV3Tx`, `ClaimStakeTx`,
|
|
406
|
+
* `ReturnStakeTx`, or `SlashStakeTx`).
|
|
407
|
+
* Validates all target state updates BEFORE writing to `statedb` to prevent partial writes.
|
|
408
|
+
*/
|
|
409
|
+
const syncTokenCharterOwnership = async (charterAsset, newOwnerAddress, statedb, context) => {
|
|
410
|
+
if (!newOwnerAddress || !isTokenCharterAsset(charterAsset)) return;
|
|
411
|
+
const normalizedOwner = (0, _ocap_util.toAddress)(newOwnerAddress);
|
|
412
|
+
if (!(0, _arcblock_did.isValid)(normalizedOwner)) return;
|
|
413
|
+
const tokenAddress = (charterAsset?.data)?.value?.tokenAddress;
|
|
414
|
+
if (!tokenAddress || !statedb?.token?.get || !statedb?.token?.update) return;
|
|
415
|
+
const existingToken = await statedb.token.get(tokenAddress, context);
|
|
416
|
+
if (!existingToken) return;
|
|
417
|
+
const updatedToken = update(normalizeLegacyTokenStateForUpdate(existingToken), { issuer: normalizedOwner });
|
|
418
|
+
let existingFactory = null;
|
|
419
|
+
let updatedFactory = null;
|
|
420
|
+
if (existingToken.tokenFactoryAddress && statedb.tokenFactory?.get && statedb.tokenFactory?.update) {
|
|
421
|
+
existingFactory = await statedb.tokenFactory.get(existingToken.tokenFactoryAddress, context);
|
|
422
|
+
if (existingFactory) updatedFactory = require_states_token_factory.update(existingFactory, { owner: normalizedOwner }, context);
|
|
423
|
+
}
|
|
424
|
+
await statedb.token.update(tokenAddress, updatedToken, context);
|
|
425
|
+
if (existingFactory && updatedFactory && statedb.tokenFactory?.update) await statedb.tokenFactory.update(existingFactory.address, updatedFactory, context);
|
|
426
|
+
};
|
|
427
|
+
/**
|
|
428
|
+
* Programmatic state migration helper: scans all existing `TokenState` records in `statedb.token`
|
|
429
|
+
* and idempotently backfills their companion Master Charter `AssetState` records in `statedb.asset`.
|
|
430
|
+
*/
|
|
431
|
+
const migrateTokensToCharterAssets = async (statedb, operationContext) => {
|
|
432
|
+
if (!statedb?.token || !statedb?.asset) return {
|
|
433
|
+
migrated: 0,
|
|
434
|
+
skipped: 0,
|
|
435
|
+
charterAddresses: []
|
|
436
|
+
};
|
|
437
|
+
let tokens = [];
|
|
438
|
+
const tokenTable = statedb.token;
|
|
439
|
+
if (typeof tokenTable.findAll === "function") tokens = await tokenTable.findAll({}, operationContext);
|
|
440
|
+
else if (typeof tokenTable.find === "function") tokens = await tokenTable.find({}, operationContext);
|
|
441
|
+
else if (typeof tokenTable.collection?.find === "function") tokens = tokenTable.collection.find({});
|
|
442
|
+
else if (typeof tokenTable.db?.selectFrom === "function") {
|
|
443
|
+
const rows = await tokenTable.db.selectFrom("token").selectAll().execute();
|
|
444
|
+
tokens = typeof tokenTable.deserializeFromDb === "function" ? rows.map((r) => tokenTable.deserializeFromDb(r)) : rows;
|
|
445
|
+
}
|
|
446
|
+
let migrated = 0;
|
|
447
|
+
let skipped = 0;
|
|
448
|
+
const charterAddresses = [];
|
|
449
|
+
for (const tokenState of tokens) {
|
|
450
|
+
if (!tokenState?.address || typeof tokenState.address !== "string") {
|
|
451
|
+
skipped++;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const normalizedTokenAddr = (0, _ocap_util.toAddress)(tokenState.address.trim());
|
|
455
|
+
if (!(0, _arcblock_did.isValid)(normalizedTokenAddr)) {
|
|
456
|
+
skipped++;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
const charterAddress = toTokenCharterAssetAddress(normalizedTokenAddr);
|
|
460
|
+
if (await statedb.asset.get(charterAddress, operationContext)) {
|
|
461
|
+
skipped++;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
let ownerOverride;
|
|
465
|
+
if (tokenState.tokenFactoryAddress && statedb.tokenFactory?.get) {
|
|
466
|
+
const tf = await statedb.tokenFactory.get(tokenState.tokenFactoryAddress, operationContext);
|
|
467
|
+
if (tf?.owner) ownerOverride = tf.owner;
|
|
468
|
+
}
|
|
469
|
+
const charterAsset = buildTokenCharterAssetState(normalizeLegacyTokenStateForUpdate(tokenState), void 0, ownerOverride);
|
|
470
|
+
await statedb.asset.create(charterAddress, charterAsset, operationContext);
|
|
471
|
+
charterAddresses.push(charterAddress);
|
|
472
|
+
migrated++;
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
migrated,
|
|
476
|
+
skipped,
|
|
477
|
+
charterAddresses
|
|
478
|
+
};
|
|
479
|
+
};
|
|
121
480
|
|
|
122
481
|
//#endregion
|
|
482
|
+
exports.TOKEN_CHARTER_KIND = TOKEN_CHARTER_KIND;
|
|
483
|
+
exports.buildTokenCharterAssetData = buildTokenCharterAssetData;
|
|
484
|
+
exports.buildTokenCharterAssetState = buildTokenCharterAssetState;
|
|
123
485
|
exports.create = create;
|
|
486
|
+
exports.extractTokenUpdatesFromCharterAsset = extractTokenUpdatesFromCharterAsset;
|
|
487
|
+
exports.iconToNftDisplay = iconToNftDisplay;
|
|
488
|
+
exports.isTokenCharterAsset = isTokenCharterAsset;
|
|
124
489
|
exports.metadataSchema = metadataSchema;
|
|
490
|
+
exports.migrateTokensToCharterAssets = migrateTokensToCharterAssets;
|
|
491
|
+
exports.multiChainForeignTokenSchema = multiChainForeignTokenSchema;
|
|
492
|
+
exports.normalizeLegacyTokenStateForUpdate = normalizeLegacyTokenStateForUpdate;
|
|
493
|
+
exports.resolveCharterMoniker = resolveCharterMoniker;
|
|
494
|
+
exports.sanitizeTokenSvg = sanitizeTokenSvg;
|
|
125
495
|
exports.stateSchema = stateSchema;
|
|
496
|
+
exports.syncCharterAssetWithToken = syncCharterAssetWithToken;
|
|
497
|
+
exports.syncTokenCharterOwnership = syncTokenCharterOwnership;
|
|
498
|
+
exports.toTokenCharterAssetAddress = toTokenCharterAssetAddress;
|
|
126
499
|
Object.defineProperty(exports, 'token_exports', {
|
|
127
500
|
enumerable: true,
|
|
128
501
|
get: function () {
|
|
@@ -130,4 +503,5 @@ Object.defineProperty(exports, 'token_exports', {
|
|
|
130
503
|
}
|
|
131
504
|
});
|
|
132
505
|
exports.update = update;
|
|
133
|
-
exports.validate = validate;
|
|
506
|
+
exports.validate = validate;
|
|
507
|
+
exports.websiteToNftEndpoint = websiteToNftEndpoint;
|