builtins2.spec.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import expect from 'expect';
  2. import { createConnection, deploy, aliceKeypair, weight, query } from './index';
  3. import { ContractPromise } from '@polkadot/api-contract';
  4. import { convertWeight } from '@polkadot/api-contract/base/util';
  5. describe('Deploy builtins2 contract and test', () => {
  6. it('builtins2', async function () {
  7. this.timeout(50000);
  8. let conn = await createConnection();
  9. const alice = aliceKeypair();
  10. let deployed_contract = await deploy(conn, alice, 'builtins2.contract', BigInt(0));
  11. let contract = new ContractPromise(conn, deployed_contract.abi, deployed_contract.address);
  12. let gasLimit = await weight(conn, contract, "burnGas", [0]);
  13. let { output: blake2_128 } = await query(conn, alice, contract, "hashBlake2128", ['0x' + Buffer.from('Call me Ishmael.', 'utf8').toString('hex')]);
  14. expect(blake2_128?.toJSON()).toBe("0x56691483d63cac66c38c168c703c6f13");
  15. let { output: blake2_256 } = await query(conn, alice, contract, "hashBlake2256", ['0x' + Buffer.from('Call me Ishmael.', 'utf8').toString('hex')]);
  16. expect(blake2_256?.toJSON()).toBe("0x1abd7330c92d835b5084219aedba821c3a599d039d5b66fb5a22ee8e813951a8");
  17. let { output: _contract_block_number } = await query(conn, alice, contract, "blockHeight", []);
  18. let contract_block_number = Number.parseInt(_contract_block_number!.toString());
  19. let rpc_block_number = await (await conn.query.system.number()).toNumber();
  20. expect(Math.abs(contract_block_number - rpc_block_number)).toBeLessThanOrEqual(3);
  21. let { output: gas_left } = await query(conn, alice, contract, "burnGas", [0], undefined, convertWeight(gasLimit).v2Weight);
  22. let gas = BigInt(gas_left!.toString());
  23. expect(gasLimit.toJSON().refTime).toBeGreaterThan(gas);
  24. let previous_diff = BigInt(gasLimit.toJSON().refTime) - gas;
  25. // Gas metering is based on execution time:
  26. // Expect each call to burn between 10000..1000000 more gas than the previous iteration.
  27. for (let i = 1; i < 100; i++) {
  28. let { output: gas_left } = await query(conn, alice, contract, "burnGas", [i], undefined, convertWeight(gasLimit).v2Weight);
  29. let gas = BigInt(gas_left!.toString());
  30. expect(gasLimit.toJSON().refTime).toBeGreaterThan(gas);
  31. let diff = BigInt(gasLimit.toJSON().refTime) - gas;
  32. expect(diff).toBeGreaterThan(previous_diff);
  33. expect(diff - previous_diff).toBeLessThan(1e6);
  34. expect(diff - previous_diff).toBeGreaterThan(1e4);
  35. previous_diff = diff;
  36. }
  37. conn.disconnect();
  38. });
  39. });