@ocap/asset 1.30.2 → 1.30.4

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 CHANGED
@@ -1,87 +1,7 @@
1
- import { TAssetFactoryState, TCreateAssetTx } from "@ocap/types";
2
- import { WalletObject } from "@ocap/wallet";
3
- import { LiteralUnion, PartialDeep } from "type-fest";
4
-
5
- //#region src/index.d.ts
6
- type $TSFixMe = any;
7
- type TPickedFactoryState = PartialDeep<TAssetFactoryState>;
8
- type TIssuer = {
9
- name: string;
10
- wallet: WalletObject;
11
- };
12
- type TIssuerInput = {
13
- id: string;
14
- pk: string;
15
- name: string;
16
- };
17
- type THook = {
18
- type: LiteralUnion<'contract' | 'url', string>;
19
- name: LiteralUnion<'mint' | 'postMint' | 'preMint', string>;
20
- hook: string;
21
- };
22
- type TInputMap = {
23
- [key: string]: string;
24
- };
25
- type TMintResult = {
26
- address: string;
27
- asset: TCreateAssetTx;
28
- };
29
- type TPreMintResult = TMintResult & {
30
- variables: TInputMap;
31
- issuer: TIssuerInput;
32
- };
33
- declare const isValidNotation: (notation: string) => boolean;
34
- declare const isValidHook: (hook: THook, quota?: $TSFixMe, throwOnError?: boolean) => boolean;
35
- declare const isValidFactory: (props: any) => boolean;
36
- /**
37
- * Find credentialSubject path in the object
38
- * Because they need prerender
39
- *
40
- * @param {object} obj
41
- * @param {string} keyword
42
- * @return {string} list of keys
43
- */
44
- declare const findPrerenderKeys: (obj: $TSFixMe, keyword: string) => string[];
45
- /**
46
- * Mint from an asset factory, used on server side
47
- *
48
- * @param {object} params { factory, inputs, issuer }
49
- * @param {object} params.factory factory object
50
- * @param {object} params.inputs factory input variables
51
- * @param {string} params.owner owner did for the new asset
52
- * @param {object} params.issuer issuer object
53
- */
54
- declare const mintFromFactory: ({
55
- factory,
56
- inputs,
57
- owner,
58
- issuer
59
- }: {
60
- factory: TPickedFactoryState;
61
- inputs: TInputMap;
62
- owner: string;
63
- issuer: TIssuerInput;
64
- }) => TMintResult;
65
- /**
66
- * Simulate minting from an asset factory, used for client side
67
- *
68
- * @param {object} params { factory, inputs, issuer }
69
- * @param {object} params.factory factory object
70
- * @param {object} params.inputs factory input variables
71
- * @param {string} params.owner owner did for the new asset
72
- * @param {object} params.issuer factory issuer wallet and name
73
- */
74
- declare const preMintFromFactory: ({
75
- factory,
76
- inputs,
77
- owner,
78
- issuer
79
- }: {
80
- factory?: TPickedFactoryState;
81
- inputs: TInputMap;
82
- owner?: string;
83
- issuer?: TIssuer;
84
- }) => Promise<TPreMintResult>;
85
- declare const formatFactoryState: (state: TAssetFactoryState) => TPickedFactoryState;
86
- //#endregion
87
- export { THook, TInputMap, TIssuer, TIssuerInput, TMintResult, TPickedFactoryState, TPreMintResult, findPrerenderKeys, formatFactoryState, isValidFactory, isValidHook, isValidNotation, mintFromFactory, preMintFromFactory };
1
+ import { DecodedAny, THook, TInputMap, TIssuer, TIssuerInput, TMintResult, TPickedFactoryState, TPreMintResult } from "./types.mjs";
2
+ import { findPrerenderKeys, isValidNotation } from "./utils.mjs";
3
+ import { formatFactoryState } from "./mint/shared.mjs";
4
+ import { mintFromFactory, preMintFromFactory } from "./mint/server.mjs";
5
+ import "./mint.mjs";
6
+ import { isValidFactory, isValidHook } from "./validate.mjs";
7
+ export { type DecodedAny, type THook, type TInputMap, type TIssuer, type TIssuerInput, type TMintResult, type TPickedFactoryState, type TPreMintResult, findPrerenderKeys, formatFactoryState, isValidFactory, isValidHook, isValidNotation, mintFromFactory, preMintFromFactory };
package/esm/index.mjs CHANGED
@@ -1,250 +1,6 @@
1
- import { fromPublicKeyHash, toTypeInfo } from "@arcblock/did";
2
- import { toAssetAddress } from "@arcblock/did-util";
3
- import { schemas, vValidate } from "@arcblock/validator";
4
- import { proofTypes, stableStringify, verify } from "@arcblock/vc";
5
- import { compile, getQuota, validate } from "@ocap/contract";
6
- import { types } from "@ocap/mcrypto";
7
- import { toBase58, toBase64 } from "@ocap/util";
8
- import Debug from "debug";
9
- import flatten from "flat";
10
- import isAbsoluteUrl from "is-absolute-url";
11
- import cloneDeep from "lodash/cloneDeep.js";
12
- import get from "lodash/get.js";
13
- import isEmpty from "lodash/isEmpty.js";
14
- import set from "lodash/set.js";
15
- import uniq from "lodash/uniq.js";
16
- import uniqBy from "lodash/uniqBy.js";
17
- import mustache from "mustache";
1
+ import { findPrerenderKeys, isValidNotation } from "./utils.mjs";
2
+ import { formatFactoryState } from "./mint/shared.mjs";
3
+ import { mintFromFactory, preMintFromFactory } from "./mint/server.mjs";
4
+ import { isValidFactory, isValidHook } from "./validate.mjs";
18
5
 
