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