arrays.spec.ts 2.6 KB

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