Skip to content

Commit

Permalink
Merge pull request #189 from ar-io/PE-6579-add-ant-validation
Browse files Browse the repository at this point in the history
feat(PE-6579): add AoAntState typeguard util
  • Loading branch information
atticusofsparta authored Aug 28, 2024
2 parents 491ea06 + 4500a39 commit bc2779e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/utils/ao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { createData } from 'arbundles';
import { z } from 'zod';

import { defaultArweave } from '../common/arweave.js';
import { AOProcess } from '../common/index.js';
import { AOProcess, Logger } from '../common/index.js';
import {
ANT_LUA_ID,
ANT_REGISTRY_ID,
Expand All @@ -28,6 +28,7 @@ import {
} from '../constants.js';
import {
AoANTRecord,
AoANTState,
AoClient,
AoSigner,
ContractSigner,
Expand Down Expand Up @@ -218,3 +219,42 @@ export function createAoSigner(signer: ContractSigner): AoSigner {

return aoSigner;
}

// using passThrough to require the minimum fields and allow others (eg TotalSupply, Logo, etc)
export const AntStateSchema = z
.object({
Name: z.string(),
Ticker: z.string(),
Owner: z.string(),
Controllers: z.array(z.string()),
Records: z.record(
z.string(),
z
.object({
transactionId: z.string(),
ttlSeconds: z.number(),
})
.passthrough(),
),
Balances: z.record(z.string(), z.number()),
})
.passthrough();

/**
* @param state
* @returns {boolean}
* @throws {z.ZodError} if the state object does not match the expected schema
*/
export function isAoANTState(
state: object,
logger: Logger = Logger.default,
): state is AoANTState {
try {
AntStateSchema.parse(state);
return true;
} catch (error) {
// this allows us to see the path of the error in the object as well as the expected schema on invalid fields
logger.error(error.issues);
return false;
}
}
34 changes: 34 additions & 0 deletions tests/unit/ant.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import assert from 'node:assert';

import { isAoANTState } from '../../src/utils/ao';

const testAoANTState = {
Name: 'TestToken',
Ticker: 'TST',
Denomination: 1,
Owner: ''.padEnd(43, '1'),
Controllers: [''.padEnd(43, '2')],
Records: {
record1: {
transactionId: ''.padEnd(43, '1'),
ttlSeconds: 3600,
},
},
Balances: {
[''.padEnd(43, '1')]: 1,
},
Logo: ''.padEnd(43, '1'),
TotalSupply: 0,
Initialized: true,
};
describe('ANT', () => {
it('should validate accurate ANT state', () => {
const res = isAoANTState(testAoANTState);
assert.strictEqual(res, true);
});

it('should invalidate inaccurate ANT state', () => {
const res = isAoANTState({ ...testAoANTState, Name: 1 });
assert.strictEqual(res, false);
});
});

0 comments on commit bc2779e

Please sign in to comment.