Skip to content

Commit

Permalink
refactor: fix decimal metadata precision / scale
Browse files Browse the repository at this point in the history
Fix ensures the decimal var type works as expected in kwild and postgres
  • Loading branch information
martin-opensky committed Jan 27, 2025
1 parent f8a1a00 commit 8bb5c98
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 87 deletions.
1 change: 1 addition & 0 deletions src/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export class Auth<T extends EnvironmentType> {
}

// handle if the inputs are an array of ActionInput objects or an array of Entries objects
// TODO: now we are not using the ActionInput objects, we are using the Entries objects
const cleanActionValues = actionBody?.inputs
? actionBody.inputs.map((input) => {
return input instanceof ActionInput ? input.toEntries() : input;
Expand Down
26 changes: 24 additions & 2 deletions src/client/kwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
throw new Error('name is required in actionBody');
}

const namespace = this.resolveNamespace(actionBody);

// ActionInput[] has been deprecated.
// This transforms the ActionInput[] into Entries[] to support legacy ActionInput[]
let inputs: Entries[] = [];
Expand All @@ -135,7 +137,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
}

let tx = Action.createTx(this, {
namespace: actionBody.namespace,
namespace,
actionName: actionBody.name.toLowerCase(),
description: actionBody.description || '',
identifier: kwilSigner.identifier,
Expand Down Expand Up @@ -330,6 +332,9 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
*/

public getDBID(owner: string | Uint8Array, name: string): string {
console.warn(
'WARNING: `getDBID()` is deprecated and will be removed in the next major version. Please use `kwil.selectQuery(query, params?, signer?)` instead.'
);
return generateDBID(owner, name);
}

Expand Down Expand Up @@ -497,6 +502,8 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
throw new Error('name is required in actionBody');
}

const namespace = this.resolveNamespace(actionBody);

// ActionInput[] is deprecated. So we are converting any ActionInput[] to an Entries[]
let inputs: Entries[] = [];
if (actionBody.inputs && transformActionInput.isActionInputArray(actionBody.inputs)) {
Expand All @@ -509,7 +516,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
// pre Challenge message
let msg = Action.createTx<EnvironmentType.BROWSER>(this, {
chainId: this.chainId,
namespace: actionBody.namespace,
namespace,
actionName: actionBody.name,
description: actionBody.description || '',
actionInputs: inputs,
Expand Down Expand Up @@ -615,6 +622,7 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {
throw new Error('Authentication process did not complete successfully');
}

// TODO: Move this to a another location
private validateNamespace(namespace: string): boolean {
// Validate namespace
if (!namespace || typeof namespace !== 'string') {
Expand All @@ -633,4 +641,18 @@ export abstract class Kwil<T extends EnvironmentType> extends Client {

return true;
}

// TODO: Move this to a another location
private resolveNamespace(actionBody: ActionBody | CallBody): string {
if (actionBody.namespace) {
return actionBody.namespace;
}

if (actionBody.dbid) {
console.warn('Warning: The "dbid" field is deprecated. Please use "namespace" instead.');
return actionBody.dbid;
}

throw new Error('Either "namespace" or "dbid" must be provided');
}
}
2 changes: 1 addition & 1 deletion src/transaction/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ export class Action<T extends EnvironmentType> {
if (parameterType.includes('numeric') || parameterType.includes('decimal')) {
parameterType = VarType.NUMERIC;
const analysis = analyzeNumber(Number(parameterValue));
metadata = [analysis.totalDigits, analysis.decimalPosition];
metadata = [analysis.precision, analysis.scale];
}

// Validate parameter type against VarType enum
Expand Down
18 changes: 12 additions & 6 deletions src/utils/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,19 @@ export function analyzeNumber(num: number) {
const decimalIndex = numStr.indexOf('.');
const hasDecimal = decimalIndex !== -1;

// Calculate total digits (excluding the decimal point)
const totalDigits = hasDecimal ? numStr.length - 1 : numStr.length;
// Precision represents the total number of digits (excluding the decimal point)
const precision = hasDecimal ? numStr.length - 1 : numStr.length;
// Scale represents the number of digits after the decimal point
const scale = hasDecimal ? numStr.length - decimalIndex - 1 : 0;

// e.g. 123.456
// precision = 6
// scale = 3

return {
hasDecimal: hasDecimal,
totalDigits: totalDigits,
decimalPosition: hasDecimal ? decimalIndex : -1,
hasDecimal,
precision,
scale,
};
}

Expand Down Expand Up @@ -119,7 +125,7 @@ export function resolveValueType(value: ValueType): {
case 'number':
const numAnalysis = analyzeNumber(value);
if (numAnalysis.hasDecimal) {
metadata = [numAnalysis.totalDigits, numAnalysis.decimalPosition];
metadata = [numAnalysis.precision, numAnalysis.scale];
varType = VarType.NUMERIC;
} else {
varType = VarType.INT8;
Expand Down
46 changes: 21 additions & 25 deletions test-eth-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,19 @@ function App() {
// await executeAction(kwil, namespace, 'insert_variables', kwilSigner, nonce);
// await kwil.query('CREATE table simple_test (text_var text PRIMARY KEY);', {}, kwilSigner, true);

await kwil.query(
'{test}INSERT INTO missing_table (id, int_var, text_var, bool_var, blob_var) VALUES ($id, $int_var, $text_var, $bool_var, $blob_var)',
{
$id: '123e4567-e89b-12d3-a456-426614174003',
$int_var: 42,
$text_var: 'Sample text',
$bool_var: true,
//$decimal_var: 1234.56,
$blob_var: new Uint8Array([1]),
},
kwilSigner,
true
);
// await kwil.query(
// '{test}INSERT INTO missing_table (id, int_var, text_var, bool_var, blob_var) VALUES ($id, $int_var, $text_var, $bool_var, $blob_var)',
// {
// $id: '123e4567-e89b-12d3-a456-426614174003',
// $int_var: 42,
// $text_var: 'Sample text',
// $bool_var: true,
// //$decimal_var: 1234.56,
// $blob_var: new Uint8Array([1]),
// },
// kwilSigner,
// true
// );

// await testViewWithParam(kwil, namespace, kwilSigner);
// await kwilAuthenticate(kwil, kwilSigner)
Expand All @@ -102,19 +102,15 @@ function App() {
*/

// Create transfer payload
// const transferBody = {
// to: signer.address, // Can be hex string or Uint8Array
// amount: BigInt(1000000000000000000), // Amount in smallest unit (1 = 10^18)
// description: 'Optional transfer description',
// };
const transferBody = {
to: signer.address, // Can be hex string or Uint8Array
amount: BigInt(1000000000000000000), // Amount in smallest unit (1 = 10^18)
description: 'Optional transfer description',
};

// Execute transfer
// const result = await kwil.funder.transfer(transferBody, kwilSigner, true);
// console.log(result);
// console.log(await kwil.getTables('main'));
// console.log(await kwil.getTableColumns('main', 'variable_test'));
// console.log(await kwil.getActions('action_test'));
// console.log(await kwil.getExtensions('action_test'));
const result = await kwil.funder.transfer(transferBody, kwilSigner, true);
console.log(result);

// Deprecated
// await kwil.selectQuery('main', 'SELECT * FROM variable_test');
Expand Down Expand Up @@ -154,7 +150,7 @@ function App() {
// DECIMAL
// console.log(
// await kwil.selectQuery('{test}SELECT * FROM variable_test WHERE decimal_var = $decimal', {
// $decimal: 1245.34,
// $decimal: 12.3456,
// })
// );

Expand Down
Loading

0 comments on commit 8bb5c98

Please sign in to comment.