generated from PolymeshAssociation/typescript-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Assets.ts
364 lines (314 loc) · 8.85 KB
/
Assets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { PolymeshPrimitivesTicker } from '@polkadot/types/lookup';
import {
Context,
createAsset,
createNftCollection,
FungibleAsset,
Identity,
NftCollection,
PolymeshError,
reserveTicker,
TickerReservation,
} from '~/internal';
import {
Asset,
CreateAssetWithTickerParams,
CreateNftCollectionParams,
ErrorCode,
GlobalMetadataKey,
PaginationOptions,
ProcedureMethod,
ReserveTickerParams,
ResultSet,
SubCallback,
TickerReservationStatus,
UnsubCallback,
} from '~/types';
import {
bytesToString,
meshMetadataSpecToMetadataSpec,
stringToIdentityId,
tickerToString,
u64ToBigNumber,
} from '~/utils/conversion';
import {
asAsset,
assembleAssetQuery,
createProcedureMethod,
getDid,
isPrintableAscii,
requestPaginated,
} from '~/utils/internal';
/**
* Handles all Asset related functionality
*/
export class Assets {
private context: Context;
/**
* @hidden
*/
constructor(context: Context) {
this.context = context;
this.reserveTicker = createProcedureMethod(
{
getProcedureAndArgs: args => [reserveTicker, args],
},
context
);
this.createAsset = createProcedureMethod(
{
getProcedureAndArgs: args => [createAsset, { reservationRequired: false, ...args }],
},
context
);
this.createNftCollection = createProcedureMethod(
{
getProcedureAndArgs: args => [createNftCollection, args],
},
context
);
}
/**
* Reserve a ticker symbol under the ownership of the signing Identity to later use in the creation of an Asset.
* The ticker will expire after a set amount of time, after which other users can reserve it
*/
public reserveTicker: ProcedureMethod<ReserveTickerParams, TickerReservation>;
/**
* Create an Asset
*
* @note if ticker is already reserved, then required role:
* - Ticker Owner
*/
public createAsset: ProcedureMethod<CreateAssetWithTickerParams, FungibleAsset>;
/**
* Create an NftCollection
*
* @note if ticker is already reserved, then required role:
* - Ticker Owner
*/
public createNftCollection: ProcedureMethod<CreateNftCollectionParams, NftCollection>;
/**
* Check if a ticker hasn't been reserved
*
* @note can be subscribed to
*/
public isTickerAvailable(args: { ticker: string }): Promise<boolean>;
public isTickerAvailable(
args: { ticker: string },
callback: SubCallback<boolean>
): Promise<UnsubCallback>;
// eslint-disable-next-line require-jsdoc
public async isTickerAvailable(
args: { ticker: string },
callback?: SubCallback<boolean>
): Promise<boolean | UnsubCallback> {
const reservation = new TickerReservation(args, this.context);
if (callback) {
return reservation.details(({ status: reservationStatus }) => {
// eslint-disable-next-line n/no-callback-literal, @typescript-eslint/no-floating-promises -- callback errors should be handled by the caller
callback(reservationStatus === TickerReservationStatus.Free);
});
}
const { status } = await reservation.details();
return status === TickerReservationStatus.Free;
}
/**
* Retrieve all the ticker reservations currently owned by an Identity. This doesn't include Assets that
* have already been launched
*
* @param args.owner - defaults to the signing Identity
*
* @note reservations with unreadable characters in their tickers will be left out
*/
public async getTickerReservations(args?: {
owner: string | Identity;
}): Promise<TickerReservation[]> {
const {
context: {
polymeshApi: { query },
},
context,
} = this;
const did = await getDid(args?.owner, context);
const entries = await query.asset.assetOwnershipRelations.entries(
stringToIdentityId(did, context)
);
return entries.reduce<TickerReservation[]>((result, [key, relation]) => {
if (relation.isTickerOwned) {
const ticker = tickerToString(key.args[1]);
if (isPrintableAscii(ticker)) {
return [...result, new TickerReservation({ ticker }, context)];
}
}
return result;
}, []);
}
/**
* Retrieve a Ticker Reservation
*
* @param args.ticker - Asset ticker
*/
public getTickerReservation(args: { ticker: string }): TickerReservation {
const { ticker } = args;
const { context } = this;
return new TickerReservation({ ticker }, context);
}
/**
* Retrieve a FungibleAsset or NftCollection
*
* @note `getFungibleAsset` and `getNftCollection` are similar to this method, but return a more specific type
*/
public async getAsset(args: { ticker: string }): Promise<Asset> {
const { context } = this;
const { ticker } = args;
return asAsset(ticker, context);
}
/**
* Retrieve all of the Assets owned by an Identity
*
* @param args.owner - Identity representation or Identity ID as stored in the blockchain
*
* @note Assets with unreadable characters in their tickers will be left out
*/
public async getAssets(args?: { owner: string | Identity }): Promise<Asset[]> {
const {
context: {
polymeshApi: { query },
},
context,
} = this;
const did = await getDid(args?.owner, context);
const entries = await query.asset.assetOwnershipRelations.entries(
stringToIdentityId(did, context)
);
const ownedTickers: string[] = [];
const rawTickers: PolymeshPrimitivesTicker[] = [];
entries.forEach(([key, relation]) => {
if (relation.isAssetOwned) {
const rawTicker = key.args[1];
const ticker = tickerToString(rawTicker);
if (isPrintableAscii(ticker)) {
ownedTickers.push(ticker);
rawTickers.push(rawTicker);
}
}
});
const ownedDetails = await query.asset.tokens.multi(rawTickers);
return assembleAssetQuery(ownedDetails, ownedTickers, context);
}
/**
* Retrieve a FungibleAsset
*
* @param args.ticker - Asset ticker
*/
public async getFungibleAsset(args: { ticker: string }): Promise<FungibleAsset> {
const { ticker } = args;
const asset = new FungibleAsset({ ticker }, this.context);
const exists = await asset.exists();
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: `There is no Asset with ticker "${ticker}"`,
});
}
return asset;
}
/**
* Retrieve an NftCollection
*
* @param args.ticker - NftCollection ticker
*/
public async getNftCollection(args: { ticker: string }): Promise<NftCollection> {
const { ticker } = args;
const nftCollection = new NftCollection({ ticker }, this.context);
const exists = await nftCollection.exists();
if (!exists) {
throw new PolymeshError({
code: ErrorCode.DataUnavailable,
message: `There is no NftCollection with ticker "${ticker}"`,
});
}
return nftCollection;
}
/**
* Retrieve all the Assets on chain
*
* @note supports pagination
*/
public async get(paginationOpts?: PaginationOptions): Promise<ResultSet<Asset>> {
const {
context: {
polymeshApi: {
query: {
asset: { assetNames, tokens },
},
},
},
context,
} = this;
const { entries, lastKey: next } = await requestPaginated(assetNames, {
paginationOpts,
});
const tickers: string[] = [];
const rawTickers: PolymeshPrimitivesTicker[] = [];
entries.forEach(
([
{
args: [rawTicker],
},
]) => {
rawTickers.push(rawTicker);
tickers.push(tickerToString(rawTicker));
}
);
const details = await tokens.multi(rawTickers);
const data = assembleAssetQuery(details, tickers, context);
return {
data,
next,
};
}
/**
* Retrieve all the Asset Global Metadata on chain. This includes metadata id, name and specs
*/
public async getGlobalMetadataKeys(): Promise<GlobalMetadataKey[]> {
const {
context: {
polymeshApi: {
query: {
asset: { assetMetadataGlobalKeyToName, assetMetadataGlobalSpecs },
},
},
},
} = this;
const [keyToNameEntries, specsEntries] = await Promise.all([
assetMetadataGlobalKeyToName.entries(),
assetMetadataGlobalSpecs.entries(),
]);
const specsEntryMap = new Map(
specsEntries.map(
([
{
args: [rawKeyId],
},
rawSpecs,
]) => [rawKeyId.toString(), rawSpecs]
)
);
return keyToNameEntries.map(
([
{
args: [rawId],
},
rawName,
]) => {
const rawSpecs = specsEntryMap.get(rawId.toString());
return {
id: u64ToBigNumber(rawId),
name: bytesToString(rawName.unwrap()),
specs: meshMetadataSpecToMetadataSpec(rawSpecs),
};
}
);
}
}