Skip to content

Commit 90b9e06

Browse files
authored
Tidy up old code from the benchmark (#4616)
# Description of Changes Fixes the `reducers.onTransfer is not a function` error - that was old code left from the 1.x sdk. Also, regenerate the module_bindings and make sure the rust and typescript modules are identical in that respect. # Expected complexity level and risk 1 # Testing - [x] Verified that `spacetime generate --lang typescript --module-path spacetimedb --out-dir module_bindings` and `spacetime generate --lang typescript --module-path rust_module --out-dir module_bindings` give the same output. - [x] Setting `USE_SPACETIME_METRICS_ENDPOINT` to `0` no longer causes the error.
1 parent cd88beb commit 90b9e06

8 files changed

Lines changed: 34 additions & 154 deletions

File tree

templates/keynote-2/module_bindings/create_account_reducer.ts

Lines changed: 0 additions & 16 deletions
This file was deleted.

templates/keynote-2/module_bindings/index.ts

Lines changed: 5 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

templates/keynote-2/module_bindings/transfer_reducer.ts

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

templates/keynote-2/module_bindings/types/reducers.ts

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

templates/keynote-2/rust_module/src/lib.rs

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use spacetimedb::{reducer, ReducerContext, Table};
55
#[derive(Debug, Clone)]
66
pub struct Accounts {
77
#[primary_key]
8+
#[index(hash)]
89
pub id: u32,
910
pub balance: i64,
1011
}
@@ -31,21 +32,7 @@ pub fn seed(ctx: &ReducerContext, n: u32, initial_balance: i64) -> Result<(), St
3132
}
3233

