UNPKG

@funded-labs/dab-js

Version:
150 lines (149 loc) 7.84 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const agent_1 = require("@dfinity/agent"); const dip_721_did_1 = __importDefault(require("../../idls/dip_721.did")); const default_1 = __importDefault(require("./default")); const standards_1 = require("../../constants/standards"); const extractMetadataValue = (metadata) => { const metadataKey = Object.keys(metadata)[0]; const value = metadata[metadataKey]; return typeof value === 'object' ? JSON.stringify(value) : value; }; const deprecationWarningForDip721LegacyRequests = ({ methodName, }) => `Oops! An attempt to ${methodName} failed, a fallback to legacy will be used. Legacy DIP721 contract support will be dropped soon, the contract should be updated`; class ERC721 extends default_1.default { constructor(canisterId, agent, blsVerify) { super(canisterId, agent); this.standard = standards_1.NFT.dip721; this.actor = agent_1.Actor.createActor(dip_721_did_1.default, { agent, canisterId, blsVerify, }); } backwardsCompatibleGuard(legacyMethod, newMethod) { return (params = []) => __awaiter(this, void 0, void 0, function* () { let res; try { res = yield this.actor[newMethod](...params); } catch (err) { deprecationWarningForDip721LegacyRequests({ methodName: newMethod, }); res = yield this.actor[legacyMethod](...params); } return res; }); } getUserTokens(principal) { return __awaiter(this, void 0, void 0, function* () { const guardedGetUserTokens = this.backwardsCompatibleGuard('ownerTokenMetadata', 'dip721_owner_token_metadata'); const userTokensResult = yield guardedGetUserTokens([principal]); const tokens = userTokensResult['Ok'] || []; if (!tokens.length) return []; const formattedTokenData = tokens .map((token) => { var _a, _b; const tokenIndex = token.token_identifier; const formatedMetadata = this.formatMetadata(token); if (!formatedMetadata) return; const operator = (_b = (_a = token.operator) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toText(); return this.serializeTokenData(formatedMetadata, tokenIndex, principal.toText(), operator); }) .filter((token) => token); return formattedTokenData; }); } transfer(to, tokenIndex) { return __awaiter(this, void 0, void 0, function* () { const guardedTransfer = this.backwardsCompatibleGuard('transfer', 'dip721_transfer'); const transferResult = yield guardedTransfer([to, BigInt(tokenIndex)]); if ('Err' in transferResult) throw new Error(`${Object.keys(transferResult.Err)[0]}: ${Object.values(transferResult.Err)[0]}`); }); } details(tokenIndex) { var _a, _b, _c, _d, _e, _f; return __awaiter(this, void 0, void 0, function* () { const guardedDetails = this.backwardsCompatibleGuard('tokenMetadata', 'dip721_token_metadata'); const metadataResult = yield guardedDetails([BigInt(tokenIndex)]); if ('Err' in metadataResult) throw new Error(`${Object.keys(metadataResult.Err)[0]}: ${Object.values(metadataResult.Err)[0]}`); const metadata = metadataResult === null || metadataResult === void 0 ? void 0 : metadataResult.Ok; const formatedMetadata = this.formatMetadata(metadata); const owner = (_c = (_b = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.owner) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toText) === null || _c === void 0 ? void 0 : _c.call(_b); const operator = (_f = (_e = (_d = metadata === null || metadata === void 0 ? void 0 : metadata.operator) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.toText) === null || _f === void 0 ? void 0 : _f.call(_e); return this.serializeTokenData(formatedMetadata, tokenIndex, owner, operator); }); } getMetadata() { var _a; return __awaiter(this, void 0, void 0, function* () { const guardedGetMetadata = this.backwardsCompatibleGuard('metadata', 'dip721_get_metadata'); const metadata = yield guardedGetMetadata(); return { icon: metadata === null || metadata === void 0 ? void 0 : metadata.logo[0], name: ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.name) === null || _a === void 0 ? void 0 : _a[0]) || '', standard: this.standard, canisterId: this.canisterId, tokens: [], description: '', }; }); } serializeTokenData(metadata, tokenIndex, owner, operator) { var _a, _b; return { index: BigInt(tokenIndex), canister: this.canisterId, metadata, owner, url: ((_b = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.location) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.TextContent) || '', standard: this.standard, operator, }; } formatMetadata(metadata) { const metadataResult = { properties: new Array() }; if (!(metadata === null || metadata === void 0 ? void 0 : metadata.properties) || !Array.isArray(metadata.properties)) { console.warn(`Oops! Failed to format the metadata properties for token, field is missing or invalid. See ${JSON.stringify(metadata)}`); console.log(metadata); return; } metadata.properties.forEach((prop) => { const propertyName = prop[0]; metadataResult[propertyName] = { value: prop[1] }; const value = (() => { try { return extractMetadataValue(prop[1]); } catch (err) { console.warn(`Oops! Failed to extract metadata value for property ${propertyName}, is that a valid key value pair?`); console.error(err); } })(); metadataResult.properties = [ ...metadataResult.properties, { name: prop[0], value }, ]; }); // Filter out reserved props from the unique traits metadataResult.properties = metadataResult.properties.filter(({ name }) => !['location', 'thumbnail', 'contentHash', 'contentType'].includes(name)); return metadataResult; } } exports.default = ERC721;