Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use UCAN tokens for NFT marketplace #779

Merged
merged 11 commits into from
Aug 23, 2022
89 changes: 89 additions & 0 deletions scripts/generateNftServiceKeypair.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { KeyPair } from 'ucan-storage/keypair';
import { build } from 'ucan-storage/ucan-storage';

const SERVICE_ENDPOINT = 'https://api.nft.storage'; // default
const API_TOKEN = process.env.API_KEY;
RustemYuzlibaev marked this conversation as resolved.
Show resolved Hide resolved

/**
* Obtaining the service DID
*
*/
async function getServiceDid() {
const didRes = await fetch(new URL('/did', SERVICE_ENDPOINT));
const { ok, value: serviceDid } = await didRes.json();

if (ok) {
return serviceDid;
} else {
throw new Error('Could not get Service DID');
}
}

/**
* Obtaining a root UCAN token.
* It will be valid for a duration of two weeks
*
*/
async function getRootToken(token) {
const ucanReq = await fetch(new URL('/ucan/token', SERVICE_ENDPOINT), {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
});

if (!ucanReq.ok) {
throw new Error('Failed to get root UCAN token');
}

const { value: rootUCAN } = await ucanReq.json();

return rootUCAN;
}

/**
* Obtaining UCAN token with specified expiration date (10 days)
*
*/
async function getUCAN(kp, serviceDid, rootUCAN) {
// convert timestamp to seconds
const nowInSeconds = Math.floor(Date.now() / 1000);
const expiration = nowInSeconds + 864000; // 10 days from now

try {
return await build({
issuer: kp,
audience: serviceDid,
expiration: expiration,
capabilities: [
{
with: `storage://${kp.did()}`,
can: 'upload/*',
},
],
proofs: [rootUCAN],
});
} catch (error) {
throw new Error('Could not create UCAN token:', error);
}
}

async function main() {
const pair = await KeyPair.create();
const privateKey = pair.export();

const kp = await KeyPair.fromExportedKey(privateKey);

const serviceDid = await getServiceDid();

const rootUCAN = await getRootToken(API_TOKEN);

const ucan = await getUCAN(kp, serviceDid, rootUCAN);

process.stdout.write(`{
RustemYuzlibaev marked this conversation as resolved.
Show resolved Hide resolved
marketplaceDid: ${kp.did()},
ucan: ${ucan}
}\n`);
}

main().catch((error) => console.error(error));