@remetra/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,12 @@ await meter.stop();
33
33
  Receipts are sent every minute. If one is rejected or the network is down, the counts are kept and
34
34
  sent with the next one.
35
35
 
36
+ ### Locked packages
37
+
38
+ Some packages only run for apps with a funded Remetra account (they use
39
+ [`@remetra/gate`](https://www.npmjs.com/package/@remetra/gate)). Once you have called `createMeter`,
40
+ they work and count their own usage. You do not need to wrap them.
41
+
36
42
  ### WebAssembly
37
43
 
38
44
  ```js
package/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Options for {@link createMeter}. */
2
2
  export interface MeterOptions {
3
- /** The app's 16-character id, from the "My app" tab. */
3
+ /** The app's 16-character id, from the App owners page. */
4
4
  appId: string;
5
5
  /** The metering key issued when the app was registered. Never your wallet key. */
6
6
  secretKey: string;
@@ -35,6 +35,8 @@ export interface Meter {
35
35
  instantiateWasm(name: string, bytes: BufferSource, imports?: WebAssembly.Imports): Promise<Record<string, any>>;
36
36
  /** Adds `n` calls by hand, for usage the wrappers cannot see. */
37
37
  record(name: string, key?: string, n?: number): void;
38
+ /** Asks whether this app may run the named locked packages. Used by @remetra/gate. */
39
+ gate(components: string[]): Promise<{ results: Record<string, { allowed: boolean; reason?: string }>; ttl: number }>;
38
40
  /** Sends a receipt now. Resolves to null when there is nothing to send. */
39
41
  flush(): Promise<ReceiptResult | null>;
40
42
  /** Stops the timer and sends a final receipt. Call on shutdown. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remetra/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Metering SDK for Remetra: count calls into royalty-bearing dependencies and send signed, zero-knowledge usage receipts.",
5
5
  "license": "Apache-2.0",
6
6
  "main": "index.js",
package/sdk/meter.js CHANGED
@@ -13,13 +13,20 @@
13
13
  // is the sum of a committed bucket breakdown, without revealing the breakdown. See zk/index.js.
14
14
  const L = require('../backend/lib');
15
15
  const zk = require('../zk');
16
+ const METER = Symbol.for('remetra.meter'), GATED = Symbol.for('remetra.gated'); // shared with @remetra/gate
16
17
 
17
18
  async function createMeter({ endpoint = 'https://remetra.xyz', appId, secretKey, flushMs = 60000, revenue = () => 0, prove = 'auto' }) {
18
19
  if (!appId || !secretKey) throw new Error('appId and secretKey are required');
19
20
  const useZk = prove === true || (prove === 'auto' && zk.canProve());
20
21
  if (prove === true && !zk.canProve()) throw new Error('zero-knowledge proving files are missing; build them with zk/build.sh');
21
22
  const kp = L.keypair(secretKey), base = endpoint.replace(/\/+$/, '') + '/api';
22
- const info = await (await fetch(`${base}/apps/${appId}`)).json();
23
+ // a brief network drop while starting must not stop the app: try a few times before giving up
24
+ let info, lastErr;
25
+ for (let i = 0; i < 4 && !info; i++) {
26
+ try { info = await (await fetch(`${base}/apps/${appId}`)).json(); }
27
+ catch (e) { lastErr = e; await new Promise((r) => setTimeout(r, 400 * (i + 1))); }
28
+ }
29
+ if (!info) throw new Error('REMETRA: could not reach ' + base + ': ' + lastErr.message);
23
30
  if (info.error) throw new Error('REMETRA: ' + info.error);
24
31
  let seq = info.lastSeq;
25
32
  const counts = new Map(); // component -> { buckets: number[], since }
@@ -31,6 +38,7 @@ async function createMeter({ endpoint = 'https://remetra.xyz', appId, secretKey,
31
38
  function record(name, key = '', n = 1) { entry(name).buckets[slot(String(key))] += n; }
32
39
 
33
40
  function wrap(name, target) {
41
+ if (target && target[GATED]) return target; // a locked package already counts its own calls
34
42
  const e = entry(name);
35
43
  let proxy = null; // declared before fn so the wrapper can compare against it safely
36
44
  const fn = (f, self, b) => function (...args) { e.buckets[b]++; return f.apply(this === undefined || this === proxy ? self : this, args); };
@@ -79,9 +87,21 @@ async function createMeter({ endpoint = 'https://remetra.xyz', appId, secretKey,
79
87
  return out;
80
88
  }
81
89
 
90
+ // The lock: asks whether this app may run the named packages (see @remetra/gate). A refusal is an
91
+ // answer, not an error; this only throws when Remetra cannot be reached, so callers can keep going.
92
+ async function gate(components) {
93
+ const res = await fetch(`${base}/gate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(L.signed(kp, 'gate.check', { appId, components })) });
94
+ const out = await res.json().catch(() => ({}));
95
+ if (res.ok) return out;
96
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) return { results: Object.fromEntries(components.map((c) => [c, { allowed: false, reason: out.error || 'Remetra refused this app.' }])), ttl: 60 };
97
+ throw new Error('Remetra gate unavailable (' + res.status + ')');
98
+ }
99
+
82
100
  const timer = setInterval(() => flush().catch((e) => console.error(e.message)), flushMs);
83
101
  timer.unref();
84
- return { wrap, wrapWasm, instantiateWasm, record, flush, stop: async () => { clearInterval(timer); return flush(); }, pubkey: kp.pubkey, proving: useZk };
102
+ const handle = { appId, record, gate };
103
+ globalThis[METER] = handle; // locked packages in this process find the meter here
104
+ return { wrap, wrapWasm, instantiateWasm, record, gate, flush, stop: async () => { clearInterval(timer); if (globalThis[METER] === handle) delete globalThis[METER]; return flush(); }, pubkey: kp.pubkey, proving: useZk };
85
105
  }
86
106
 
87
107
  module.exports = { createMeter };