storacha-network / w3up

⁂ w3up protocol implementation
https://github.com/storacha-network/specs
Other
54 stars 19 forks source link

feat: utility exports for better UX #1505

Closed alanshaw closed 2 months ago

alanshaw commented 2 months ago

This PR re-exports some ucanto exports and a utility function to parse a proof (in any current or legacy format). This should make working with the client easier as all the things you need are available (no additional deps to install), makes the docs much more succinct and easier to follow, and actually allows you to import a base64 encoded delegation successfully from any period in time you obtained it.

Here's one of many code snippets from the docs site that will be improved by this PR:

Before

import * as Client from '@web3-storage/w3up-client'
import { StoreMemory } from '@web3-storage/w3up-client/stores/memory'
import { importDAG } from '@ucanto/core/delegation'
import { CarReader } from '@ipld/car'
import * as Signer from '@ucanto/principal/ed25519'

async function main () {
  // Load client with specific private key
  const principal = Signer.parse(process.env.KEY)
  const store = new StoreMemory()
  const client = await Client.create({ principal, store })
  // Add proof that this agent has been delegated capabilities on the space
  const proof = await parseProof(process.env.PROOF)
  const space = await client.addSpace(proof)
  await client.setCurrentSpace(space.did())
  // READY to go!
}

/** @param {string} data Base64 encoded CAR file */
async function parseProof (data) {
  const blocks = []
  const reader = await CarReader.fromBytes(Buffer.from(data, 'base64'))
  for await (const block of reader.blocks()) {
    blocks.push(block)
  }
  return importDAG(blocks)
}

After

import * as Client from '@web3-storage/w3up-client'
import { Signer } from '@web3-storage/w3up-client/principal/ed25519'
import { StoreMemory } from '@web3-storage/w3up-client/stores/memory'
import * as Proof from '@web3-storage/w3up-client/proof'

async function main () {
  // Load client with specific private key
  const principal = Signer.parse(process.env.KEY)
  const store = new StoreMemory()
  const client = await Client.create({ principal, store })
  // Add proof that this agent has been delegated capabilities on the space
  const proof = await Proof.parse(process.env.PROOF)
  const space = await client.addSpace(proof)
  await client.setCurrentSpace(space.did())
  // READY to go!
}