19
- //#region src/index.ts
20
- const debug = Debug("@ocap/asset");
21
- const SUPPORTED_HOOK_NAMES = [
22
- "preMint",
23
- "mint",
24
- "postMint"
25
- ];
26
- const SUPPORTED_HOOK_TYPES = ["contract", "url"];
27
- const isValidNotation = (notation) => [
28
- "ctx",
29
- "data",
30
- "input"
31
- ].includes(notation.split(".").shift() ?? "");
32
- const isValidHook = (hook, quota, throwOnError = false) => {
33
- if (SUPPORTED_HOOK_TYPES.includes(hook.type) === false) return false;
34
- if (SUPPORTED_HOOK_NAMES.includes(hook.name) === false) return false;
35
- if (hook.type === "url") return isAbsoluteUrl(hook.hook);
36
- if (hook.type === "contract") try {
37
- validate(compile(hook.hook), quota);
38
- return true;
39
- } catch (err) {
40
- if (process.env.NODE_ENV !== "test") console.error("invalid contract hook", err.message);
41
- if (throwOnError) throw new Error(`Factory hook ${hook.name} is invalid: ${err.message}`);
42
- return false;
43
- }
44
- return false;
45
- };
46
- const isValidFactory = (props) => {
47
- if (!props) throw new Error("Factory props should not be empty");
48
- const { value, error } = vValidate(schemas.factorySchema, props);
49
- if (error) throw new Error(`Invalid factory: ${error.details.map((x) => x.message).join(", ")}`);
50
- if (["tokens", "assets"].every((x) => isEmpty(value.input[x])) && value.input.value <= 0) throw new Error("Factory input should contain at least one token or asset");
51
- if (uniqBy(value.input.tokens, "address").length !== value.input.tokens.length) throw new Error("Factory token input should not contains duplicate address");
52
- if (uniq(value.input.assets).length !== value.input.assets.length) throw new Error("Factory asset input should not contains duplicate address");
53
- try {
54
- const template = JSON.stringify(value.output, null, 2);
55
- if (mustache.parse(template).filter(([type]) => type === "name").some(([, notation]) => isValidNotation(notation) === false)) throw new Error("Invalid tags found in the output template");
56
- } catch (_err) {
57
- throw new Error("Factory output should be a valid mustache template when serialized as json");
58
- }
59
- const quota = getQuota(value.input);
60
- if (Array.isArray(value.hooks)) {
61
- const invalidHook = value.hooks.find((x) => isValidHook(x, quota, true) === false);
62
- if (invalidHook) throw new Error(`Factory hook ${invalidHook.name} is invalid`);
63
- }
64
- if (value.settlement === "instant") {
65
- if (quota.value <= 0 && Object.keys(quota.tokens).every((x) => quota[x] <= 0)) return true;
66
- if (isEmpty(value.hooks)) throw new Error("Factory hooks should not be empty for instant settlement");
67
- const mintHook = value.hooks.find((x) => x.name === "mint");
68
- if (!mintHook) throw new Error("Factory hook mint should not be empty for instant settlement that consumes token");
69
- try {
70
- validate(compile(mintHook.hook), quota, true);
71
- } catch (err) {
72
- throw new Error(`Factory hook mint is invalid: ${err.message}`);
73
- }
74
- }
75
- return true;
76
- };
77
- /**
78
- * Find credentialSubject path in the object
79
- * Because they need prerender
80
- *
81
- * @param {object} obj
82
- * @param {string} keyword
83
- * @return {string} list of keys
84
- */
85
- const findPrerenderKeys = (obj, keyword) => {
86
- const flatObj = flatten(obj, { safe: true });
87
- return uniq(Object.keys(flatObj).map((x) => x.split(".")).filter((x) => x.includes(keyword)).map((x) => x.slice(0, x.lastIndexOf(keyword) + 1)).sort((a, b) => b.length - a.length).map((x) => x.join(".")));
88
- };
89
- /**
90
- * Mint from an asset factory, used on server side
91
- *
92
- * @param {object} params { factory, inputs, issuer }
93
- * @param {object} params.factory factory object
94
- * @param {object} params.inputs factory input variables
95
- * @param {string} params.owner owner did for the new asset
96
- * @param {object} params.issuer issuer object
97
- */
98
- const mintFromFactory = ({ factory, inputs, owner, issuer }) => {
99
- const { output, address: factoryAddress, numMinted, data } = factory;
100
- debug("mintFromFactory.args", JSON.stringify({
101
- output,
102
- factoryAddress,
103
- numMinted,
104
- inputs,
105
- owner,
106
- issuer,
107
- data
108
- }, null, 2));
109
- const asset = JSON.parse(mustache.render(JSON.stringify(output), {
110
- input: inputs,
111
- data: data?.value || data,
112
- ctx: {
113
- factory: factoryAddress,
114
- id: (numMinted ?? 0) + 1,
115
- owner,
116
- issuer
117
- }
118
- }));
119
- const address = toAssetAddress(asset);
120
- debug("mintFromFactory.result", JSON.stringify({
121
- asset,
122
- address
123
- }, null, 2));
124
- return {
125
- asset,
126
- address
127
- };
128
- };
129
- /**
130
- * Simulate minting from an asset factory, used for client side
131
- *
132
- * @param {object} params { factory, inputs, issuer }
133
- * @param {object} params.factory factory object
134
- * @param {object} params.inputs factory input variables
135
- * @param {string} params.owner owner did for the new asset
136
- * @param {object} params.issuer factory issuer wallet and name
137
- */
138
- const preMintFromFactory = async ({ factory, inputs, owner, issuer }) => {
139
- if (Object.keys(inputs).some((x) => typeof inputs[x] !== "string")) throw new Error("Failed to mint asset from factory: input values must be strings");
140
- if (!factory) throw new Error("Failed to mint asset from factory: factory is required");
141
- if (!issuer) throw new Error("Failed to mint asset from factory: issuer is required");
142
- let asset = null;
143
- const { output, numMinted, address: factoryAddress, data } = factory;
144
- const { wallet, name } = issuer;
145
- debug("preMintFromFactory.args", JSON.stringify({
146
- output,
147
- factoryAddress,
148
- numMinted,
149
- inputs,
150
- owner,
151
- issuer,
152
- data
153
- }, null, 2));
154
- const extra = {};
155
- const issuerObject = {
156
- id: wallet.address,
157
- pk: toBase58(wallet.publicKey),
158
- name
159
- };
160
- const render = (templateObject) => JSON.parse(mustache.render(JSON.stringify(templateObject), {
161
- input: {
162
- ...inputs,
163
- ...extra
164
- },
165
- data: data?.value || data,
166
- ctx: {
167
- factory: factoryAddress,
168
- id: (numMinted ?? 0) + 1,
169
- owner,
170
- issuer: issuerObject
171
- }
172
- }));
173
- const template = cloneDeep(output);
174
- const prerenderKeys = findPrerenderKeys(template, "credentialSubject");
175
- if (prerenderKeys.length) {
176
- extra.issuanceDate = (/* @__PURE__ */ new Date()).toISOString();
177
- for (const key of prerenderKeys) {
178
- const subjectTemplate = get(template, key);
179
- const subjectObject = Array.isArray(subjectTemplate) ? subjectTemplate.map((x) => render(x)) : render(subjectTemplate);
180
- set(template, key, subjectObject);
181
- const vcRootPath = key.split(".").slice(0, -1).join(".");
182
- const vcIdPath = vcRootPath.split(".").concat(["id"]).join(".");
183
- const typeInfo = toTypeInfo(issuerObject.id);
184
- const pkType = typeInfo.pk;
185
- const vcType = {
186
- ...typeInfo,
187
- role: types.RoleType.ROLE_VC
188
- };
189
- const vcId = fromPublicKeyHash(wallet.hash(stableStringify(subjectObject)), vcType);
190
- extra.id = vcId;
191
- extra.proofType = proofTypes[pkType];
192
- set(template, vcIdPath, vcId);
193
- if (!proofTypes[pkType]) throw new Error("Unsupported signer type when create verifiable credential");
194
- let vcObj = render(get(template, vcRootPath));
195
- vcObj.proof = void 0;
196
- const vcStr = stableStringify(vcObj);
197
- const signature = toBase64(await wallet.sign(vcStr));
198
- vcObj.proof = {
199
- type: proofTypes[pkType],
200
- created: extra.issuanceDate,
201
- proofPurpose: "assertionMethod",
202
- jws: signature
203
- };
204
- extra.signature = signature;
205
- try {
206
- asset = render(cloneDeep(output));
207
- vcObj = get(asset, vcRootPath);
208
- debug("preMintFromFactory.result", JSON.stringify(asset, null, 2));
209
- await verify({
210
- vc: vcObj,
211
- trustedIssuers: [issuerObject.id],
212
- ownerDid: owner,
213
- ignoreExpired: true
214
- });
215
- } catch (err) {
216
- console.error(err);
217
- throw new Error("Failed to mint asset from factory: invalid verifiable credential minted");
218
- }
219
- }
220
- } else {
221
- asset = render(template);
222
- debug("preMintFromFactory.result", JSON.stringify(asset, null, 2));
223
- }
224
- return {
225
- address: toAssetAddress(asset),
226
- issuer: issuerObject,
227
- variables: {
228
- ...inputs,
229
- ...extra
230
- },
231
- asset
232
- };
233
- };
234
- const formatFactoryState = (state) => {
235
- const { address, output, data, numMinted } = state;
236
- const outputX = cloneDeep(output);
237
- const outputData = outputX.data;
238
- outputData.value = JSON.parse(outputData.value);
239
- outputData.type = outputData.typeUrl;
240
- const stateData = data;
241
- return {
242
- address,
243
- output: outputX,
244
- data: stateData?.value ? JSON.parse(stateData.value) : {},
245
- numMinted
246
- };
247
- };
248
-
249
- //#endregion
250
6
  export { findPrerenderKeys, formatFactoryState, isValidFactory, isValidHook, isValidNotation, mintFromFactory, preMintFromFactory };
