ShortStrings.test.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const { expect } = require('chai');
  2. const { expectRevertCustomError } = require('../helpers/customError');
  3. const ShortStrings = artifacts.require('$ShortStrings');
  4. function length(sstr) {
  5. return parseInt(sstr.slice(64), 16);
  6. }
  7. function decode(sstr) {
  8. return web3.utils.toUtf8(sstr).slice(0, length(sstr));
  9. }
  10. contract('ShortStrings', function () {
  11. before(async function () {
  12. this.mock = await ShortStrings.new();
  13. });
  14. for (const str of [0, 1, 16, 31, 32, 64, 1024].map(length => 'a'.repeat(length))) {
  15. describe(`with string length ${str.length}`, function () {
  16. it('encode / decode', async function () {
  17. if (str.length < 32) {
  18. const encoded = await this.mock.$toShortString(str);
  19. expect(decode(encoded)).to.be.equal(str);
  20. const length = await this.mock.$byteLength(encoded);
  21. expect(length.toNumber()).to.be.equal(str.length);
  22. const decoded = await this.mock.$toString(encoded);
  23. expect(decoded).to.be.equal(str);
  24. } else {
  25. await expectRevertCustomError(this.mock.$toShortString(str), `StringTooLong("${str}")`);
  26. }
  27. });
  28. it('set / get with fallback', async function () {
  29. const { logs } = await this.mock.$toShortStringWithFallback(str, 0);
  30. const { ret0 } = logs.find(({ event }) => event == 'return$toShortStringWithFallback').args;
  31. const promise = this.mock.$toString(ret0);
  32. if (str.length < 32) {
  33. expect(await promise).to.be.equal(str);
  34. } else {
  35. await expectRevertCustomError(promise, 'InvalidShortString()');
  36. }
  37. const length = await this.mock.$byteLengthWithFallback(ret0, 0);
  38. expect(length.toNumber()).to.be.equal(str.length);
  39. const recovered = await this.mock.$toStringWithFallback(ret0, 0);
  40. expect(recovered).to.be.equal(str);
  41. });
  42. });
  43. }
  44. });