Skip to content

Commit

Permalink
fix: sort account keys when generating file
Browse files Browse the repository at this point in the history
  • Loading branch information
hstove committed May 7, 2024
1 parent 3e62990 commit a77e4e9
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/curly-bees-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clarigen/cli': patch
---

The accounts type now has a fixed alphabetical ordering. This will prevent git changes just from re-running `clarigen`.
5 changes: 5 additions & 0 deletions .changeset/rare-plums-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clarigen/boot': patch
---

Adds updated boot package exports
23 changes: 17 additions & 6 deletions packages/cli/src/files/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { Session } from '../session';
import { Session, SessionAccount } from '../session';

export function generateAccountsCode(session: Session) {
const accounts = Object.fromEntries(
session.accounts.map(account => {
const { name, ...rest } = account;
export function generateAccountsCode(accounts: SessionAccount[]) {
const sortedAccounts = sortAccounts(accounts);
return Object.fromEntries(
sortedAccounts.map(a => {
const { name, ...rest } = a;
return [name, rest];
})
);
}

return `export const accounts = ${JSON.stringify(accounts)} as const;`;
// Sort accounts alphabetically by their name.
// Used to preserve ordering when generating files
export function sortAccounts(accounts: SessionAccount[]): SessionAccount[] {
const nameSorted = [...accounts].sort((a, b) => {
if (a.name < b.name) {
return -1;
}
return 1;
});
return nameSorted;
}
2 changes: 1 addition & 1 deletion packages/cli/src/files/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const contracts = {
${contractDefs.join(',\n')}
} as const;
${generateAccountsCode(session)}
${generateAccountsCode(session.accounts)}
${generateIdentifiersCode(session)}
Expand Down
24 changes: 24 additions & 0 deletions packages/cli/test/files.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { generateAccountsCode } from '../src/files/accounts';
import { SessionAccount } from '../src/session';
import { describe, expect, test } from 'vitest';

test('accounts are sorted before serialization', async () => {
const accounts: SessionAccount[] = [
{
name: 'wallet_2',
balance: '100',
address: 'aaa',
},
{
name: 'wallet_1',
balance: '200',
address: 'bbb',
},
];
const serialized = generateAccountsCode(accounts);
expect(Object.keys(serialized)[0]).toEqual('wallet_1');
expect(serialized.wallet_1).toEqual({
balance: '200',
address: 'bbb',
});
});

0 comments on commit a77e4e9

Please sign in to comment.