@@ -0,0 +1,17 @@
1
+ import { TInputMap, TIssuer, TPickedFactoryState, TPreMintResult } from "../types.mjs";
2
+ import { formatFactoryState } from "./shared.mjs";
3
+
4
+ //#region src/mint/client.d.ts
5
+ declare const preMintFromFactory: ({
6
+ factory,
7
+ inputs,
8
+ owner,
9
+ issuer
10
+ }: {
11
+ factory?: TPickedFactoryState;
12
+ inputs: TInputMap;
13
+ owner?: string;
14
+ issuer?: TIssuer;
15
+ }) => Promise<TPreMintResult>;
16
+ //#endregion
17
+ export { formatFactoryState, preMintFromFactory };
@@ -0,0 +1,32 @@
1
+ import { formatFactoryState, preparePreMintAsset } from "./shared.mjs";
2
+ import { toAssetAddress } from "@arcblock/did-util/cbor";
3
+
4
+ //#region src/mint/client.ts
5
+ /**
6
+ * `@ocap/asset/mint/client` — CBOR-only mint helpers.
7
+ *
8
+ * Pulls `toAssetAddress` from `@arcblock/did-util/cbor` so browser/Worker
9
+ * bundles that stick to CBOR never drag `google-protobuf` or any `*_pb.js`
10
+ * in through the aggregate did-util entry.
11
+ *
12
+ * The client-facing `preMintFromFactory` drops the legacy `encoding`
13
+ * parameter — the subpath IS the encoding selector. Chain-side callers that
14
+ * need dispatch keep using `@ocap/asset/mint/server` or `@ocap/asset`.
15
+ */
16
+ const preMintFromFactory = async ({ factory, inputs, owner, issuer }) => {
17
+ const { asset, issuer: issuerObject, variables } = await preparePreMintAsset({
18
+ factory,
19
+ inputs,
20
+ owner,
21
+ issuer
22
+ });
23
+ return {
24
+ address: toAssetAddress(asset),
25
+ issuer: issuerObject,
26
+ variables,
27
+ asset
28
+ };
29
+ };
30
+
31
+ //#endregion
32
+ export { formatFactoryState, preMintFromFactory };
@@ -0,0 +1,34 @@
1
+ import { TInputMap, TIssuer, TIssuerInput, TMintResult, TPickedFactoryState, TPreMintResult } from "../types.mjs";
2
+ import { formatFactoryState } from "./shared.mjs";
3
+ import { ItxEncoding } from "@arcblock/did-util";
4
+
5
+ //#region src/mint/server.d.ts
6
+
7
+ declare const mintFromFactory: ({
8
+ factory,
9
+ inputs,
10
+ owner,
11
+ issuer,
12
+ encoding
13
+ }: {
14
+ factory: TPickedFactoryState;
15
+ inputs: TInputMap;
16
+ owner: string;
17
+ issuer: TIssuerInput;
18
+ encoding: ItxEncoding;
19
+ }) => TMintResult;
20
+ declare const preMintFromFactory: ({
21
+ factory,
22
+ inputs,
23
+ owner,
24
+ issuer,
25
+ encoding
26
+ }: {
27
+ factory?: TPickedFactoryState;
28
+ inputs: TInputMap;
29
+ owner?: string;
30
+ issuer?: TIssuer;
31
+ encoding: ItxEncoding;
32
+ }) => Promise<TPreMintResult>;
33
+ //#endregion
34
+ export { formatFactoryState, mintFromFactory, preMintFromFactory };
@@ -0,0 +1,49 @@
1
+ import { formatFactoryState, preparePreMintAsset, renderMintAsset } from "./shared.mjs";
2
+ import Debug from "debug";
3
+ import { toAssetAddress } from "@arcblock/did-util";
4
+
5
+ //#region src/mint/server.ts
6
+ /**
7
+ * `@ocap/asset/mint/server` — dual-encoding mint helpers for chain-side use.
8
+ *
9
+ * Pulls `toAssetAddress` from the aggregate `@arcblock/did-util` entry, which
10
+ * dispatches on the explicit `encoding` argument. Server pipes read
11
+ * `context.txEncoding` (filled by the DecodeTx pipe's tag-55799 check) and
12
+ * pass it in.
13
+ */
14
+ const debug = Debug("@ocap/asset");
15
+ const mintFromFactory = ({ factory, inputs, owner, issuer, encoding }) => {
16
+ const asset = renderMintAsset({
17
+ factory,
18
+ inputs,
19
+ owner,
20
+ issuer
21
+ });
22
+ const address = toAssetAddress(asset, encoding);
23
+ debug("mintFromFactory.result", JSON.stringify({
24
+ asset,
25
+ address,
26
+ encoding
27
+ }, null, 2));
28
+ return {
29
+ asset,
30
+ address
31
+ };
32
+ };
33
+ const preMintFromFactory = async ({ factory, inputs, owner, issuer, encoding }) => {
34
+ const { asset, issuer: issuerObject, variables } = await preparePreMintAsset({
35
+ factory,
36
+ inputs,
37
+ owner,
38
+ issuer
39
+ });
40
+ return {
41
+ address: toAssetAddress(asset, encoding),
42
+ issuer: issuerObject,
43
+ variables,
44
+ asset
45
+ };
46
+ };
47
+
48
+ //#endregion
49
+ export { formatFactoryState, mintFromFactory, preMintFromFactory };
@@ -0,0 +1,47 @@
1
+ import { TInputMap, TIssuer, TIssuerInput, TPickedFactoryState } from "../types.mjs";
2
+ import { TAssetFactoryState, TCreateAssetTx } from "@ocap/types";
3
+
4
+ //#region src/mint/shared.d.ts
5
+ type $TSFixMe = any;
6
+ declare const formatFactoryState: (state: TAssetFactoryState) => TPickedFactoryState;
7
+ /**
8
+ * Render the asset payload for `mintFromFactory`. Pure sync template expand —
9
+ * no VC signing, no async calls. Callers compute the address via the
10
+ * encoding-appropriate `toAssetAddress`.
11
+ */
12
+ declare const renderMintAsset: ({
13
+ factory,
14
+ inputs,
15
+ owner,
16
+ issuer
17
+ }: {
18
+ factory: TPickedFactoryState;
19
+ inputs: TInputMap;
20
+ owner: string;
21
+ issuer: TIssuerInput;
22
+ }) => TCreateAssetTx;
23
+ /**
24
+ * Build the rendered asset + resolved issuer + resolved variables for a
25
+ * pre-mint flow. Handles credentialSubject prerender + VC proof signing.
26
+ *
27
+ * Callers compute the final address via the encoding-appropriate
28
+ * `toAssetAddress`. Matches the original `preMintFromFactory` behavior one
29
+ * for one — the only factored-out line is the final address derivation.
30
+ */
31
+ declare const preparePreMintAsset: ({
32
+ factory,
33
+ inputs,
34
+ owner,
35
+ issuer
36
+ }: {
37
+ factory?: TPickedFactoryState;
38
+ inputs: TInputMap;
39
+ owner?: string;
40
+ issuer?: TIssuer;
41
+ }) => Promise<{
42
+ asset: $TSFixMe;
43
+ issuer: TIssuerInput;
44
+ variables: TInputMap;
45
+ }>;
46
+ //#endregion
47
+ export { formatFactoryState, preparePreMintAsset, renderMintAsset };