@originvault/ov-id-sdk
Version:
A TypeScript SDK for managing decentralized identities (DIDs) and verifiable credentials (VCs)
111 lines • 4.39 kB
JavaScript
import { v5 as uuidv5 } from 'uuid';
import { getVerifiedAuthentication, } from './storePrivateKeys.js';
import { CheqdNetwork } from '@cheqd/sdk';
import fs from 'fs';
import path from 'path';
import { getDIDKeys } from './identityManager.js';
import { co2 } from "@tgwf/co2";
let jsonFilePath;
let dirId;
const cleanUp = (collectionId) => {
if (jsonFilePath)
fs.unlinkSync(jsonFilePath);
if (collectionId) {
fs.rmdirSync(collectionId, { recursive: true });
}
};
export async function createResource({ did, name, version, provider, agent, keyStore, data, filePath, resourceId, resourceType }) {
if (!filePath && !data) {
throw new Error('Either filePath or data must be provided');
}
try {
const resolvedKeys = await getDIDKeys(did);
if (!resolvedKeys) {
console.log("Could not resolve DID", did);
return undefined;
}
const { keyName: id, kid: key } = resolvedKeys;
const verificationMethod = await getVerifiedAuthentication(id, agent);
// Extract the last part of the DID string to use as the collectionId
const collectionId = id.split(':').pop() || '';
dirId = collectionId;
const fileRelativePath = uuidv5(name, uuidv5.URL); // Use sanitized name
const resourceUUID = resourceId || uuidv5(fileRelativePath + new Date().toISOString(), uuidv5.URL);
const privateKey = await keyStore.getKey({ alias: key });
jsonFilePath = filePath ? filePath : generateResourceFile(collectionId, fileRelativePath, data);
// Check if the file exists before reading
if (!fs.existsSync(jsonFilePath)) {
throw new Error(`File not found: ${jsonFilePath}`);
}
const signInputs = [{
verificationMethodId: verificationMethod?.id || '',
keyType: 'Ed25519',
privateKeyHex: privateKey.privateKeyHex,
}];
const payload = {
collectionId,
id: resourceUUID,
name,
resourceType,
data: Buffer.from(fs.readFileSync(jsonFilePath)),
};
if (version) {
payload.version = version;
}
const options = {
kms: 'local',
network: CheqdNetwork.Mainnet,
payload,
signInputs,
file: jsonFilePath,
fee: {
amount: [{ denom: 'ncheq', amount: '2500000000' }],
gas: '2000000',
}
};
const params = {
options,
};
const co2Emission = new co2();
const co2EmissionResult = co2Emission.perByte(JSON.stringify(params).length, false);
console.log(`🌱 ${name}@${version} - Resource size in carbon grams: ${co2EmissionResult.toFixed(5)}g`);
try {
const result = await provider.createResource(params, { agent });
!filePath && cleanUp(dirId);
if (result) {
// Return the link to the cheqd resolver
return `https://resolver.originvault.box/1.0/identifiers/${did}/resources/${resourceUUID}`;
}
return undefined;
}
catch (error) {
!filePath && cleanUp(dirId);
throw `Error creating resource: ${error}`;
}
}
catch (error) {
console.error("Check data formatting and RPC endpoint connection. Error creating resource:", error);
!filePath && cleanUp(dirId);
return undefined;
}
}
export function generateResourceFile(dirPath, filePath, data) {
const jsonFilePath = path.resolve(dirPath, filePath);
// Ensure the directory exists before writing the file
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
// Convert data to JSON and write to file
fs.writeFileSync(jsonFilePath, JSON.stringify(data, null, 2));
// Check if the file was created successfully
if (!fs.existsSync(jsonFilePath)) {
throw new Error(`File generation failed: ${jsonFilePath}`);
}
console.log(`File generated at: ${jsonFilePath}`);
return jsonFilePath;
}
export async function getResources({ did, agent }) {
const resolvedDid = await agent.resolveDid({ didUrl: did });
console.log('DID', resolvedDid);
}
//# sourceMappingURL=resourceManager.js.map