Skip to content

Commit

Permalink
test: upgrade tests to support new kwild changes
Browse files Browse the repository at this point in the history
Implement tests that use new CREATE NAMESPACE, CREATE ACTION, CREATE TABLE SQL syntax and test these
actions.  Add the execSql and selectQuery API tests
  • Loading branch information
martin-opensky committed Jan 28, 2025
1 parent 8bb5c98 commit 876212a
Show file tree
Hide file tree
Showing 16 changed files with 627 additions and 625 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"pack_pre": "copyfiles package.json README.md dist && rimraf ./kwil*.tgz",
"pack_post": "copyfiles ./kwil*.tgz ./pkg && rimraf ./kwil*.tgz",
"pack": "npm run pack_build && npm run pack_pre && npm --prefix ./dist pack && npm run pack_post",
"integration": "npx jest ./tests/kwil",
"integration": "npx jest ./tests/integration/**/*.test.ts",
"scratchpad": "ts-node testing-functions/scratchpad.js"
},
"author": "Kwil, Inc. <luke@kwil.com>",
Expand Down
15 changes: 10 additions & 5 deletions src/api_client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,8 @@ export default class Client extends Api {
});
}

protected async callClient(msg: Message): Promise<CallClientResponse<Object[] | MsgReceipt>> {
// TODO: Ensure return type is correct (Promise<GenericResponse<Object[] | MsgReceipt>>)
protected async callClient(msg: Message): Promise<CallClientResponse<Object[]>> {
const body = this.buildJsonRpcRequest<CallRequest>(JSONRPCMethod.METHOD_CALL, {
body: msg.body,
auth_type: msg.auth_type,
Expand All @@ -289,10 +290,12 @@ export default class Client extends Api {

const res = await super.post<JsonRPCResponse<CallResponse>>(`/rpc/v1`, body);

const errorResponse = this.checkAuthError(res);
if (errorResponse) {
return errorResponse;
}
// TODO: Remove this once we have auth working
// TODO: What is MsgReceipt type?
// const errorResponse = this.checkAuthError(res);
// if (errorResponse) {
// return errorResponse;
// }

return checkRes(res, (r) => this.parseQueryResponse(r.result.query_result));
}
Expand Down Expand Up @@ -368,6 +371,8 @@ function checkRes<T, R>(
throw new Error(`failed to parse response: ${res}`);
}

console.log('res', res);

if (res.data.error) {
const data = res.data.error.data ? `, data: ${JSON.stringify(res.data.error.data)}` : '';
throw new Error(
Expand Down
8 changes: 4 additions & 4 deletions src/api_client/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export interface ClientConfig extends ApiConfig {
}

export interface KwilConfig extends ClientConfig {
chainId: string;
autoAuthenticate?: boolean;
chainId: string;
autoAuthenticate?: boolean;
}

/**
Expand All @@ -28,6 +28,6 @@ export interface KwilConfig extends ClientConfig {
* @property {number} [timeout] - timeout for requests in milliseconds
* @property {boolean} [logging] - enable logging
* @property {Function} [logger] - custom logger function
* @property {number} [cache] - Time to live cache in seconds. Only getSchema requests are cached. Default is 10 minutes.
* @property {number} [cache] - @deprecated Cache is no longer supported.
*/
export type Config = KwilConfig;
export type Config = KwilConfig;
22 changes: 9 additions & 13 deletions src/client/kwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { GenericResponse } from '../core/resreq';
import { Database, DeployBody, DropBody } from '../core/database';
import { TxReceipt } from '../core/tx';
import { Account, ChainInfo, ChainInfoOpts, DatasetInfo } from '../core/network';
import { Cache } from '../utils/cache';
import { TxInfoReceipt } from '../core/txQuery';
import {
AuthenticationMode,
Expand Down Expand Up @@ -39,16 +38,13 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
protected readonly chainId: string;
private readonly autoAuthenticate: boolean;

//TODO: cache schemas
private schemas: Cache<GenericResponse<Database>>;
public funder: Funder<T>;
public auth: Auth<T>;

private authMode?: string; // To store the mode on the class for subsequent requests

protected constructor(opts: KwilConfig) {
super(opts);
this.schemas = Cache.passive(opts.cache);

// set chainId
this.chainId = opts.chainId;
Expand Down Expand Up @@ -153,7 +149,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
return await this.broadcastClient(
transaction,
// TODO: check the difference between commit and sync
synchronous ? BroadcastSyncType.SYNC : undefined
synchronous ? BroadcastSyncType.SYNC : BroadcastSyncType.COMMIT
);
}

Expand Down Expand Up @@ -228,21 +224,21 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
*
* @example
* // Insert with parameters
* await kwil.query(
* await kwil.execSql(
* '{mydb}INSERT INTO users (name, email) VALUES ($name, $email)',
* { $name: 'John', $email: 'john@example.com' },
* signer
* );
*
* // Update with parameters
* await kwil.query(
* await kwil.execSql(
* '{mydb}UPDATE users SET status = $status WHERE id = $id',
* { $status: 'active', $id: 123 },
* signer
* );
*
* // Delete with parameters
* await kwil.query(
* await kwil.execSql(
* '{mydb}DELETE FROM users WHERE id = $id',
* { $id: 123 },
* signer
Expand All @@ -251,7 +247,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
* @returns Promise resolving to transaction receipt
*/

public async query(
public async execSql(
query: string,
params: QueryParams,
signer: KwilSigner,
Expand All @@ -267,7 +263,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {

const transaction = await PayloadTx.createTx(this, {
chainId: this.chainId,
description: `Performing a mutative query: ${query}`,
description: `Performing a mutative query`,
payload: rawStatementPayload,
payloadType: PayloadType.RAW_STATEMENT,
identifier: signer.identifier,
Expand All @@ -277,8 +273,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {

return await this.broadcastClient(
transaction,
// TODO: Are the sync types correct?
synchronous ? BroadcastSyncType.SYNC : undefined
synchronous ? BroadcastSyncType.SYNC : BroadcastSyncType.COMMIT
);
}

Expand Down Expand Up @@ -428,7 +423,8 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
actionBody: CallBody,
kwilSigner?: KwilSigner,
cookieHandlerCallback?: { setCookie: () => void; resetCookie: () => void }
): Promise<GenericResponse<Object[] | MsgReceipt>> {
// TODO: Ensure return type is correct (Promise<GenericResponse<Object[] | MsgReceipt>>)
): Promise<GenericResponse<Object[]>> {
// Ensure auth mode is set
await this.ensureAuthenticationMode();

Expand Down
3 changes: 2 additions & 1 deletion src/client/node/nodeKwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export class NodeKwil extends Kwil<EnvironmentType.NODE> {
public async call(
actionBody: CallBodyNode,
kwilSigner?: KwilSigner
): Promise<GenericResponse<Object[] | MsgReceipt>> {
// TODO: Ensure return type is correct (Promise<GenericResponse<Object[] | MsgReceipt>>)
): Promise<GenericResponse<Object[]>> {
const setCookie = () => {
// set the temporary cookie, if the user provided one
if (actionBody.cookie) {
Expand Down
3 changes: 2 additions & 1 deletion src/client/web/webKwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export class WebKwil extends Kwil<EnvironmentType.BROWSER> {
public async call(
actionBody: CallBody,
kwilSigner?: KwilSigner
): Promise<GenericResponse<Object[] | MsgReceipt>> {
// TODO: Ensure return type is correct (Promise<GenericResponse<Object[] | MsgReceipt>>)
): Promise<GenericResponse<Object[]>> {
return await this.baseCall(actionBody, kwilSigner);
}
}
5 changes: 2 additions & 3 deletions src/core/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ export type PayloadBytesTypes =
| BytesEncodingStatus.UINT8_ENCODED;

export enum BroadcastSyncType {
ASYNC = 0,
SYNC = 1,
COMMIT = 2,
SYNC = 0, // Waits for the TX to be confirmed before returning
COMMIT = 1, // Returns TX immediately, even if the transaction succeeds or fails
}

export enum AuthErrorCodes {
Expand Down
2 changes: 1 addition & 1 deletion src/funder/funder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class Funder<T extends EnvironmentType> {
return await this.funderClient.broadcastClient(
transaction,
// TODO: Are the sync types correct?
synchronous ? BroadcastSyncType.SYNC : undefined
synchronous ? BroadcastSyncType.SYNC : BroadcastSyncType.COMMIT
);
}
}
1 change: 1 addition & 0 deletions src/transaction/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ export class Action<T extends EnvironmentType> {
* @returns {EncodedValue[][]} - An array of arrays of encoded values.
*/
private encodeActionInputs(selectedAction: NamespaceAction, actionInputs: Entries[]) {
// TODO: Shouldn't need to use any[]
const encodedActionInputs: any[] = [];

for (let i = 0; i < actionInputs.length; i++) {
Expand Down
145 changes: 0 additions & 145 deletions src/utils/cache.ts

This file was deleted.

16 changes: 12 additions & 4 deletions test-eth-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ function App() {
// 'Transfer: ',
// await getTxProperties(encodeTransfer(transfer), PayloadType.TRANSFER, 'kwil-testnet', nonce)
// );

// await executeAction(kwil, namespace, 'insert_variables', kwilSigner, nonce);
const wrongKwilSigner = new KwilSigner(signer, '0xC0B84D0E05c59e48110577F8Ec2EEE360F804371');
await executeAction(kwil, namespace, 'insert_variables', wrongKwilSigner, nonce);
// await kwil.query('CREATE table simple_test (text_var text PRIMARY KEY);', {}, kwilSigner, true);

// await kwil.query(
Expand Down Expand Up @@ -109,8 +109,16 @@ function App() {
};

// Execute transfer
const result = await kwil.funder.transfer(transferBody, kwilSigner, true);
console.log(result);
// const result = await kwil.funder.transfer(transferBody, kwilSigner, true);
// console.log(result);

// const execResult = await kwil.execSql(
// `CREATE ACTION add_post($user text, $title text, $body text) PUBLIC { $id uuid := uuid_generate_v5('455f60aa-0569-4aaa-8469-63be2ec4dd96'::uuid, @txid); INSERT INTO posts (id, name, post_title, post_body) VALUES ($id, $user, $title, $body); }`,
// {},
// kwilSigner,
// true
// );
// console.log(execResult);

// Deprecated
// await kwil.selectQuery('main', 'SELECT * FROM variable_test');
Expand Down
Loading

0 comments on commit 876212a

Please sign in to comment.