@ocap/asset 1.27.16 → 1.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.d.ts CHANGED
@@ -1,36 +1,38 @@
1
- import type { LiteralUnion, PartialDeep } from 'type-fest';
2
- import type { WalletObject } from '@ocap/wallet';
3
- import type { TAssetFactoryState, TCreateAssetTx } from '@ocap/types';
1
+ import { LiteralUnion, PartialDeep } from "type-fest";
2
+ import { WalletObject } from "@ocap/wallet";
3
+ import { TAssetFactoryState, TCreateAssetTx } from "@ocap/types";
4
+
5
+ //#region src/index.d.ts
4
6
  type $TSFixMe = any;
5
- export type TPickedFactoryState = PartialDeep<TAssetFactoryState>;
6
- export type TIssuer = {
7
- name: string;
8
- wallet: WalletObject;
7
+ type TPickedFactoryState = PartialDeep<TAssetFactoryState>;
8
+ type TIssuer = {
9
+ name: string;
10
+ wallet: WalletObject;
9
11
  };
10
- export type TIssuerInput = {
11
- id: string;
12
- pk: string;
13
- name: string;
12
+ type TIssuerInput = {
13
+ id: string;
14
+ pk: string;
15
+ name: string;
14
16
  };
15
- export type THook = {
16
- type: LiteralUnion<'contract' | 'url', string>;
17
- name: LiteralUnion<'mint' | 'postMint' | 'preMint', string>;
18
- hook: string;
17
+ type THook = {
18
+ type: LiteralUnion<'contract' | 'url', string>;
19
+ name: LiteralUnion<'mint' | 'postMint' | 'preMint', string>;
20
+ hook: string;
19
21
  };
20
- export type TInputMap = {
21
- [key: string]: string;
22
+ type TInputMap = {
23
+ [key: string]: string;
22
24
  };
23
- export type TMintResult = {
24
- address: string;
25
- asset: TCreateAssetTx;
25
+ type TMintResult = {
26
+ address: string;
27
+ asset: TCreateAssetTx;
26
28
  };
27
- export type TPreMintResult = TMintResult & {
28
- variables: TInputMap;
29
- issuer: TIssuerInput;
29
+ type TPreMintResult = TMintResult & {
30
+ variables: TInputMap;
31
+ issuer: TIssuerInput;
30
32
  };
31
- export declare const isValidNotation: (notation: string) => boolean;
32
- export declare const isValidHook: (hook: THook, quota?: $TSFixMe, throwOnError?: boolean) => boolean;
33
- export declare const isValidFactory: (props: any) => boolean;
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;
34
36
  /**
35
37
  * Find credentialSubject path in the object
36
38
  * Because they need prerender
@@ -39,7 +41,7 @@ export declare const isValidFactory: (props: any) => boolean;
39
41
  * @param {string} keyword
40
42
  * @return {string} list of keys
41
43
  */
42
- export declare const findPrerenderKeys: (obj: $TSFixMe, keyword: string) => string[];
44
+ declare const findPrerenderKeys: (obj: $TSFixMe, keyword: string) => string[];
43
45
  /**
44
46
  * Mint from an asset factory, used on server side
45
47
  *
@@ -49,11 +51,16 @@ export declare const findPrerenderKeys: (obj: $TSFixMe, keyword: string) => stri
49
51
  * @param {string} params.owner owner did for the new asset
50
52
  * @param {object} params.issuer issuer object
51
53
  */
52
- export declare const mintFromFactory: ({ factory, inputs, owner, issuer, }: {
53
- factory: TPickedFactoryState;
54
- inputs: TInputMap;
55
- owner: string;
56
- issuer: TIssuerInput;
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;
57
64
  }) => TMintResult;
58
65
  /**
59
66
  * Simulate minting from an asset factory, used for client side
@@ -64,11 +71,17 @@ export declare const mintFromFactory: ({ factory, inputs, owner, issuer, }: {
64
71
  * @param {string} params.owner owner did for the new asset
65
72
  * @param {object} params.issuer factory issuer wallet and name
66
73
  */
67
- export declare const preMintFromFactory: ({ factory, inputs, owner, issuer, }: {
68
- factory?: TPickedFactoryState;
69
- inputs: TInputMap;
70
- owner?: string;
71
- issuer?: TIssuer;
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;
72
84
  }) => Promise<TPreMintResult>;
73
- export declare const formatFactoryState: (state: TAssetFactoryState) => TPickedFactoryState;
74
- export {};
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 };
package/esm/index.js CHANGED
@@ -1,248 +1,245 @@
1
- /* eslint-disable @typescript-eslint/ban-ts-comment */
2
- import get from 'lodash/get';
3
- import set from 'lodash/set';
4
- import uniq from 'lodash/uniq';
5
- import uniqBy from 'lodash/uniqBy';
6
- import isEmpty from 'lodash/isEmpty';
7
- import flatten from 'flat';
8
- import mustache from 'mustache';
9
- import isAbsoluteUrl from 'is-absolute-url';
10
- import cloneDeep from 'lodash/cloneDeep';
11
- import { toTypeInfo, fromPublicKeyHash } from '@arcblock/did';
12
- import { verify, stableStringify, proofTypes } from '@arcblock/vc';
13
- import { schemas } from '@arcblock/validator';
14
- import { toAssetAddress } from '@arcblock/did-util';
15
- import { types } from '@ocap/mcrypto';
16
- import { toBase58, toBase64 } from '@ocap/util';
17
- import { compile, validate, getQuota } from '@ocap/contract';
18
- import Debug from 'debug';
19
- const debug = Debug('@ocap/asset');
20
- const SUPPORTED_HOOK_NAMES = ['preMint', 'mint', 'postMint'];
21
- const SUPPORTED_HOOK_TYPES = ['contract', 'url'];
22
- export const isValidNotation = (notation) => ['ctx', 'data', 'input'].includes(notation.split('.').shift());
23
- export const isValidHook = (hook, quota, throwOnError = false) => {
24
- if (SUPPORTED_HOOK_TYPES.includes(hook.type) === false) {
25
- return false;
26
- }
27
- if (SUPPORTED_HOOK_NAMES.includes(hook.name) === false) {
28
- return false;
29
- }
30
- if (hook.type === 'url') {
31
- return isAbsoluteUrl(hook.hook);
32
- }
33
- if (hook.type === 'contract') {
34
- try {
35
- const compiled = compile(hook.hook);
36
- validate(compiled, quota);
37
- return true;
38
- }
39
- catch (err) {
40
- if (process.env.NODE_ENV !== 'test') {
41
- console.error('invalid contract hook', err.message);
42
- }
43
- if (throwOnError) {
44
- throw new Error(`Factory hook ${hook.name} is invalid: ${err.message}`);
45
- }
46
- return false;
47
- }
48
- }
49
- return false;
1
+ import get from "lodash/get.js";
2
+ import set from "lodash/set.js";
3
+ import uniq from "lodash/uniq.js";
4
+ import uniqBy from "lodash/uniqBy.js";
5
+ import isEmpty from "lodash/isEmpty.js";
6
+ import flatten from "flat";
7
+ import mustache from "mustache";
8
+ import isAbsoluteUrl from "is-absolute-url";
9
+ import cloneDeep from "lodash/cloneDeep.js";
10
+ import { fromPublicKeyHash, toTypeInfo } from "@arcblock/did";
11
+ import { proofTypes, stableStringify, verify } from "@arcblock/vc";
12
+ import { schemas } from "@arcblock/validator";
13
+ import { toAssetAddress } from "@arcblock/did-util";
14
+ import { types } from "@ocap/mcrypto";
15
+ import { toBase58, toBase64 } from "@ocap/util";
16
+ import { compile, getQuota, validate } from "@ocap/contract";
17
+ import Debug from "debug";
18
+
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;
50
45
  };
51
- // @link https://github.com/improbable-eng/ts-protoc-gen
52
- export const isValidFactory = (props) => {
53
- if (!props) {
54
- throw new Error('Factory props should not be empty');
55
- }
56
- const { value, error } = schemas.factorySchema.validate(props);
57
- if (error) {
58
- throw new Error(`Invalid factory: ${error.details.map((x) => x.message).join(', ')}`);
59
- }
60
- // input.tokens and input.assets should not be empty
61
- if (['tokens', 'assets'].every((x) => isEmpty(value.input[x])) && value.input.value <= 0) {
62
- throw new Error('Factory input should contain at least one token or asset');
63
- }
64
- if (uniqBy(value.input.tokens, 'address').length !== value.input.tokens.length) {
65
- throw new Error('Factory token input should not contains duplicate address');
66
- }
67
- if (uniq(value.input.assets).length !== value.input.assets.length) {
68
- throw new Error('Factory asset input should not contains duplicate address');
69
- }
70
- try {
71
- // should be a valid mustache template when serialized as json
72
- const template = JSON.stringify(value.output, null, 2);
73
- const result = mustache.parse(template);
74
- if (result.filter(([type]) => type === 'name').some(([, notation]) => isValidNotation(notation) === false)) {
75
- throw new Error('Invalid tags found in the output template');
76
- }
77
- }
78
- catch (err) {
79
- throw new Error('Factory output should be a valid mustache template when serialized as json');
80
- }
81
- // validate hooks
82
- const quota = getQuota(value.input);
83
- if (Array.isArray(value.hooks)) {
84
- const invalidHook = value.hooks.find((x) => isValidHook(x, quota, true) === false);
85
- if (invalidHook) {
86
- throw new Error(`Factory hook ${invalidHook.name} is invalid`);
87
- }
88
- }
89
- // ensure input and hook are zero-sum for factories that consumes token
90
- if (value.settlement === 'instant') {
91
- if (quota.value <= 0 && Object.keys(quota.tokens).every((x) => quota[x] <= 0)) {
92
- return true;
93
- }
94
- if (isEmpty(value.hooks)) {
95
- throw new Error('Factory hooks should not be empty for instant settlement');
96
- }
97
- const mintHook = value.hooks.find((x) => x.name === 'mint');
98
- if (!mintHook) {
99
- throw new Error('Factory hook mint should not be empty for instant settlement that consumes token');
100
- }
101
- try {
102
- const compiled = compile(mintHook.hook);
103
- validate(compiled, quota, true);
104
- }
105
- catch (err) {
106
- throw new Error(`Factory hook mint is invalid: ${err.message}`);
107
- }
108
- }
109
- return true;
46
+ const isValidFactory = (props) => {
47
+ if (!props) throw new Error("Factory props should not be empty");
48
+ const { value, error } = schemas.factorySchema.validate(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;
110
76
  };
111
77
  /**
112
- * Find credentialSubject path in the object
113
- * Because they need prerender
114
- *
115
- * @param {object} obj
116
- * @param {string} keyword
117
- * @return {string} list of keys
118
- */
119
- export const findPrerenderKeys = (obj, keyword) => {
120
- const flatObj = flatten(obj, { safe: true });
121
- const keys = Object.keys(flatObj)
122
- .map((x) => x.split('.'))
123
- .filter((x) => x.includes(keyword))
124
- .map((x) => x.slice(0, x.lastIndexOf(keyword) + 1))
125
- .sort((a, b) => b.length - a.length)
126
- .map((x) => x.join('.'));
127
- return uniq(keys);
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(".")));
128
88
  };
129
89
  /**
130
- * Mint from an asset factory, used on server 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 issuer object
137
- */
138
- export const mintFromFactory = ({ factory, inputs, owner, issuer, }) => {
139
- const { output, address: factoryAddress, numMinted, data } = factory;
140
- debug('mintFromFactory.args', JSON.stringify({ output, factoryAddress, numMinted, inputs, owner, issuer, data }, null, 2));
141
- const asset = JSON.parse(mustache.render(JSON.stringify(output), {
142
- input: inputs,
143
- data: data.value || data,
144
- ctx: { factory: factoryAddress, id: numMinted + 1, owner, issuer },
145
- }));
146
- const address = toAssetAddress(asset);
147
- debug('mintFromFactory.result', JSON.stringify({ asset, address }, null, 2));
148
- return { asset, address };
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 + 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
+ };
149
128
  };
150
129
  /**
151
- * Simulate minting from an asset factory, used for client side
152
- *
153
- * @param {object} params { factory, inputs, issuer }
154
- * @param {object} params.factory factory object
155
- * @param {object} params.inputs factory input variables
156
- * @param {string} params.owner owner did for the new asset
157
- * @param {object} params.issuer factory issuer wallet and name
158
- */
159
- export const preMintFromFactory = async ({ factory, inputs, owner, issuer, }) => {
160
- if (Object.keys(inputs).some((x) => typeof inputs[x] !== 'string')) {
161
- throw new Error('Failed to mint asset from factory: input values must be strings');
162
- }
163
- let asset = null;
164
- const { output, numMinted, address: factoryAddress, data } = factory;
165
- const { wallet, name } = issuer;
166
- debug('preMintFromFactory.args', JSON.stringify({ output, factoryAddress, numMinted, inputs, owner, issuer, data }, null, 2));
167
- const extra = {};
168
- const issuerObject = { id: wallet.address, pk: toBase58(wallet.publicKey), name };
169
- const render = (templateObject) => JSON.parse(mustache.render(JSON.stringify(templateObject), {
170
- input: { ...inputs, ...extra },
171
- data: data.value || data,
172
- ctx: { factory: factoryAddress, id: numMinted + 1, owner, issuer: issuerObject },
173
- }));
174
- const template = cloneDeep(output);
175
- // prerender credentialSubjects if they exists
176
- // then populate their ids
177
- const prerenderKeys = findPrerenderKeys(template, 'credentialSubject');
178
- if (prerenderKeys.length) {
179
- extra.issuanceDate = new Date().toISOString();
180
- for (const key of prerenderKeys) {
181
- const subjectTemplate = get(template, key);
182
- const subjectObject = Array.isArray(subjectTemplate)
183
- ? subjectTemplate.map((x) => render(x))
184
- : render(subjectTemplate);
185
- set(template, key, subjectObject);
186
- // calculate credential id from credentialSubject
187
- const vcRootPath = key.split('.').slice(0, -1).join('.');
188
- const vcIdPath = vcRootPath.split('.').concat(['id']).join('.');
189
- const typeInfo = toTypeInfo(issuerObject.id);
190
- const vcType = { ...typeInfo, role: types.RoleType.ROLE_VC };
191
- const vcId = fromPublicKeyHash(wallet.hash(stableStringify(subjectObject)), vcType);
192
- extra.id = vcId;
193
- extra.proofType = proofTypes[typeInfo.pk];
194
- // technically we do not support nested vc when minting
195
- // But it is possible to support multiple credentialSubjects when minting
196
- set(template, vcIdPath, vcId);
197
- // Generate proof signatures
198
- if (!proofTypes[typeInfo.pk]) {
199
- throw new Error('Unsupported signer type when create verifiable credential');
200
- }
201
- let vcObj = render(get(template, vcRootPath));
202
- delete vcObj.proof;
203
- const vcStr = stableStringify(vcObj);
204
- // eslint-disable-next-line no-await-in-loop
205
- const signature = toBase64(await wallet.sign(vcStr));
206
- vcObj.proof = {
207
- type: proofTypes[typeInfo.pk],
208
- created: extra.issuanceDate,
209
- proofPurpose: 'assertionMethod',
210
- jws: signature,
211
- };
212
- extra.signature = signature;
213
- try {
214
- // Simulate minting from start, so that we can ensure the validity of minted asset
215
- asset = render(cloneDeep(output));
216
- vcObj = get(asset, vcRootPath);
217
- debug('preMintFromFactory.result', JSON.stringify(asset, null, 2));
218
- // eslint-disable-next-line no-await-in-loop
219
- await verify({ vc: vcObj, trustedIssuers: [issuerObject.id], ownerDid: owner, ignoreExpired: true });
220
- }
221
- catch (err) {
222
- console.error(err);
223
- throw new Error('Failed to mint asset from factory: invalid verifiable credential minted');
224
- }
225
- }
226
- }
227
- else {
228
- // populate other variables into the whole output
229
- asset = render(template);
230
- debug('preMintFromFactory.result', JSON.stringify(asset, null, 2));
231
- }
232
- // calculate address
233
- const address = toAssetAddress(asset);
234
- // return extra inputs
235
- return { address, issuer: issuerObject, variables: { ...inputs, ...extra }, asset };
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
+ let asset = null;
141
+ const { output, numMinted, address: factoryAddress, data } = factory;
142
+ const { wallet, name } = issuer;
143
+ debug("preMintFromFactory.args", JSON.stringify({
144
+ output,
145
+ factoryAddress,
146
+ numMinted,
147
+ inputs,
148
+ owner,
149
+ issuer,
150
+ data
151
+ }, null, 2));
152
+ const extra = {};
153
+ const issuerObject = {
154
+ id: wallet.address,
155
+ pk: toBase58(wallet.publicKey),
156
+ name
157
+ };
158
+ const render = (templateObject) => JSON.parse(mustache.render(JSON.stringify(templateObject), {
159
+ input: {
160
+ ...inputs,
161
+ ...extra
162
+ },
163
+ data: data.value || data,
164
+ ctx: {
165
+ factory: factoryAddress,
166
+ id: numMinted + 1,
167
+ owner,
168
+ issuer: issuerObject
169
+ }
170
+ }));
171
+ const template = cloneDeep(output);
172
+ const prerenderKeys = findPrerenderKeys(template, "credentialSubject");
173
+ if (prerenderKeys.length) {
174
+ extra.issuanceDate = (/* @__PURE__ */ new Date()).toISOString();
175
+ for (const key of prerenderKeys) {
176
+ const subjectTemplate = get(template, key);
177
+ const subjectObject = Array.isArray(subjectTemplate) ? subjectTemplate.map((x) => render(x)) : render(subjectTemplate);
178
+ set(template, key, subjectObject);
179
+ const vcRootPath = key.split(".").slice(0, -1).join(".");
180
+ const vcIdPath = vcRootPath.split(".").concat(["id"]).join(".");
181
+ const typeInfo = toTypeInfo(issuerObject.id);
182
+ const vcType = {
183
+ ...typeInfo,
184
+ role: types.RoleType.ROLE_VC
185
+ };
186
+ const vcId = fromPublicKeyHash(wallet.hash(stableStringify(subjectObject)), vcType);
187
+ extra.id = vcId;
188
+ extra.proofType = proofTypes[typeInfo.pk];
189
+ set(template, vcIdPath, vcId);
190
+ if (!proofTypes[typeInfo.pk]) throw new Error("Unsupported signer type when create verifiable credential");
191
+ let vcObj = render(get(template, vcRootPath));
192
+ delete vcObj.proof;
193
+ const vcStr = stableStringify(vcObj);
194
+ const signature = toBase64(await wallet.sign(vcStr));
195
+ vcObj.proof = {
196
+ type: proofTypes[typeInfo.pk],
197
+ created: extra.issuanceDate,
198
+ proofPurpose: "assertionMethod",
199
+ jws: signature
200
+ };
201
+ extra.signature = signature;
202
+ try {
203
+ asset = render(cloneDeep(output));
204
+ vcObj = get(asset, vcRootPath);
205
+ debug("preMintFromFactory.result", JSON.stringify(asset, null, 2));
206
+ await verify({
207
+ vc: vcObj,
208
+ trustedIssuers: [issuerObject.id],
209
+ ownerDid: owner,
210
+ ignoreExpired: true
211
+ });
212
+ } catch (err) {
213
+ console.error(err);
214
+ throw new Error("Failed to mint asset from factory: invalid verifiable credential minted");
215
+ }
216
+ }
217
+ } else {
218
+ asset = render(template);
219
+ debug("preMintFromFactory.result", JSON.stringify(asset, null, 2));
220
+ }
221
+ return {
222
+ address: toAssetAddress(asset),
223
+ issuer: issuerObject,
224
+ variables: {
225
+ ...inputs,
226
+ ...extra
227
+ },
228
+ asset
229
+ };
236
230
  };
237
- export const formatFactoryState = (state) => {
238
- const { address, output, data, numMinted } = state;
239
- const outputX = cloneDeep(output);
240
- outputX.data.value = JSON.parse(outputX.data.value);
241
- outputX.data.type = outputX.data.typeUrl;
242
- return {
243
- address,
244
- output: outputX,
245
- data: data.value ? JSON.parse(data.value) : {},
246
- numMinted,
247
- };
231
+ const formatFactoryState = (state) => {
232
+ const { address, output, data, numMinted } = state;
233
+ const outputX = cloneDeep(output);
234
+ outputX.data.value = JSON.parse(outputX.data.value);
235
+ outputX.data.type = outputX.data.typeUrl;
236
+ return {
237
+ address,
238
+ output: outputX,
239
+ data: data.value ? JSON.parse(data.value) : {},
240
+ numMinted
241
+ };
248
242
  };
243
+
244
+ //#endregion
245
+ export { findPrerenderKeys, formatFactoryState, isValidFactory, isValidHook, isValidNotation, mintFromFactory, preMintFromFactory };
@@ -0,0 +1,6 @@
1
+ declare module 'lodash/cloneDeep';
2
+ declare module 'lodash/get';
3
+ declare module 'lodash/isEmpty';
4
+ declare module 'lodash/set';
5
+ declare module 'lodash/uniq';
6
+ declare module 'lodash/uniqBy';
@@ -0,0 +1,29 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+
29
+ exports.__toESM = __toESM;