3334
#[reducer]
34-
pub fn create_account(ctx: &ReducerContext, id: u32, balance: i64) -> Result<(), String> {
35-
let accounts = ctx.db.accounts();
36-
let by_id = accounts.id();
37-
38-
if let Some(mut row) = by_id.find(&id) {
39-
row.balance = balance;
40-
by_id.update(row);
41-
} else {
42-
accounts.insert(Accounts { id, balance });
43-
}
44-
Ok(())
45-
}
46-
47-
#[reducer]
48-
pub fn transfer(ctx: &ReducerContext, from: u32, to: u32, amount: i64, _client_txn_id: u64) -> Result<(), String> {
35+
pub fn transfer(ctx: &ReducerContext, from: u32, to: u32, amount: i64) -> Result<(), String> {
4936
if from == to {
5037
return Err("same_account".into());
5138
}

templates/keynote-2/spacetimedb/src/index.ts

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { schema, table, t, SenderError } from 'spacetimedb/server';
22

33
const spacetimedb = schema({
4-
account: table(
5-
{ name: 'account' },
4+
accounts: table(
5+
{ name: 'accounts', public: true },
66
{
77
id: t.u32().primaryKey().index('hash'),
88
balance: t.i64(),
@@ -12,9 +12,9 @@ const spacetimedb = schema({
1212
export default spacetimedb;
1313

1414
export const seed = spacetimedb.reducer(
15-
{ n: t.u32(), balance: t.i64() },
16-
(ctx, { n, balance }) => {
17-
const accounts = ctx.db.account;
15+
{ n: t.u32(), initialBalance: t.i64() },
16+
(ctx, { n, initialBalance: balance }) => {
17+
const accounts = ctx.db.accounts;
1818

1919
for (const row of accounts) {
2020
accounts.delete(row);
@@ -27,15 +27,24 @@ export const seed = spacetimedb.reducer(
2727
);
2828

2929
export const transfer = spacetimedb.reducer(
30-
{ from: t.u32(), to: t.u32(), amount: t.u32() },
31-
(ctx, { from, to, amount: amt }) => {
32-
const accounts = ctx.db.account;
30+
{ from: t.u32(), to: t.u32(), amount: t.i64() },
31+
(ctx, { from, to, amount }) => {
32+
if (from === to) {
33+
throw new SenderError('same_account');
34+
}
35+
if (amount <= 0) {
36+
throw new SenderError('non_positive_amount');
37+
}
38+
39+
const accounts = ctx.db.accounts;
3340
const byId = accounts.id;
3441

35-
const fromRow = byId.find(from)!;
36-
const toRow = byId.find(to)!;
42+
const fromRow = byId.find(from);
43+
const toRow = byId.find(to);
44+
if (fromRow === null || toRow === null) {
45+
throw new SenderError('account_missing');
46+
}
3747

38-
const amount = BigInt(amt);
3948
if (fromRow.balance < amount) {
4049
throw new SenderError('insufficient_funds');
4150
}

templates/keynote-2/src/cli.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ const testDirPath = fileURLToPath(testDirUrl);
226226

227227
if (connectors && !connectors.includes(tc.system)) continue;
228228

229-
const makeConnector = (CONNECTORS as any)[tc.system];
229+
const makeConnector = CONNECTORS[tc.system];
230230
if (!makeConnector) throw new Error(`Unknown connector ${tc.system}`);
231231

232232
const connector = makeConnector();

templates/keynote-2/src/connectors/spacetimedb.ts

Lines changed: 6 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,6 @@ export function spacetimedb(
1717
});
1818
}
1919

20-
// --- reducer completion tracking ------------------------
21-
const transferWaiters = new Map<
22-
bigint,
23-
{ resolve: () => void; reject: (e: unknown) => void }
24-
>();
25-
26-
let nextTransferId = 1n;
27-
let transferHooked = false;
28-
2920
async function connectWithBindings() {
3021
if (!url) throw new Error('STDB_URL not set');
3122
if (!moduleName) throw new Error('STDB_MODULE not set');
@@ -49,53 +40,6 @@ export function spacetimedb(
4940
console.log('[stdb] connected');
5041
const conn = ctx;
5142

52-
const reducers = conn.reducers;
53-
54-
if (
55-
process.env.USE_SPACETIME_METRICS_ENDPOINT === '0' &&
56-
!transferHooked
57-
) {
58-
transferHooked = true;
59-
console.log('[stdb] hooking onTransfer');
60-
(reducers as any).onTransfer(
61-
(
62-
eventCtx: any,
63-
args: {
64-
from: number;
65-
to: number;
66-
amount: bigint;
67-
clientTxnId: bigint;
68-
},
69-
) => {
70-
const clientTxnId = args.clientTxnId;
71-
// console.log('[stdb] onTransfer fired', { ...args, status: eventCtx?.event?.status });
72-
73-
const waiter = transferWaiters.get(clientTxnId);
74-
if (!waiter) {
75-
console.warn(
76-
'[stdb] no waiter for clientTxnId',
77-
clientTxnId.toString(),
78-
);
79-
return;
80-
}
81-
82-
transferWaiters.delete(clientTxnId);
83-
84-
const status = eventCtx?.event?.status;
85-
86-
if (status?.tag === 'Committed') {
87-
waiter.resolve();
88-
} else if (status?.tag === 'Failed') {
89-
waiter.reject(new Error(status?.value ?? 'transfer failed'));
90-
} else if (status?.tag === 'OutOfEnergy') {
91-
waiter.reject(new Error('transfer out of energy'));
92-
} else {
93-
waiter.reject(new Error('unknown transfer status'));
94-
}
95-
},
96-
);
97-
}
98-
9943
resolveReady();
10044

10145
if (subscriptions.length > 0) {
@@ -147,19 +91,6 @@ export function spacetimedb(
14791
},
14892

14993
async close() {
150-
const err = new Error('SpacetimeDB connection closed');
151-
152-
// Fail any in-flight transfers
153-
for (const waiter of transferWaiters.values()) {
154-
try {
155-
waiter.reject(err);
156-
} catch {
157-
/* ignore */
158-
}
159-
}
160-
transferWaiters.clear();
161-
transferHooked = false;
162-
16394
try {
16495
conn.disconnect();
16596
} catch (e) {
@@ -184,47 +115,18 @@ export function spacetimedb(
184115

185116
switch (fn) {
186117
case 'seed': {
187-
conn.reducers.seed({
118+
return conn.reducers.seed({
188119
n: args.accounts,
189120
initialBalance: args.initialBalance,
190121
});
191-
return;
192-
}
193-
194-
case 'createAccount': {
195-
conn.reducers.createAccount({ id: args.id, balance: args.balance });
196-
return;
197122
}
198123

199124
case 'transfer': {
200-
const clientTxnId = nextTransferId++;
201-
202-
if (process.env.USE_SPACETIME_METRICS_ENDPOINT === '0') {
203-
return new Promise<void>((resolve, reject) => {
204-
const waiter = { resolve, reject };
205-
transferWaiters.set(clientTxnId, waiter);
206-
207-
try {
208-
conn.reducers.transfer({
209-
from: args.from,
210-
to: args.to,
211-
amount: args.amount,
212-
clientTxnId,
213-
});
214-
} catch (err) {
215-
console.log(`ERROR ${err}`);
216-
transferWaiters.delete(clientTxnId);
217-
reject(err);
218-
}
219-
});
220-
} else {
221-
return conn.reducers.transfer({
222-
from: args.from,
223-
to: args.to,
224-
amount: args.amount,
225-
clientTxnId,
226-
});
227-
}
125+
return conn.reducers.transfer({
126+
from: args.from,
127+
to: args.to,
128+
amount: args.amount,
129+
});
228130
}
229131

230132
default:

0 commit comments

Comments
 (0)