Skip to content

Instantly share code, notes, and snippets.

@easrng
Created January 1, 2026 18:54
Show Gist options
  • Select an option

  • Save easrng/02379cef81077120d972c5c8d046ae36 to your computer and use it in GitHub Desktop.

Select an option

Save easrng/02379cef81077120d972c5c8d046ae36 to your computer and use it in GitHub Desktop.
import { fromBase32, toBase32 } from "npm:@atcute/multibase";
import * as TID from "npm:@atcute/tid";
import { Did, Tid } from "npm:@atcute/lexicons";
interface RecordRef {
did: Did;
tid: Tid;
}
function encode({ did, tid }: RecordRef): string {
const tidParsed = TID.parse(tid);
let header = (BigInt(tidParsed.timestamp) << 10n) | BigInt(tidParsed.clockid);
let didBytes: Uint8Array;
if (did.startsWith("did:plc:")) {
header |= 1n << 63n;
didBytes = fromBase32(did.slice(8));
} else {
didBytes = new TextEncoder().encode(did.slice(4));
}
const buffer = new Uint8Array(8 + didBytes.length);
const view = new DataView(buffer.buffer);
view.setBigUint64(0, header, false);
buffer.set(didBytes, 8);
return toBase32(buffer);
}
function decode(encoded: string): RecordRef {
const buffer = fromBase32(encoded);
const view = new DataView(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength,
);
const header = view.getBigUint64(0, false);
const isPlc = (header & (1n << 63n)) !== 0n;
const timestamp = Number((header >> 10n) & ((1n << 53n) - 1n));
const clockid = Number(header & 1023n);
const tid = TID.create(timestamp, clockid);
const payload = buffer.subarray(8);
let did: Did;
if (isPlc) {
did = `did:plc:${toBase32(payload)}`;
} else {
did = `did:${new TextDecoder().decode(payload)}`;
}
return { did, tid };
}
const plcIn: RecordRef = {
did: "did:plc:ttdrpj45ibqunmfhdsb4zdwq",
tid: "3m3yeflczwk23",
};
// Expected: ted4uxcr7zaadhghc6tz2qdbi2ykohedzshna
const encodedPlc = encode(plcIn);
const decodedPlc = decode(encodedPlc);
console.log(`Encoded: ${encodedPlc}`);
console.log(
`Match: ${decodedPlc.did === plcIn.did && decodedPlc.tid === plcIn.tid}`,
);
const webIn: RecordRef = {
did: "did:web:example.com",
tid: "3m3yeflczwk23",
};
// Expected: ded4uxcr7zaac53fmi5gk6dbnvygyzjomnxw2
const encodedWeb = encode(webIn);
const decodedWeb = decode(encodedWeb);
console.log(`Encoded: ${encodedWeb}`);
console.log(
`Match: ${decodedWeb.did === webIn.did && decodedWeb.tid === webIn.tid}`,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment