/**
* One Charter attestation builder (Kognai seat SEAT10).
* Hashes the Charter, the Constitution and the SOUL texts (sha256 of their exact UTF 8 bytes), takes their IPFS ids,
* and outputs one EAS attestation payload for one schema, the same schema the Charter attestation verifier reads:
* string version,string date,string[] names,bytes32[] digests,string[] cids
* Pure and synchronous: no network, no key, no clock.
*/
import { createHash } from 'node:crypto';
import { encodeAbiParameters, encodePacked, keccak256, parseAbiParameters } from 'viem';
export const CHARTER_SCHEMA = 'string version,string date,string[] names,bytes32[] digests,string[] cids';
export const TEXT_NAMES = ['charter', 'constitution', 'soul'] as const;
export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
export const ZERO_UID = '0x' + '0'.repeat(64);
export type Text = string | Uint8Array;
export type Texts = Text[] | Record<string, Text>;
export type Cids = string[] | Record<string, string>;
export interface BuildInput { texts: Texts; cids: Cids; version: string; date: string; resolver?: string; revocable?: boolean }
export interface Attestation {
/** the EAS schema string, stable */
schema: string;
/** EAS schema UID: keccak256(abi.encodePacked(schema, resolver, revocable)) */
schemaUid: `0x${string}`;
/** ABI encoded attestation data for the schema */
data: `0x${string}`;
/** sha256 of each text as 0x and 64 lowercase hex, in the shape of the input (array in, array out; object in, object out) */
digests: string[] | Record<string, string>;
names: string[];
cids: string[];
version: string;
date: string;
/** ready for EAS attest({ schema, data }) */
request: { schema: `0x${string}`; data: { recipient: string; expirationTime: bigint; revocable: boolean; refUID: string; data: `0x${string}`; value: bigint } };
}
const CID_V0 = /^Qm[1-9A-HJ-NP-Za-km-z]{44}$/;
const CID_V1 = /^b[a-z2-7]{58,}$/;
const NAME = /^[a-z][a-z0-9_-]{0,31}$/;
export const isCid = (s: unknown): s is string => typeof s === 'string' && (CID_V0.test(s) || CID_V1.test(s));
export function sha256Hex(text: Text): string {
return '0x' + createHash('sha256').update(typeof text === 'string' ? Buffer.from(text, 'utf8') : text).digest('hex');
}
/** Names in a stable order: charter, constitution, soul first, then any other name alphabetically. */
function orderNames(keys: string[]): string[] {
const known = TEXT_NAMES.filter((n) => keys.includes(n));
return [...known, ...keys.filter((k) => !(TEXT_NAMES as readonly string[]).includes(k)).sort()];
}
function entries(texts: Texts, cids: Cids): { names: string[]; list: Text[]; cidList: string[] } {
if (Array.isArray(texts)) {
if (!Array.isArray(cids)) throw new Error('texts and cids must both be arrays or both be objects');
if (texts.length !== TEXT_NAMES.length) throw new Error('an array of texts holds exactly the charter, constitution and soul texts, in that order');
if (cids.length !== texts.length) throw new Error('cids must have one id per text');
return { names: [...TEXT_NAMES], list: texts, cidList: cids };
}
if (!texts || typeof texts !== 'object' || !cids || typeof cids !== 'object' || Array.isArray(cids)) throw new Error('texts and cids must both be arrays or both be objects');
const keys = Object.keys(texts);
for (const n of TEXT_NAMES) if (!keys.includes(n)) throw new Error(`texts is missing the ${n} text`);
for (const k of keys) if (!NAME.test(k)) throw new Error(`text name ${JSON.stringify(k)} must be lowercase letters, digits, - or _`);
const ck = Object.keys(cids);
if (ck.length !== keys.length || !keys.every((k) => ck.includes(k))) throw new Error('cids must have exactly the same names as texts');
const names = orderNames(keys);
return { names, list: names.map((n) => texts[n]), cidList: names.map((n) => cids[n]) };
}
function validDate(s: unknown): s is string {
if (typeof s !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;
return new Date(s + 'T00:00:00Z').toISOString().slice(0, 10) === s;
}
export function schemaUid(schema: string, resolver: string = ZERO_ADDRESS, revocable = true): `0x${string}` {
return keccak256(encodePacked(['string', 'address', 'bool'], [schema, resolver as `0x${string}`, revocable]));
}
export function buildAttestation(input: BuildInput): Attestation {
const { texts, cids, version, date, resolver = ZERO_ADDRESS, revocable = true } = input ?? ({} as never);
const { names, list, cidList } = entries(texts, cids);
list.forEach((t, i) => {
if (typeof t !== 'string' && !(t instanceof Uint8Array)) throw new Error(`the ${names[i]} text must be a string or bytes`);
if (t.length === 0) throw new Error(`the ${names[i]} text is empty`);
});
cidList.forEach((c, i) => { if (!isCid(c)) throw new Error(`the ${names[i]} cid is not an IPFS id (CIDv0 Qm... or CIDv1 base32 b...)`); });
if (typeof version !== 'string' || !version.trim() || version.length > 64) throw new Error('version must be a non empty string of at most 64 characters');
if (!validDate(date)) throw new Error('date must be a calendar date YYYY-MM-DD');
if (typeof resolver !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(resolver)) throw new Error('resolver must be an address');
const list256 = list.map(sha256Hex);
const data = encodeAbiParameters(parseAbiParameters(CHARTER_SCHEMA), [version, date, names, list256 as `0x${string}`[], cidList]);
const uid = schemaUid(CHARTER_SCHEMA, resolver, revocable === true);
const digests = Array.isArray(texts) ? list256 : Object.fromEntries(names.map((n, i) => [n, list256[i]]));
return {
schema: CHARTER_SCHEMA, schemaUid: uid, data, digests, names, cids: cidList, version, date,
request: { schema: uid, data: { recipient: ZERO_ADDRESS, expirationTime: 0n, revocable: revocable === true, refUID: ZERO_UID, data, value: 0n } },
};
}
agentgate-source: code mirror on Cloudflare Pages. All repos