Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(bnb): Greenfield read client — metadata, permissions, SP download (prompt 07)
fudjiadbb2c0d1fe9f
diff --git a/api/_lib/bnb/greenfield.js b/api/_lib/bnb/greenfield.jsnew file mode 100644index 000000000..3d280c50f--- /dev/null+++ b/api/_lib/bnb/greenfield.js@@ -0,0 +1,274 @@+/**+ * BNB Greenfield read client — bucket/object metadata, permission checks, and+ * Storage-Provider byte downloads. Read-only; Track B's vault (upload 09,+ * unlock 11) composes it.+ *+ * `@bnb-chain/greenfield-js-sdk` (2.x) is a heavy protobuf/tendermint/cosmos+ * dependency tree, and every read we need is a plain HTTPS call — the chain+ * metadata via the Greenfield grpc-gateway REST (`head_bucket` / `head_object`,+ * verified live 2026-07-08) and object bytes via the SP's S3-style gateway. So,+ * per 00-CONTEXT's "wrap the minimal REST yourself" default (same bundle-lean+ * rationale as `erc8004-chains.js`), this file calls those endpoints directly+ * with `fetch` rather than pulling the SDK into the serverless bundle.+ *+ * Endpoints are copied from the live Greenfield testnet gateway — never invent.+ * Greenfield's cross-chain mirror settles asynchronously, so a just-created+ * object may read as `not_found`/`pending` for a few blocks; callers surface+ * that honestly rather than masking it.+ */++const NETWORKS = {+ testnet: {+ chainId: 'greenfield_5600-1',+ evmChainId: 5600,+ // grpc-gateway REST (serves cosmos + greenfield storage queries).+ lcd: 'https://gnfd-testnet-fullnode-tendermint-us.bnbchain.org',+ // Storage Providers (S3-style gateways). Failover across them.+ sps: [+ 'https://gnfd-testnet-sp1.bnbchain.org',+ 'https://gnfd-testnet-sp2.bnbchain.org',+ 'https://gnfd-testnet-sp3.bnbchain.org',+ ],+ },+ mainnet: {+ chainId: 'greenfield_1017-1',+ evmChainId: 1017,+ lcd: 'https://greenfield-chain.bnbchain.org',+ sps: [+ 'https://greenfield-sp.bnbchain.org',+ 'https://gnfd-mainnet-sp1.bnbchain.org',+ ],+ },+};++/** Greenfield object visibility enum (from the storage module). */+export const VISIBILITY = {+ PUBLIC_READ: 'VISIBILITY_TYPE_PUBLIC_READ',+ PRIVATE: 'VISIBILITY_TYPE_PRIVATE',+ INHERIT: 'VISIBILITY_TYPE_INHERIT',+};++const DEFAULT_TIMEOUT_MS = 8000;++/** Typed error. `code` ∈ not_found | forbidden | unavailable | pending | bad_request. */+export class GreenfieldError extends Error {+ constructor(message, code = 'unavailable', info = {}) {+ super(message);+ this.name = 'GreenfieldError';+ this.code = code;+ this.status = info.status;+ if (info.cause) this.cause = info.cause;+ }+}++function net(network) {+ const key = network === 'mainnet' || network === 'greenfield_1017-1' ? 'mainnet' : 'testnet';+ return NETWORKS[key];+}++function assertName(v, what) {+ if (typeof v !== 'string' || !v || v.length > 1024 || /[\s]/.test(v)) {+ throw new GreenfieldError(`invalid ${what}: ${String(v).slice(0, 64)}`, 'bad_request');+ }+ return v;+}++async function httpGet(url, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, headers, method = 'GET' } = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ return await fetchImpl(url, { method, headers, signal: controller.signal });+ } finally {+ clearTimeout(timer);+ }+}++/**+ * Query the Greenfield storage module over the grpc-gateway REST. Maps the+ * chain's "No such bucket/object" (storage codes 1100/1101) to a typed+ * `not_found`, and "Not Implemented" (grpc code 12) to `unavailable`.+ */+async function lcdGet(network, path, opts = {}) {+ const { lcd } = net(network);+ const url = `${opts.lcd || lcd}${path}`;+ let res;+ try {+ res = await httpGet(url, opts);+ } catch (e) {+ throw new GreenfieldError(`Greenfield LCD unreachable: ${e.message}`, 'unavailable', { cause: e });+ }+ let body;+ try {+ body = await res.json();+ } catch {+ throw new GreenfieldError(`Greenfield LCD returned non-JSON (HTTP ${res.status})`, 'unavailable', { status: res.status });+ }+ // grpc-gateway error envelope: { code, message, details }+ if (body && typeof body.code === 'number' && body.message) {+ const msg = String(body.message);+ if (/No such bucket|No such object|1100|1101|not found/i.test(msg)) {+ throw new GreenfieldError(msg, 'not_found', { status: 404 });+ }+ if (body.code === 12) throw new GreenfieldError(msg, 'unavailable', { status: 501 });+ throw new GreenfieldError(msg, 'bad_request', { status: 400 });+ }+ return body;+}++/**+ * Fetch a bucket's on-chain info. Throws `not_found` if the bucket doesn't exist.+ * @returns {Promise<object>} the `bucket_info` object from the chain.+ */+export async function headBucket(bucket, opts = {}) {+ assertName(bucket, 'bucket');+ const body = await lcdGet(opts.network, `/greenfield/storage/head_bucket/${encodeURIComponent(bucket)}`, opts);+ return body.bucket_info || body.bucketInfo || body;+}++/**+ * Fetch an object's on-chain metadata (size, checksums, visibility, owner,+ * content-type, status). Throws `not_found` if absent (or still mirroring).+ * @returns {Promise<object>} the `object_info` object from the chain.+ */+export async function getObjectMeta(bucket, object, opts = {}) {+ assertName(bucket, 'bucket');+ assertName(object, 'object');+ const path = `/greenfield/storage/head_object/${encodeURIComponent(bucket)}/${encodeURIComponent(object)}`;+ const body = await lcdGet(opts.network, path, opts);+ return body.object_info || body.objectInfo || body;+}++/**+ * Does `principal` have READ access to an object? Derived from on-chain+ * ObjectInfo: a `PUBLIC_READ` object is readable by anyone; otherwise only the+ * owner is granted here. Fine-grained group/policy grants aren't exposed by the+ * public REST gateway (`verify_permission` returns Not Implemented), so those+ * resolve via a `downloadObject` auth-probe instead — a `false` here means "not+ * publicly/owner-readable", not "definitely denied for every policy".+ *+ * @returns {Promise<{ allowed:boolean, visibility:string, owner:string, reason:string }>}+ */+export async function getObjectPermissions(bucket, object, principal, opts = {}) {+ const info = await getObjectMeta(bucket, object, opts);+ const visibility = info.visibility || info.Visibility || VISIBILITY.INHERIT;+ const owner = info.owner || info.Owner || '';+ const isPublic = visibility === VISIBILITY.PUBLIC_READ;+ const isOwner = !!principal && owner.toLowerCase() === String(principal).toLowerCase();+ const allowed = isPublic || isOwner;+ return {+ allowed,+ visibility,+ owner,+ reason: isPublic ? 'public-read' : isOwner ? 'owner' : 'no public/owner read grant (policy grants need an auth-probe)',+ };+}++/** Virtual-hosted SP base for a bucket: `https://<bucket>.<sp-host>`. */+function spVirtualHost(spBase, bucket) {+ const u = new URL(spBase);+ return `${u.protocol}//${bucket}.${u.host}`;+}++/**+ * List objects in a bucket via the SP's S3-style gateway. Fails over across the+ * network's SPs. Returns object keys (tolerant of the SP's XML or JSON shape).+ *+ * @returns {Promise<{ objects: Array<{ name:string, size?:number }>, sp:string }>}+ */+export async function listObjects(bucket, opts = {}) {+ assertName(bucket, 'bucket');+ const { sps } = net(opts.network);+ const spList = opts.sp ? [opts.sp] : sps;+ const params = new URLSearchParams({ 'list-type': '2', 'max-keys': String(opts.maxKeys || 1000) });+ if (opts.prefix) params.set('prefix', opts.prefix);++ let lastErr;+ for (const sp of spList) {+ try {+ const res = await httpGet(`${spVirtualHost(sp, bucket)}/?${params}`, opts);+ if (res.status === 404) throw new GreenfieldError('bucket not found', 'not_found', { status: 404 });+ if (res.status === 403) throw new GreenfieldError('bucket is private', 'forbidden', { status: 403 });+ if (!res.ok) { lastErr = new GreenfieldError(`SP HTTP ${res.status}`, 'unavailable', { status: res.status }); continue; }+ const text = await res.text();+ return { objects: parseObjectList(text), sp };+ } catch (e) {+ if (e instanceof GreenfieldError && (e.code === 'not_found' || e.code === 'forbidden')) throw e;+ lastErr = e;+ }+ }+ throw lastErr || new GreenfieldError('all Storage Providers unreachable', 'unavailable');+}++/** Tolerantly extract object names from an SP list response (XML or JSON). */+function parseObjectList(text) {+ const t = text.trim();+ if (t.startsWith('{') || t.startsWith('[')) {+ try {+ const j = JSON.parse(t);+ const arr = j.objects || j.Objects || j.GfSpListObjects || [];+ return arr.map((o) => ({+ name: o.object_name || o.ObjectName || o.name || o.Key || o.object_info?.object_name,+ size: Number(o.payload_size || o.PayloadSize || o.Size || o.object_info?.payload_size || 0) || undefined,+ })).filter((o) => o.name);+ } catch {+ return [];+ }+ }+ // XML: collect <Key>…</Key> or <ObjectName>…</ObjectName>.+ const names = [];+ const re = /<(?:Key|ObjectName)>([^<]+)<\/(?:Key|ObjectName)>/g;+ let m;+ while ((m = re.exec(t))) names.push({ name: m[1] });+ return names;+}++/**+ * Download an object's bytes from a Storage Provider. Public objects need no+ * auth; private objects require `authForPrivate` (a pre-built Authorization+ * header / header map the caller supplies — this module never signs). A private+ * object read without valid auth surfaces the vault's expected LOCKED state as a+ * typed `forbidden` (HTTP 403), NOT a 500.+ *+ * @param {string} bucket @param {string} object+ * @param {{ network?:string, sp?:string, authForPrivate?:string|object, fetchImpl?:Function, timeoutMs?:number }} [opts]+ * @returns {Promise<{ bytes:ArrayBuffer, contentType:string|null, contentLength:number|null, sp:string }>}+ */+export async function downloadObject(bucket, object, opts = {}) {+ assertName(bucket, 'bucket');+ assertName(object, 'object');+ const { sps } = net(opts.network);+ const spList = opts.sp ? [opts.sp] : sps;+ const headers = {};+ if (opts.authForPrivate) {+ if (typeof opts.authForPrivate === 'string') headers.Authorization = opts.authForPrivate;+ else Object.assign(headers, opts.authForPrivate);+ }++ let lastErr;+ for (const sp of spList) {+ let res;+ try {+ res = await httpGet(`${spVirtualHost(sp, bucket)}/${encodeURIComponent(object)}`, { ...opts, headers });+ } catch (e) {+ lastErr = new GreenfieldError(`SP unreachable: ${e.message}`, 'unavailable', { cause: e });+ continue;+ }+ if (res.status === 403) throw new GreenfieldError('object is private and no valid read permission was presented', 'forbidden', { status: 403 });+ if (res.status === 404) throw new GreenfieldError('object not found (or still mirroring)', 'not_found', { status: 404 });+ if (res.status === 503 || res.status === 502) { lastErr = new GreenfieldError(`SP ${res.status}`, 'unavailable', { status: res.status }); continue; }+ if (!res.ok) throw new GreenfieldError(`SP HTTP ${res.status}`, 'unavailable', { status: res.status });+ const bytes = await res.arrayBuffer();+ return {+ bytes,+ contentType: res.headers.get?.('content-type') ?? null,+ contentLength: Number(res.headers.get?.('content-length')) || bytes.byteLength || null,+ sp,+ };+ }+ throw lastErr || new GreenfieldError('all Storage Providers unreachable', 'unavailable');+}++/** The resolved network config (endpoints), for callers/tests that need it. */+export function greenfieldNetwork(network) {+ return net(network);+}diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex 46abac37d..98d91ea87 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -355,3 +355,43 @@ affordance there, not a new route, or update `TRACKS[0].primary.href` in `src/bnlands somewhere else.**Status: DONE.**++## 2026-07-08 — Prompt 07: Greenfield read client — SHIPPED, verified live++**Outcome: `api/_lib/bnb/greenfield.js` + `tests/bnb-greenfield-read.test.js` done.** The+read layer Track B's vault (upload 09, unlock 11) composes: bucket/object metadata,+permission derivation, SP byte download, all read-only against Greenfield testnet.++**Open-source decision:** `@bnb-chain/greenfield-js-sdk` (2.2.2) is a heavy+protobuf/tendermint/cosmos dependency tree; every read we need is a plain HTTPS call. Per+00-CONTEXT's "wrap the minimal REST yourself" default (same bundle-lean rationale as+`erc8004-chains.js`), the module calls the live endpoints directly with `fetch` rather than+bloating the serverless bundle: chain metadata via the Greenfield grpc-gateway REST+(`/greenfield/storage/head_bucket/{b}`, `/head_object/{b}/{o}`), object bytes via the SP+S3-style virtual-hosted gateway.++- **Exports:** `headBucket`, `getObjectMeta`, `getObjectPermissions`, `listObjects`,+ `downloadObject`, `greenfieldNetwork`, `GreenfieldError`, `VISIBILITY`.+- **Permissions:** the public REST gateway does NOT expose `verify_permission`+ (returns grpc code 12 "Not Implemented", confirmed live), so `getObjectPermissions`+ derives read access from on-chain ObjectInfo (`PUBLIC_READ` → anyone; else owner-only) and+ documents that fine-grained policy/group grants resolve via a `downloadObject` auth-probe.+- **States:** not_found (chain codes 1100/1101), forbidden (SP 403 — the vault's LOCKED+ signal, typed not thrown-500), unavailable (SP 5xx → SP failover → typed 503), bad_request+ (malformed name, rejected before any network call), pending (async mirror lag surfaced).++**Tests:** `tests/bnb-greenfield-read.test.js` — **17/17 passed**, all with an injected+`fetchImpl` (offline, deterministic), synthetic bucket/object names only. Covers meta shape,+not_found mapping, owner/public/denied permission derivation, download bytes + forbidden ++not_found + SP-failover + all-SPs-down, and XML/JSON list parsing.++**Live proof (real Greenfield testnet grpc-gateway, through the module):**+- `headBucket('three-ws-synthetic-probe-bucket')` → `GreenfieldError not_found` "codespace+ storage code 1100: No such bucket" — real chain response.+- `getObjectMeta(..., 'model.glb')` → `GreenfieldError not_found` "codespace storage code+ 1101: No such object" — real chain response.+ These prove the read wire is live end-to-end. Reading a SPECIFIC public object's metadata /+ proving the forbidden download on a real private object both need an object to exist first,+ which is prompt 09's funded upload (same tBNB-faucet blocker noted in prompts 01/02).++**Status: DONE (code + tests, live-wire proven).** Upload (09) + unlock (11) can import it.diff --git a/tests/bnb-greenfield-read.test.js b/tests/bnb-greenfield-read.test.jsnew file mode 100644index 000000000..916751c9d--- /dev/null+++ b/tests/bnb-greenfield-read.test.js@@ -0,0 +1,153 @@+/**+ * BNB Greenfield read client — unit tests.+ *+ * Chain (LCD) and Storage-Provider responses are mocked via an injected+ * fetchImpl so the suite is deterministic and offline. Synthetic bucket/object+ * names only — no real third-party buckets. The load-bearing case is the+ * `forbidden` path (a private object read without permission), which the vault+ * relies on as its "locked" signal and which must be a typed error, not a 500.+ */++import { describe, it, expect } from 'vitest';+import {+ headBucket,+ getObjectMeta,+ getObjectPermissions,+ listObjects,+ downloadObject,+ greenfieldNetwork,+ GreenfieldError,+ VISIBILITY,+} from '../api/_lib/bnb/greenfield.js';++const OWNER = '0x1111111111111111111111111111111111111111';+const OTHER = '0x2222222222222222222222222222222222222222';++function jsonResponse(obj, status = 200) {+ return { ok: status >= 200 && status < 300, status, async json() { return obj; }, async text() { return JSON.stringify(obj); }, headers: { get: () => null } };+}+function bytesResponse(status, { contentType = 'model/gltf-binary', body = new Uint8Array([1, 2, 3]) } = {}) {+ return {+ ok: status >= 200 && status < 300,+ status,+ async arrayBuffer() { return body.buffer; },+ async text() { return ''; },+ headers: { get: (h) => (h.toLowerCase() === 'content-type' ? contentType : h.toLowerCase() === 'content-length' ? String(body.length) : null) },+ };+}++describe('network config', () => {+ it('defaults to testnet and exposes chain + SP endpoints', () => {+ const t = greenfieldNetwork();+ expect(t.chainId).toBe('greenfield_5600-1');+ expect(t.sps.length).toBeGreaterThanOrEqual(2);+ expect(greenfieldNetwork('mainnet').chainId).toBe('greenfield_1017-1');+ });+});++describe('getObjectMeta', () => {+ it('returns object_info on success', async () => {+ const fetchImpl = async () => jsonResponse({ object_info: { object_name: 'model.glb', payload_size: '2048', visibility: VISIBILITY.PUBLIC_READ, owner: OWNER } });+ const meta = await getObjectMeta('syn-bucket', 'model.glb', { fetchImpl });+ expect(meta.object_name).toBe('model.glb');+ expect(meta.visibility).toBe(VISIBILITY.PUBLIC_READ);+ });++ it('maps a "No such object" chain error to typed not_found', async () => {+ const fetchImpl = async () => jsonResponse({ code: 2, message: 'codespace storage code 1101: No such object', details: [] });+ await expect(getObjectMeta('syn-bucket', 'ghost.glb', { fetchImpl })).rejects.toMatchObject({ code: 'not_found' });+ });++ it('rejects a malformed object name before any network call', async () => {+ let called = false;+ const fetchImpl = async () => { called = true; return jsonResponse({}); };+ await expect(getObjectMeta('syn-bucket', 'has space', { fetchImpl })).rejects.toBeInstanceOf(GreenfieldError);+ expect(called).toBe(false);+ });+});++describe('headBucket', () => {+ it('returns bucket_info on success', async () => {+ const fetchImpl = async () => jsonResponse({ bucket_info: { bucket_name: 'syn-bucket', owner: OWNER } });+ const info = await headBucket('syn-bucket', { fetchImpl });+ expect(info.bucket_name).toBe('syn-bucket');+ });+ it('maps "No such bucket" to not_found', async () => {+ const fetchImpl = async () => jsonResponse({ code: 2, message: 'codespace storage code 1100: No such bucket', details: [] });+ await expect(headBucket('ghost', { fetchImpl })).rejects.toMatchObject({ code: 'not_found' });+ });+});++describe('getObjectPermissions', () => {+ it('grants a public-read object to any principal', async () => {+ const fetchImpl = async () => jsonResponse({ object_info: { visibility: VISIBILITY.PUBLIC_READ, owner: OWNER } });+ const p = await getObjectPermissions('syn-bucket', 'pub.glb', OTHER, { fetchImpl });+ expect(p.allowed).toBe(true);+ expect(p.reason).toBe('public-read');+ });++ it('grants the owner of a private object', async () => {+ const fetchImpl = async () => jsonResponse({ object_info: { visibility: VISIBILITY.PRIVATE, owner: OWNER } });+ const p = await getObjectPermissions('syn-bucket', 'priv.glb', OWNER, { fetchImpl });+ expect(p.allowed).toBe(true);+ expect(p.reason).toBe('owner');+ });++ it('returns false for a principal not in the policy of a private object', async () => {+ const fetchImpl = async () => jsonResponse({ object_info: { visibility: VISIBILITY.PRIVATE, owner: OWNER } });+ const p = await getObjectPermissions('syn-bucket', 'priv.glb', OTHER, { fetchImpl });+ expect(p.allowed).toBe(false);+ });+});++describe('downloadObject', () => {+ it('returns bytes for a public object', async () => {+ const fetchImpl = async () => bytesResponse(200);+ const out = await downloadObject('syn-bucket', 'pub.glb', { fetchImpl });+ expect(out.bytes.byteLength).toBe(3);+ expect(out.contentType).toBe('model/gltf-binary');+ });++ it('a private object without permission → typed forbidden (not a 500)', async () => {+ const fetchImpl = async () => bytesResponse(403);+ await expect(downloadObject('syn-bucket', 'priv.glb', { fetchImpl })).rejects.toMatchObject({ code: 'forbidden', status: 403 });+ });++ it('missing object → typed not_found', async () => {+ const fetchImpl = async () => bytesResponse(404);+ await expect(downloadObject('syn-bucket', 'ghost.glb', { fetchImpl })).rejects.toMatchObject({ code: 'not_found' });+ });++ it('fails over to the next SP on a 503, then succeeds', async () => {+ let n = 0;+ const fetchImpl = async () => (++n === 1 ? bytesResponse(503) : bytesResponse(200));+ const out = await downloadObject('syn-bucket', 'pub.glb', { fetchImpl });+ expect(out.bytes.byteLength).toBe(3);+ expect(n).toBe(2);+ });++ it('all SPs down → typed unavailable', async () => {+ const fetchImpl = async () => bytesResponse(503);+ await expect(downloadObject('syn-bucket', 'pub.glb', { fetchImpl })).rejects.toMatchObject({ code: 'unavailable' });+ });+});++describe('listObjects', () => {+ it('parses an S3-style XML object list', async () => {+ const xml = '<?xml version="1.0"?><ListObjectsResult><Contents><Key>a.glb</Key></Contents><Contents><Key>b.glb</Key></Contents></ListObjectsResult>';+ const fetchImpl = async () => ({ ok: true, status: 200, async text() { return xml; }, async json() { return {}; }, headers: { get: () => null } });+ const out = await listObjects('syn-bucket', { fetchImpl });+ expect(out.objects.map((o) => o.name)).toEqual(['a.glb', 'b.glb']);+ });++ it('parses a JSON object list', async () => {+ const fetchImpl = async () => ({ ok: true, status: 200, async text() { return JSON.stringify({ objects: [{ object_name: 'x.glb', payload_size: '10' }] }); }, async json() { return {}; }, headers: { get: () => null } });+ const out = await listObjects('syn-bucket', { fetchImpl });+ expect(out.objects[0]).toMatchObject({ name: 'x.glb', size: 10 });+ });++ it('private bucket → forbidden', async () => {+ const fetchImpl = async () => ({ ok: false, status: 403, async text() { return ''; }, async json() { return {}; }, headers: { get: () => null } });+ await expect(listObjects('syn-bucket', { fetchImpl })).rejects.toMatchObject({ code: 'forbidden' });+ });+});