builtins2.spec.ts 2.7 KB

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