arrays.spec.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import expect from 'expect';
  2. import crypto from 'crypto';
  3. import { createConnection, deploy, transaction, aliceKeypair, weight, query, } from './index';
  4. import { ContractPromise } from '@polkadot/api-contract';
  5. import { ApiPromise } from '@polkadot/api';
  6. describe('Deploy arrays contract and test', () => {
  7. let conn: ApiPromise;
  8. before(async function () {
  9. conn = await createConnection();
  10. });
  11. after(async function () {
  12. await conn.disconnect();
  13. });
  14. it('arrays in account storage', async function () {
  15. this.timeout(50000);
  16. const alice = aliceKeypair();
  17. let deployed_contract = await deploy(conn, alice, 'arrays.contract', BigInt(0));
  18. let contract = new ContractPromise(conn, deployed_contract.abi, deployed_contract.address);
  19. let users = [];
  20. for (let i = 0; i < 3; i++) {
  21. let addr = '0x' + crypto.randomBytes(32).toString('hex');
  22. let name = `name${i}`;
  23. let id = crypto.randomBytes(4).readUInt32BE(0) % 1024;
  24. let perms: string[] = [];
  25. for (let j = 0; j < Math.random() * 3; j++) {
  26. let p = Math.floor(Math.random() * 8);
  27. perms.push(`Perm${p + 1}`);
  28. }
  29. let gasLimit = await weight(conn, contract, "addUser", [id, addr, name, perms]);
  30. const tx1 = contract.tx.addUser({ gasLimit }, id, addr, name, perms);
  31. await transaction(tx1, alice);
  32. users.push({ "name": name, "addr": addr, "id": id, "perms": perms });
  33. }
  34. let user = users[Math.floor(Math.random() * users.length)];
  35. let res1 = await query(conn, alice, contract, "getUserById", [user.id]);
  36. expect(res1.output?.toJSON()).toStrictEqual(user);
  37. if (user.perms.length > 0) {
  38. let perms = user.perms;
  39. let p = perms[Math.floor(Math.random() * perms.length)];
  40. let res2 = await query(conn, alice, contract, "hasPermission", [user.id, p]);
  41. expect(res2.output?.toJSON()).toBe(true);
  42. }
  43. user = users[Math.floor(Math.random() * users.length)];
  44. let res3 = await query(conn, alice, contract, "getUserByAddress", [user.addr]);
  45. expect(res3.output?.toJSON()).toStrictEqual(user);
  46. let gasLimit = await weight(conn, contract, "removeUser", [user.id]);
  47. const tx2 = contract.tx.removeUser({ gasLimit }, user.id);
  48. await transaction(tx2, alice);
  49. let res4 = await query(conn, alice, contract, "userExists", [user.id]);
  50. expect(res4.output?.toJSON()).toBe(false);
  51. });
  52. });