ShortStrings.test.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. const FALLBACK_SENTINEL = ethers.zeroPadValue('0xFF', 32);
  5. const length = sstr => parseInt(sstr.slice(64), 16);
  6. const decode = sstr => ethers.toUtf8String(sstr).slice(0, length(sstr));
  7. const encode = str =>
  8. str.length < 32
  9. ? ethers.concat([
  10. ethers.encodeBytes32String(str).slice(0, -2),
  11. ethers.zeroPadValue(ethers.toBeArray(str.length), 1),
  12. ])
  13. : FALLBACK_SENTINEL;
  14. async function fixture() {
  15. const mock = await ethers.deployContract('$ShortStrings');
  16. return { mock };
  17. }
  18. describe('ShortStrings', function () {
  19. beforeEach(async function () {
  20. Object.assign(this, await loadFixture(fixture));
  21. });
  22. for (const str of [0, 1, 16, 31, 32, 64, 1024].map(length => 'a'.repeat(length))) {
  23. describe(`with string length ${str.length}`, function () {
  24. it('encode / decode', async function () {
  25. if (str.length < 32) {
  26. const encoded = await this.mock.$toShortString(str);
  27. expect(encoded).to.equal(encode(str));
  28. expect(decode(encoded)).to.equal(str);
  29. expect(await this.mock.$byteLength(encoded)).to.equal(str.length);
  30. expect(await this.mock.$toString(encoded)).to.equal(str);
  31. } else {
  32. await expect(this.mock.$toShortString(str))
  33. .to.be.revertedWithCustomError(this.mock, 'StringTooLong')
  34. .withArgs(str);
  35. }
  36. });
  37. it('set / get with fallback', async function () {
  38. const short = await this.mock
  39. .$toShortStringWithFallback(str, 0)
  40. .then(tx => tx.wait())
  41. .then(receipt => receipt.logs.find(ev => ev.fragment.name == 'return$toShortStringWithFallback').args[0]);
  42. expect(short).to.equal(encode(str));
  43. const promise = this.mock.$toString(short);
  44. if (str.length < 32) {
  45. expect(await promise).to.equal(str);
  46. } else {
  47. await expect(promise).to.be.revertedWithCustomError(this.mock, 'InvalidShortString');
  48. }
  49. expect(await this.mock.$byteLengthWithFallback(short, 0)).to.equal(str.length);
  50. expect(await this.mock.$toStringWithFallback(short, 0)).to.equal(str);
  51. });
  52. });
  53. }
  54. });