pyth.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. const elliptic = require("elliptic");
  2. const governance = require("@pythnetwork/xc-governance-sdk");
  3. const { deployProxy, upgradeProxy } = require("@openzeppelin/truffle-upgrades");
  4. const {
  5. expectRevert,
  6. expectEvent,
  7. time,
  8. } = require("@openzeppelin/test-helpers");
  9. const { assert, expect } = require("chai");
  10. // Use "WormholeReceiver" if you are testing with Wormhole Receiver
  11. const Wormhole = artifacts.require("Wormhole");
  12. const PythUpgradable = artifacts.require("PythUpgradable");
  13. const MockPythUpgrade = artifacts.require("MockPythUpgrade");
  14. const MockUpgradeableProxy = artifacts.require("MockUpgradeableProxy");
  15. const testSigner1PK =
  16. "cfb12303a19cde580bb4dd771639b0d26bc68353645571a8cff516ab2ee113a0";
  17. const testSigner2PK =
  18. "892330666a850761e7370376430bb8c2aa1494072d3bfeaed0c4fa3d5a9135fe";
  19. contract("Pyth", function () {
  20. const testSigner1 = web3.eth.accounts.privateKeyToAccount(testSigner1PK);
  21. const testSigner2 = web3.eth.accounts.privateKeyToAccount(testSigner2PK);
  22. const testGovernanceChainId = "1";
  23. const testGovernanceEmitter =
  24. "0x0000000000000000000000000000000000000000000000000000000000001234";
  25. const testPyth2WormholeChainId = "1";
  26. const testPyth2WormholeEmitter =
  27. "0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b";
  28. // Place all atomic operations that are done within migrations here.
  29. beforeEach(async function () {
  30. this.pythProxy = await deployProxy(PythUpgradable, [
  31. (await Wormhole.deployed()).address,
  32. [testPyth2WormholeChainId],
  33. [testPyth2WormholeEmitter],
  34. testGovernanceChainId,
  35. testGovernanceEmitter,
  36. 0, // Initial governance sequence
  37. 60, // Validity time in seconds
  38. 0, // single update fee in wei
  39. ]);
  40. });
  41. it("should be initialized with the correct signers and values", async function () {
  42. await this.pythProxy.isValidDataSource(
  43. testPyth2WormholeChainId,
  44. testPyth2WormholeEmitter
  45. );
  46. });
  47. it("there should be no owner", async function () {
  48. // Check that the ownership is renounced.
  49. const owner = await this.pythProxy.owner();
  50. assert.equal(owner, "0x0000000000000000000000000000000000000000");
  51. });
  52. it("deployer cannot upgrade the contract", async function () {
  53. // upgrade proxy should fail
  54. await expectRevert(
  55. upgradeProxy(this.pythProxy.address, MockPythUpgrade),
  56. "Ownable: caller is not the owner."
  57. );
  58. });
  59. // NOTE(2022-05-02): Raw hex payload obtained from format serialization unit tests in `wormhole_attester/sdk/rust`
  60. // Latest known addition: wire format v3
  61. //
  62. // Tests rely on a wormhole_attester/sdk/rust mock price/prod ID generation rule:
  63. // nthProdByte(n) = n % 256, starting with n=1
  64. // nthPriceByte(n) = 255 - (n % 256), starting with n=1
  65. //
  66. // Examples:
  67. // 1st prod = "0x010101[...]"
  68. // 1st price = "0xFEFEFE[...]"
  69. // 2nd prod = "0x020202[...]"
  70. // 2nd price = "0xFDFDFD[...]"
  71. // 3rd prod = "0x030303[...]"
  72. // 3rd price = "0xFCFCFC[...]"
  73. const RAW_BATCH_ATTESTATION_TIME_REGEX = /DEADBEEFFADEDEED/g;
  74. const RAW_BATCH_PUBLISH_TIME_REGEX = /00000000DADEBEEF/g;
  75. const RAW_BATCH_PRICE_REGEX = /0000002BAD2FEED7/g;
  76. const RAW_BATCH_PREV_PRICE_REGEX = /0000DEADFACEBEEF/g;
  77. const RAW_BATCH_PREV_PUBLISH_TIME_REGEX = /00000000DEADBABE/g;
  78. const RAW_BATCH_EMA_PRICE_REGEX = /FFFFFFFFFFFFFFD6/g;
  79. const RAW_PRICE_ATTESTATION_SIZE = 149;
  80. const RAW_BATCH_ATTESTATION_COUNT = 10;
  81. const RAW_BATCH =
  82. "0x" +
  83. "5032574800030000000102000A00950101010101010101010101010101010101010101010101010101010101010101FEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFE0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0202020202020202020202020202020202020202020202020202020202020202FDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFD0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0303030303030303030303030303030303030303030303030303030303030303FCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFC0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0404040404040404040404040404040404040404040404040404040404040404FBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFBFB0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0505050505050505050505050505050505050505050505050505050505050505FAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFA0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0606060606060606060606060606060606060606060606060606060606060606F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F9F90000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0707070707070707070707070707070707070707070707070707070707070707F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F8F80000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0808080808080808080808080808080808080808080808080808080808080808F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F70000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0909090909090909090909090909090909090909090909090909090909090909F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F6F60000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0AF5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F5F50000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A010001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF";
  84. const RAW_UNKNOWN_BATCH_ATTESTATION_COUNT = 3;
  85. const RAW_UNKNOWN_BATCH =
  86. "0x" +
  87. "5032574800030000000102000300950101010101010101010101010101010101010101010101010101010101010101FEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFE0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A000001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0202020202020202020202020202020202020202020202020202020202020202FDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFD0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A000001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF0303030303030303030303030303030303030303030303030303030303030303FCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFC0000002BAD2FEED70000000000000065FFFFFFFDFFFFFFFFFFFFFFD6000000000000002A000001E14C0004E6D0DEADBEEFFADEDEED00000000DADEBEEF00000000DEADBABE0000DEADFACEBEEF000000BADBADBEEF";
  88. // Takes an unsigned 64-bit integer, converts it to hex with 0-padding
  89. function u64ToHex(timestamp) {
  90. // u64 -> 8 bytes -> 16 hex bytes
  91. return timestamp.toString(16).padStart(16, "0");
  92. }
  93. function generateRawBatchAttestation(
  94. publishTime,
  95. attestationTime,
  96. priceVal,
  97. emaPriceVal
  98. ) {
  99. const pubTs = u64ToHex(publishTime);
  100. const attTs = u64ToHex(attestationTime);
  101. const price = u64ToHex(priceVal);
  102. const emaPrice = u64ToHex(emaPriceVal || priceVal);
  103. const replaced = RAW_BATCH.replace(RAW_BATCH_PUBLISH_TIME_REGEX, pubTs)
  104. .replace(RAW_BATCH_ATTESTATION_TIME_REGEX, attTs)
  105. .replace(RAW_BATCH_PRICE_REGEX, price)
  106. .replace(RAW_BATCH_EMA_PRICE_REGEX, emaPrice);
  107. return replaced;
  108. }
  109. function generateRawUnknownBatchAttestation(
  110. publishTime,
  111. attestationTime,
  112. priceVal,
  113. emaPriceVal,
  114. prevPublishTime,
  115. prevPriceVal
  116. ) {
  117. const pubTs = u64ToHex(publishTime);
  118. const attTs = u64ToHex(attestationTime);
  119. const price = u64ToHex(priceVal);
  120. const emaPrice = u64ToHex(emaPriceVal);
  121. const prevPubTs = u64ToHex(prevPublishTime);
  122. const prevPrice = u64ToHex(prevPriceVal);
  123. const replaced = RAW_UNKNOWN_BATCH.replace(
  124. RAW_BATCH_PUBLISH_TIME_REGEX,
  125. pubTs
  126. )
  127. .replace(RAW_BATCH_ATTESTATION_TIME_REGEX, attTs)
  128. .replace(RAW_BATCH_PRICE_REGEX, price)
  129. .replace(RAW_BATCH_EMA_PRICE_REGEX, emaPrice)
  130. .replace(RAW_BATCH_PREV_PUBLISH_TIME_REGEX, prevPubTs)
  131. .replace(RAW_BATCH_PREV_PRICE_REGEX, prevPrice);
  132. return replaced;
  133. }
  134. it("should parse batch price attestation correctly", async function () {
  135. let attestationTime = 1647273460; // re-used for publishTime
  136. let publishTime = 1647273465; // re-used for publishTime
  137. let priceVal = 1337;
  138. let emaPriceVal = 2022;
  139. let rawBatch = generateRawBatchAttestation(
  140. publishTime,
  141. attestationTime,
  142. priceVal,
  143. emaPriceVal
  144. );
  145. const receipt = await updatePriceFeeds(this.pythProxy, [rawBatch]);
  146. expectEventMultipleTimes(
  147. receipt,
  148. "PriceFeedUpdate",
  149. {
  150. price: "1337",
  151. },
  152. 10
  153. );
  154. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  155. const price_id =
  156. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  157. const price = await this.pythProxy.getPriceUnsafe(price_id);
  158. assert.equal(price.price, priceVal.toString());
  159. assert.equal(price.conf, "101"); // The value is hardcoded in the RAW_BATCH.
  160. assert.equal(price.publishTime, publishTime.toString());
  161. assert.equal(price.expo, "-3"); // The value is hardcoded in the RAW_BATCH.
  162. const emaPrice = await this.pythProxy.getEmaPriceUnsafe(price_id);
  163. assert.equal(emaPrice.price, emaPriceVal.toString());
  164. assert.equal(emaPrice.conf, "42"); // The value is hardcoded in the RAW_BATCH.
  165. assert.equal(emaPrice.publishTime, publishTime.toString());
  166. assert.equal(emaPrice.expo, "-3"); // The value is hardcoded in the RAW_BATCH.
  167. }
  168. });
  169. async function updatePriceFeeds(
  170. contract,
  171. batches,
  172. valueInWei,
  173. chainId,
  174. emitter
  175. ) {
  176. let updateData = [];
  177. for (let data of batches) {
  178. const vm = await signAndEncodeVM(
  179. 1,
  180. 1,
  181. chainId || testPyth2WormholeChainId,
  182. emitter || testPyth2WormholeEmitter,
  183. 0,
  184. data,
  185. [testSigner1PK],
  186. 0,
  187. 0
  188. );
  189. updateData.push("0x" + vm);
  190. }
  191. return await contract.updatePriceFeeds(updateData, { value: valueInWei });
  192. }
  193. /**
  194. * Create a governance instruction VAA from the Instruction object. Then
  195. * Submit and execute it on the contract.
  196. * @param contract Pyth contract
  197. * @param {governance.Instruction} governanceInstruction
  198. * @param {number} sequence
  199. */
  200. async function createAndThenSubmitGovernanceInstructionVaa(
  201. contract,
  202. governanceInstruction,
  203. sequence
  204. ) {
  205. await contract.executeGovernanceInstruction(
  206. await createVAAFromUint8Array(
  207. governanceInstruction.serialize(),
  208. testGovernanceChainId,
  209. testGovernanceEmitter,
  210. sequence
  211. )
  212. );
  213. }
  214. it("should attest price updates over wormhole", async function () {
  215. let ts = 1647273460;
  216. let rawBatch = generateRawBatchAttestation(ts - 5, ts, 1337);
  217. await updatePriceFeeds(this.pythProxy, [rawBatch]);
  218. });
  219. it("should attest price updates empty", async function () {
  220. const receipt = await updatePriceFeeds(this.pythProxy, []);
  221. expectEvent.notEmitted(receipt, "PriceFeedUpdate");
  222. expectEvent.notEmitted(receipt, "BatchPriceFeedUpdate");
  223. });
  224. it("should attest price updates with multiple batches of correct order", async function () {
  225. let ts = 1647273460;
  226. let rawBatch1 = generateRawBatchAttestation(ts - 5, ts, 1337);
  227. let rawBatch2 = generateRawBatchAttestation(ts + 5, ts + 10, 1338);
  228. const receipt = await updatePriceFeeds(this.pythProxy, [
  229. rawBatch1,
  230. rawBatch2,
  231. ]);
  232. expectEvent(receipt, "PriceFeedUpdate", {
  233. publishTime: (ts - 5).toString(),
  234. });
  235. expectEvent(receipt, "PriceFeedUpdate", {
  236. publishTime: (ts + 5).toString(),
  237. });
  238. expectEventMultipleTimes(receipt, "BatchPriceFeedUpdate", {}, 2);
  239. });
  240. it("should attest price updates with multiple batches of wrong order", async function () {
  241. let ts = 1647273460;
  242. let rawBatch1 = generateRawBatchAttestation(ts - 5, ts, 1337);
  243. let rawBatch2 = generateRawBatchAttestation(ts + 5, ts + 10, 1338);
  244. const receipt = await updatePriceFeeds(this.pythProxy, [
  245. rawBatch2,
  246. rawBatch1,
  247. ]);
  248. expectEvent(receipt, "PriceFeedUpdate", {
  249. publishTime: (ts + 5).toString(),
  250. });
  251. expectEventMultipleTimes(receipt, "BatchPriceFeedUpdate", {}, 2);
  252. expectEventNotEmittedWithArgs(receipt, "PriceFeedUpdate", {
  253. publishTime: (ts - 5).toString(),
  254. });
  255. });
  256. /**
  257. * Set fee to `newFee` by creating and submitting a governance instruction for it.
  258. * @param contarct Pyth contract
  259. * @param {number} newFee
  260. * @param {number=} governanceSequence Sequence number of the governance instruction. Defaults to 1.
  261. */
  262. async function setFeeTo(contract, newFee, governanceSequence) {
  263. await createAndThenSubmitGovernanceInstructionVaa(
  264. contract,
  265. new governance.SetFeeInstruction(
  266. governance.CHAINS.ethereum,
  267. BigInt(newFee),
  268. BigInt(0)
  269. ),
  270. governanceSequence ?? 1
  271. );
  272. }
  273. it("should not attest price updates with when required fee is not given", async function () {
  274. // Check initial fee is zero
  275. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 0);
  276. // Set fee to 10
  277. await setFeeTo(this.pythProxy, 10);
  278. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 10);
  279. let ts = 1647273460;
  280. let rawBatch1 = generateRawBatchAttestation(ts - 5, ts, 1337);
  281. let rawBatch2 = generateRawBatchAttestation(ts + 5, ts + 10, 1338);
  282. // Getting the fee from the contract
  283. let feeInWei = await this.pythProxy.methods["getUpdateFee(bytes[])"]([
  284. rawBatch1,
  285. rawBatch2,
  286. ]);
  287. assert.equal(feeInWei, 20);
  288. // When a smaller fee is payed it reverts
  289. await expectRevertCustomError(
  290. updatePriceFeeds(this.pythProxy, [rawBatch1, rawBatch2], feeInWei - 1),
  291. "InsufficientFee"
  292. );
  293. });
  294. it("should attest price updates with when required fee is given", async function () {
  295. // Check initial fee is zero
  296. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 0);
  297. // Set fee to 10
  298. await setFeeTo(this.pythProxy, 10);
  299. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 10);
  300. let ts = 1647273460;
  301. let rawBatch1 = generateRawBatchAttestation(ts - 5, ts, 1337);
  302. let rawBatch2 = generateRawBatchAttestation(ts + 5, ts + 10, 1338);
  303. // Getting the fee from the contract
  304. let feeInWei = await this.pythProxy.methods["getUpdateFee(bytes[])"]([
  305. rawBatch1,
  306. rawBatch2,
  307. ]);
  308. assert.equal(feeInWei, 20);
  309. await updatePriceFeeds(this.pythProxy, [rawBatch1, rawBatch2], feeInWei);
  310. const pythBalance = await web3.eth.getBalance(this.pythProxy.address);
  311. assert.equal(pythBalance, feeInWei);
  312. });
  313. it("should attest price updates with required fee even if more fee is given", async function () {
  314. // Check initial fee is zero
  315. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 0);
  316. // Set fee to 10
  317. await setFeeTo(this.pythProxy, 10);
  318. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), 10);
  319. let ts = 1647273460;
  320. let rawBatch1 = generateRawBatchAttestation(ts - 5, ts, 1337);
  321. let rawBatch2 = generateRawBatchAttestation(ts + 5, ts + 10, 1338);
  322. // Paying the fee works and extra fee is not paid back.
  323. let feeInWei = await this.pythProxy.methods["getUpdateFee(bytes[])"]([
  324. rawBatch1,
  325. rawBatch2,
  326. ]);
  327. assert.equal(feeInWei, 20);
  328. await updatePriceFeeds(
  329. this.pythProxy,
  330. [rawBatch1, rawBatch2],
  331. feeInWei + 10
  332. );
  333. const pythBalance = await web3.eth.getBalance(this.pythProxy.address);
  334. assert.equal(pythBalance, feeInWei + 10);
  335. });
  336. it("should cache price updates", async function () {
  337. let currentTimestamp = (await web3.eth.getBlock("latest")).timestamp;
  338. let priceVal = 521;
  339. let rawBatch = generateRawBatchAttestation(
  340. currentTimestamp - 5,
  341. currentTimestamp,
  342. priceVal
  343. );
  344. let receipt = await updatePriceFeeds(this.pythProxy, [rawBatch]);
  345. expectEvent(receipt, "PriceFeedUpdate", {
  346. price: priceVal.toString(),
  347. publishTime: (currentTimestamp - 5).toString(),
  348. });
  349. expectEvent(receipt, "BatchPriceFeedUpdate");
  350. let first_prod_id = "0x" + "01".repeat(32);
  351. let first_price_id = "0x" + "fe".repeat(32);
  352. let second_prod_id = "0x" + "02".repeat(32);
  353. let second_price_id = "0x" + "fd".repeat(32);
  354. // Confirm that previously non-existent feeds are created
  355. let first = await this.pythProxy.queryPriceFeed(first_price_id);
  356. console.debug(`first is ${JSON.stringify(first)}`);
  357. assert.equal(first.price.price, priceVal);
  358. let second = await this.pythProxy.queryPriceFeed(second_price_id);
  359. assert.equal(second.price.price, priceVal);
  360. // Confirm the price is bumped after a new attestation updates each record
  361. let nextTimestamp = currentTimestamp + 1;
  362. let rawBatch2 = generateRawBatchAttestation(
  363. nextTimestamp - 5,
  364. nextTimestamp,
  365. priceVal + 5
  366. );
  367. receipt = await updatePriceFeeds(this.pythProxy, [rawBatch2]);
  368. expectEvent(receipt, "PriceFeedUpdate", {
  369. price: (priceVal + 5).toString(),
  370. publishTime: (nextTimestamp - 5).toString(),
  371. });
  372. expectEvent(receipt, "BatchPriceFeedUpdate");
  373. first = await this.pythProxy.queryPriceFeed(first_price_id);
  374. assert.equal(first.price.price, priceVal + 5);
  375. second = await this.pythProxy.queryPriceFeed(second_price_id);
  376. assert.equal(second.price.price, priceVal + 5);
  377. // Confirm that only strictly larger timestamps trigger updates
  378. let rawBatch3 = generateRawBatchAttestation(
  379. nextTimestamp - 5,
  380. nextTimestamp,
  381. priceVal + 10
  382. );
  383. receipt = await updatePriceFeeds(this.pythProxy, [rawBatch3]);
  384. expectEvent.notEmitted(receipt, "PriceFeedUpdate");
  385. expectEvent(receipt, "BatchPriceFeedUpdate");
  386. first = await this.pythProxy.queryPriceFeed(first_price_id);
  387. assert.equal(first.price.price, priceVal + 5);
  388. assert.notEqual(first.price.price, priceVal + 10);
  389. second = await this.pythProxy.queryPriceFeed(second_price_id);
  390. assert.equal(second.price.price, priceVal + 5);
  391. assert.notEqual(second.price.price, priceVal + 10);
  392. });
  393. it("should fail transaction if a price is not found", async function () {
  394. await expectRevertCustomError(
  395. this.pythProxy.queryPriceFeed(
  396. "0xdeadfeeddeadfeeddeadfeeddeadfeeddeadfeeddeadfeeddeadfeeddeadfeed"
  397. ),
  398. "PriceFeedNotFound"
  399. );
  400. });
  401. it("should revert on getting stale current prices", async function () {
  402. let smallestTimestamp = 1;
  403. let rawBatch = generateRawBatchAttestation(
  404. smallestTimestamp,
  405. smallestTimestamp + 5,
  406. 1337
  407. );
  408. await updatePriceFeeds(this.pythProxy, [rawBatch]);
  409. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  410. const price_id =
  411. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  412. await expectRevertCustomError(
  413. this.pythProxy.getPrice(price_id),
  414. "StalePrice"
  415. );
  416. }
  417. });
  418. it("should revert on getting current prices too far into the future as they are considered unknown", async function () {
  419. let largestTimestamp = 4294967295;
  420. let rawBatch = generateRawBatchAttestation(
  421. largestTimestamp - 5,
  422. largestTimestamp,
  423. 1337
  424. );
  425. await updatePriceFeeds(this.pythProxy, [rawBatch]);
  426. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  427. const price_id =
  428. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  429. await expectRevertCustomError(
  430. this.pythProxy.getPrice(price_id),
  431. "StalePrice"
  432. );
  433. }
  434. });
  435. /**
  436. * Set valid time period to `newValidPeriod` by creating and submitting a
  437. * governance instruction for it.
  438. * @param contract Pyth contract
  439. * @param {number} newValidPeriod
  440. * @param {number=} governanceSequence Sequence number of the governance instruction. Defaults to 1.
  441. */
  442. async function setValidPeriodTo(
  443. contract,
  444. newValidPeriod,
  445. governanceSequence
  446. ) {
  447. await createAndThenSubmitGovernanceInstructionVaa(
  448. contract,
  449. new governance.SetValidPeriodInstruction(
  450. governance.CHAINS.ethereum,
  451. BigInt(newValidPeriod)
  452. ),
  453. governanceSequence ?? 1
  454. );
  455. }
  456. it("changing validity time works", async function () {
  457. const latestTime = await time.latest();
  458. let rawBatch = generateRawBatchAttestation(latestTime, latestTime, 1337);
  459. await updatePriceFeeds(this.pythProxy, [rawBatch]);
  460. // Setting the validity time to 30 seconds
  461. await setValidPeriodTo(this.pythProxy, 30, 1);
  462. assert.equal(await this.pythProxy.validTimePeriodSeconds(), 30);
  463. // Then prices should be available
  464. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  465. const price_id =
  466. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  467. // Expect getPrice to work (not revert)
  468. await this.pythProxy.getPrice(price_id);
  469. }
  470. // One minute passes
  471. await time.increase(time.duration.minutes(1));
  472. // The prices should become unavailable now.
  473. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  474. const price_id =
  475. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  476. await expectRevertCustomError(
  477. this.pythProxy.getPrice(price_id),
  478. "StalePrice"
  479. );
  480. }
  481. // Setting the validity time to 120 seconds
  482. await setValidPeriodTo(this.pythProxy, 120, 2);
  483. assert.equal(await this.pythProxy.validTimePeriodSeconds(), 120);
  484. // Then prices should be available because the valid period is now 120 seconds
  485. for (var i = 1; i <= RAW_BATCH_ATTESTATION_COUNT; i++) {
  486. const price_id =
  487. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  488. let priceFeedResult = await this.pythProxy.queryPriceFeed(price_id);
  489. // Expect getPrice to work (not revert)
  490. await this.pythProxy.getPrice(price_id);
  491. }
  492. });
  493. it("should use prev price and timestamp on unknown attestation status", async function () {
  494. const latestTime = await time.latest();
  495. let rawBatch = generateRawUnknownBatchAttestation(
  496. latestTime,
  497. latestTime,
  498. 1337, // price
  499. 1500, // ema price
  500. latestTime - 10,
  501. 1000 // prev price
  502. );
  503. const receipt = await updatePriceFeeds(this.pythProxy, [rawBatch]);
  504. expectEvent(receipt, "PriceFeedUpdate", {
  505. price: "1000",
  506. });
  507. // Then prices should be available because the valid period is now 120 seconds
  508. for (var i = 1; i <= RAW_UNKNOWN_BATCH_ATTESTATION_COUNT; i++) {
  509. const price_id =
  510. "0x" + (255 - (i % 256)).toString(16).padStart(2, "0").repeat(32);
  511. const price = await this.pythProxy.getPrice(price_id);
  512. assert.equal(price.price, "1000");
  513. assert.equal(price.publishTime, (latestTime - 10).toString());
  514. const emaPrice = await this.pythProxy.getEmaPrice(price_id);
  515. assert.equal(emaPrice.price, "1500");
  516. assert.equal(emaPrice.publishTime, (latestTime - 10).toString());
  517. }
  518. });
  519. // Governance
  520. // Logics that apply to all governance messages
  521. it("Make sure invalid magic and module won't work", async function () {
  522. // First 4 bytes of data are magic and the second byte after that is module
  523. const data = new governance.SetValidPeriodInstruction(
  524. governance.CHAINS.ethereum,
  525. BigInt(10)
  526. ).serialize();
  527. const wrongMagic = Buffer.from(data);
  528. wrongMagic[1] = 0;
  529. const vaaWrongMagic = await createVAAFromUint8Array(
  530. wrongMagic,
  531. testGovernanceChainId,
  532. testGovernanceEmitter,
  533. 1
  534. );
  535. await expectRevertCustomError(
  536. this.pythProxy.executeGovernanceInstruction(vaaWrongMagic),
  537. "InvalidGovernanceMessage"
  538. );
  539. const wrongModule = Buffer.from(data);
  540. wrongModule[4] = 0;
  541. const vaaWrongModule = await createVAAFromUint8Array(
  542. wrongModule,
  543. testGovernanceChainId,
  544. testGovernanceEmitter,
  545. 1
  546. );
  547. await expectRevertCustomError(
  548. this.pythProxy.executeGovernanceInstruction(vaaWrongModule),
  549. "InvalidGovernanceTarget"
  550. );
  551. const outOfBoundModule = Buffer.from(data);
  552. outOfBoundModule[4] = 20;
  553. const vaaOutOfBoundModule = await createVAAFromUint8Array(
  554. outOfBoundModule,
  555. testGovernanceChainId,
  556. testGovernanceEmitter,
  557. 1
  558. );
  559. await expectRevert(
  560. this.pythProxy.executeGovernanceInstruction(vaaOutOfBoundModule),
  561. "Panic: Enum value out of bounds."
  562. );
  563. });
  564. it("Make sure governance with wrong sender won't work", async function () {
  565. const data = new governance.SetValidPeriodInstruction(
  566. governance.CHAINS.ethereum,
  567. BigInt(10)
  568. ).serialize();
  569. const vaaWrongEmitter = await createVAAFromUint8Array(
  570. data,
  571. testGovernanceChainId,
  572. "0x0000000000000000000000000000000000000000000000000000000000001111",
  573. 1
  574. );
  575. await expectRevertCustomError(
  576. this.pythProxy.executeGovernanceInstruction(vaaWrongEmitter),
  577. "InvalidGovernanceDataSource"
  578. );
  579. const vaaWrongChain = await createVAAFromUint8Array(
  580. data,
  581. governance.CHAINS.karura,
  582. testGovernanceEmitter,
  583. 1
  584. );
  585. await expectRevertCustomError(
  586. this.pythProxy.executeGovernanceInstruction(vaaWrongChain),
  587. "InvalidGovernanceDataSource"
  588. );
  589. });
  590. it("Make sure governance with only target chain id and 0 work", async function () {
  591. const wrongChainData = new governance.SetValidPeriodInstruction(
  592. governance.CHAINS.solana,
  593. BigInt(10)
  594. ).serialize();
  595. const wrongChainVaa = await createVAAFromUint8Array(
  596. wrongChainData,
  597. testGovernanceChainId,
  598. testGovernanceEmitter,
  599. 1
  600. );
  601. await expectRevertCustomError(
  602. this.pythProxy.executeGovernanceInstruction(wrongChainVaa),
  603. "InvalidGovernanceTarget"
  604. );
  605. const dataForAllChains = new governance.SetValidPeriodInstruction(
  606. governance.CHAINS.unset,
  607. BigInt(10)
  608. ).serialize();
  609. const vaaForAllChains = await createVAAFromUint8Array(
  610. dataForAllChains,
  611. testGovernanceChainId,
  612. testGovernanceEmitter,
  613. 1
  614. );
  615. await this.pythProxy.executeGovernanceInstruction(vaaForAllChains);
  616. const dataForEth = new governance.SetValidPeriodInstruction(
  617. governance.CHAINS.ethereum,
  618. BigInt(10)
  619. ).serialize();
  620. const vaaForEth = await createVAAFromUint8Array(
  621. dataForEth,
  622. testGovernanceChainId,
  623. testGovernanceEmitter,
  624. 2
  625. );
  626. await this.pythProxy.executeGovernanceInstruction(vaaForEth);
  627. });
  628. it("Make sure that governance messages are executed in order and cannot be reused", async function () {
  629. const data = new governance.SetValidPeriodInstruction(
  630. governance.CHAINS.ethereum,
  631. BigInt(10)
  632. ).serialize();
  633. const vaaSeq1 = await createVAAFromUint8Array(
  634. data,
  635. testGovernanceChainId,
  636. testGovernanceEmitter,
  637. 1
  638. );
  639. await this.pythProxy.executeGovernanceInstruction(vaaSeq1),
  640. // Replaying shouldn't work
  641. await expectRevertCustomError(
  642. this.pythProxy.executeGovernanceInstruction(vaaSeq1),
  643. "OldGovernanceMessage"
  644. );
  645. const vaaSeq2 = await createVAAFromUint8Array(
  646. data,
  647. testGovernanceChainId,
  648. testGovernanceEmitter,
  649. 2
  650. );
  651. await this.pythProxy.executeGovernanceInstruction(vaaSeq2),
  652. // Replaying shouldn't work
  653. await expectRevertCustomError(
  654. this.pythProxy.executeGovernanceInstruction(vaaSeq1),
  655. "OldGovernanceMessage"
  656. );
  657. await expectRevertCustomError(
  658. this.pythProxy.executeGovernanceInstruction(vaaSeq2),
  659. "OldGovernanceMessage"
  660. );
  661. });
  662. // Per governance type logic
  663. it("Upgrading the contract with chain id 0 is invalid", async function () {
  664. const newImplementation = await PythUpgradable.new();
  665. const data = new governance.EthereumUpgradeContractInstruction(
  666. governance.CHAINS.unset, // 0
  667. new governance.HexString20Bytes(newImplementation.address)
  668. ).serialize();
  669. const vaa = await createVAAFromUint8Array(
  670. data,
  671. testGovernanceChainId,
  672. testGovernanceEmitter,
  673. 1
  674. );
  675. await expectRevertCustomError(
  676. this.pythProxy.executeGovernanceInstruction(vaa),
  677. "InvalidGovernanceTarget"
  678. );
  679. });
  680. it("Upgrading the contract should work", async function () {
  681. const newImplementation = await PythUpgradable.new();
  682. const data = new governance.EthereumUpgradeContractInstruction(
  683. governance.CHAINS.ethereum,
  684. new governance.HexString20Bytes(newImplementation.address)
  685. ).serialize();
  686. const vaa = await createVAAFromUint8Array(
  687. data,
  688. testGovernanceChainId,
  689. testGovernanceEmitter,
  690. 1
  691. );
  692. const receipt = await this.pythProxy.executeGovernanceInstruction(vaa);
  693. // Couldn't get the oldImplementation address.
  694. expectEvent(receipt, "ContractUpgraded", {
  695. newImplementation: newImplementation.address,
  696. });
  697. expectEvent(receipt, "Upgraded", {
  698. implementation: newImplementation.address,
  699. });
  700. });
  701. it("Upgrading the contract to a non-pyth contract won't work", async function () {
  702. const newImplementation = await MockUpgradeableProxy.new();
  703. const data = new governance.EthereumUpgradeContractInstruction(
  704. governance.CHAINS.ethereum,
  705. new governance.HexString20Bytes(newImplementation.address)
  706. ).serialize();
  707. const vaa = await createVAAFromUint8Array(
  708. data,
  709. testGovernanceChainId,
  710. testGovernanceEmitter,
  711. 1
  712. );
  713. // Calling a non-existing method will cause a revert with no explanation.
  714. await expectRevert(
  715. this.pythProxy.executeGovernanceInstruction(vaa),
  716. "revert"
  717. );
  718. });
  719. it("Transferring governance data source should work", async function () {
  720. const newEmitterAddress =
  721. "0x0000000000000000000000000000000000000000000000000000000000001111";
  722. const newEmitterChain = governance.CHAINS.acala;
  723. const claimInstructionData =
  724. new governance.RequestGovernanceDataSourceTransferInstruction(
  725. governance.CHAINS.unset,
  726. 1
  727. ).serialize();
  728. const claimVaaHexString = await createVAAFromUint8Array(
  729. claimInstructionData,
  730. newEmitterChain,
  731. newEmitterAddress,
  732. 1
  733. );
  734. await expectRevertCustomError(
  735. this.pythProxy.executeGovernanceInstruction(claimVaaHexString),
  736. "InvalidGovernanceDataSource"
  737. );
  738. const claimVaa = Buffer.from(claimVaaHexString.substring(2), "hex");
  739. const data =
  740. new governance.AuthorizeGovernanceDataSourceTransferInstruction(
  741. governance.CHAINS.unset,
  742. claimVaa
  743. ).serialize();
  744. const vaa = await createVAAFromUint8Array(
  745. data,
  746. testGovernanceChainId,
  747. testGovernanceEmitter,
  748. 1
  749. );
  750. const oldGovernanceDataSource = await this.pythProxy.governanceDataSource();
  751. const receipt = await this.pythProxy.executeGovernanceInstruction(vaa);
  752. const newGovernanceDataSource = await this.pythProxy.governanceDataSource();
  753. expectEvent(receipt, "GovernanceDataSourceSet", {
  754. oldDataSource: oldGovernanceDataSource,
  755. newDataSource: newGovernanceDataSource,
  756. });
  757. expect(newGovernanceDataSource.chainId).equal(newEmitterChain.toString());
  758. expect(newGovernanceDataSource.emitterAddress).equal(newEmitterAddress);
  759. // Verifies the data source has changed.
  760. await expectRevertCustomError(
  761. this.pythProxy.executeGovernanceInstruction(vaa),
  762. "InvalidGovernanceDataSource"
  763. );
  764. // Make sure a claim vaa does not get executed
  765. const claimLonely =
  766. new governance.RequestGovernanceDataSourceTransferInstruction(
  767. governance.CHAINS.unset,
  768. 2
  769. ).serialize();
  770. const claimLonelyVaa = await createVAAFromUint8Array(
  771. claimLonely,
  772. newEmitterChain,
  773. newEmitterAddress,
  774. 2
  775. );
  776. await expectRevertCustomError(
  777. this.pythProxy.executeGovernanceInstruction(claimLonelyVaa),
  778. "InvalidGovernanceMessage"
  779. );
  780. // Transfer back the ownership to the old governance data source without increasing
  781. // the governance index should not work
  782. // A wrong vaa that does not move the governance index
  783. const transferBackClaimInstructionDataWrong =
  784. new governance.RequestGovernanceDataSourceTransferInstruction(
  785. governance.CHAINS.unset,
  786. 1 // The same governance data source index => Should fail
  787. ).serialize();
  788. const transferBackClaimVaaHexStringWrong = await createVAAFromUint8Array(
  789. transferBackClaimInstructionDataWrong,
  790. testGovernanceChainId,
  791. testGovernanceEmitter,
  792. 2
  793. );
  794. const transferBackClaimVaaWrong = Buffer.from(
  795. transferBackClaimVaaHexStringWrong.substring(2),
  796. "hex"
  797. );
  798. const transferBackDataWrong =
  799. new governance.AuthorizeGovernanceDataSourceTransferInstruction(
  800. governance.CHAINS.unset,
  801. transferBackClaimVaaWrong
  802. ).serialize();
  803. const transferBackVaaWrong = await createVAAFromUint8Array(
  804. transferBackDataWrong,
  805. newEmitterChain,
  806. newEmitterAddress,
  807. 2
  808. );
  809. await expectRevertCustomError(
  810. this.pythProxy.executeGovernanceInstruction(transferBackVaaWrong),
  811. "OldGovernanceMessage"
  812. );
  813. });
  814. it("Setting data sources should work", async function () {
  815. const data = new governance.SetDataSourcesInstruction(
  816. governance.CHAINS.ethereum,
  817. [
  818. new governance.DataSource(
  819. governance.CHAINS.acala,
  820. new governance.HexString32Bytes(
  821. "0x0000000000000000000000000000000000000000000000000000000000001111"
  822. )
  823. ),
  824. ]
  825. ).serialize();
  826. const vaa = await createVAAFromUint8Array(
  827. data,
  828. testGovernanceChainId,
  829. testGovernanceEmitter,
  830. 1
  831. );
  832. const oldDataSources = await this.pythProxy.validDataSources();
  833. const receipt = await this.pythProxy.executeGovernanceInstruction(vaa);
  834. expectEvent(receipt, "DataSourcesSet", {
  835. oldDataSources: oldDataSources,
  836. newDataSources: await this.pythProxy.validDataSources(),
  837. });
  838. assert.isTrue(
  839. await this.pythProxy.isValidDataSource(
  840. governance.CHAINS.acala,
  841. "0x0000000000000000000000000000000000000000000000000000000000001111"
  842. )
  843. );
  844. assert.isFalse(
  845. await this.pythProxy.isValidDataSource(
  846. testPyth2WormholeChainId,
  847. testPyth2WormholeEmitter
  848. )
  849. );
  850. let rawBatch = generateRawBatchAttestation(100, 100, 1337);
  851. await expectRevertCustomError(
  852. updatePriceFeeds(this.pythProxy, [rawBatch]),
  853. "InvalidUpdateDataSource"
  854. );
  855. await updatePriceFeeds(
  856. this.pythProxy,
  857. [rawBatch],
  858. 0,
  859. governance.CHAINS.acala,
  860. "0x0000000000000000000000000000000000000000000000000000000000001111"
  861. );
  862. });
  863. it("Setting fee should work", async function () {
  864. const data = new governance.SetFeeInstruction(
  865. governance.CHAINS.ethereum,
  866. BigInt(5),
  867. BigInt(3) // 5*10**3 = 5000
  868. ).serialize();
  869. const vaa = await createVAAFromUint8Array(
  870. data,
  871. testGovernanceChainId,
  872. testGovernanceEmitter,
  873. 1
  874. );
  875. const oldFee = await this.pythProxy.singleUpdateFeeInWei();
  876. const receipt = await this.pythProxy.executeGovernanceInstruction(vaa);
  877. expectEvent(receipt, "FeeSet", {
  878. oldFee: oldFee,
  879. newFee: await this.pythProxy.singleUpdateFeeInWei(),
  880. });
  881. assert.equal(await this.pythProxy.singleUpdateFeeInWei(), "5000");
  882. let rawBatch = generateRawBatchAttestation(100, 100, 1337);
  883. await expectRevertCustomError(
  884. updatePriceFeeds(this.pythProxy, [rawBatch], 0),
  885. "InsufficientFee"
  886. );
  887. await updatePriceFeeds(this.pythProxy, [rawBatch], 5000);
  888. });
  889. it("Setting valid period should work", async function () {
  890. const data = new governance.SetValidPeriodInstruction(
  891. governance.CHAINS.ethereum,
  892. BigInt(0)
  893. ).serialize();
  894. const vaa = await createVAAFromUint8Array(
  895. data,
  896. testGovernanceChainId,
  897. testGovernanceEmitter,
  898. 1
  899. );
  900. const oldValidPeriod = await this.pythProxy.validTimePeriodSeconds();
  901. const receipt = await this.pythProxy.executeGovernanceInstruction(vaa);
  902. expectEvent(receipt, "ValidPeriodSet", {
  903. oldValidPeriod: oldValidPeriod,
  904. newValidPeriod: await this.pythProxy.validTimePeriodSeconds(),
  905. });
  906. assert.equal(await this.pythProxy.validTimePeriodSeconds(), "0");
  907. // The behaviour of valid time period is extensively tested before,
  908. // and adding it here will cause more complexity (and is not so short).
  909. });
  910. // Version
  911. it("Make sure version is the npm package version", async function () {
  912. const contractVersion = await this.pythProxy.version();
  913. const { version } = require("../package.json");
  914. expect(contractVersion).equal(version);
  915. });
  916. });
  917. const signAndEncodeVM = async function (
  918. timestamp,
  919. nonce,
  920. emitterChainId,
  921. emitterAddress,
  922. sequence,
  923. data,
  924. signers,
  925. guardianSetIndex,
  926. consistencyLevel
  927. ) {
  928. const body = [
  929. web3.eth.abi.encodeParameter("uint32", timestamp).substring(2 + (64 - 8)),
  930. web3.eth.abi.encodeParameter("uint32", nonce).substring(2 + (64 - 8)),
  931. web3.eth.abi
  932. .encodeParameter("uint16", emitterChainId)
  933. .substring(2 + (64 - 4)),
  934. web3.eth.abi.encodeParameter("bytes32", emitterAddress).substring(2),
  935. web3.eth.abi.encodeParameter("uint64", sequence).substring(2 + (64 - 16)),
  936. web3.eth.abi
  937. .encodeParameter("uint8", consistencyLevel)
  938. .substring(2 + (64 - 2)),
  939. data.substr(2),
  940. ];
  941. const hash = web3.utils.soliditySha3(
  942. web3.utils.soliditySha3("0x" + body.join(""))
  943. );
  944. let signatures = "";
  945. for (let i in signers) {
  946. const ec = new elliptic.ec("secp256k1");
  947. const key = ec.keyFromPrivate(signers[i]);
  948. const signature = key.sign(hash.substr(2), { canonical: true });
  949. const packSig = [
  950. web3.eth.abi.encodeParameter("uint8", i).substring(2 + (64 - 2)),
  951. zeroPadBytes(signature.r.toString(16), 32),
  952. zeroPadBytes(signature.s.toString(16), 32),
  953. web3.eth.abi
  954. .encodeParameter("uint8", signature.recoveryParam)
  955. .substr(2 + (64 - 2)),
  956. ];
  957. signatures += packSig.join("");
  958. }
  959. const vm = [
  960. web3.eth.abi.encodeParameter("uint8", 1).substring(2 + (64 - 2)),
  961. web3.eth.abi
  962. .encodeParameter("uint32", guardianSetIndex)
  963. .substring(2 + (64 - 8)),
  964. web3.eth.abi
  965. .encodeParameter("uint8", signers.length)
  966. .substring(2 + (64 - 2)),
  967. signatures,
  968. body.join(""),
  969. ].join("");
  970. return vm;
  971. };
  972. function zeroPadBytes(value, length) {
  973. while (value.length < 2 * length) {
  974. value = "0" + value;
  975. }
  976. return value;
  977. }
  978. async function createVAAFromUint8Array(
  979. dataBuffer,
  980. emitterChainId,
  981. emitterAddress,
  982. sequence
  983. ) {
  984. const dataHex = "0x" + dataBuffer.toString("hex");
  985. return (
  986. "0x" +
  987. (await signAndEncodeVM(
  988. 0,
  989. 0,
  990. emitterChainId.toString(),
  991. emitterAddress,
  992. sequence,
  993. dataHex,
  994. [testSigner1PK],
  995. 0,
  996. 0
  997. ))
  998. );
  999. }
  1000. // There is no way to check event with given args has not emitted with expectEvent
  1001. // or how many times an event was emitted. This function is implemented to count
  1002. // the matching events and is used for the mentioned purposes.
  1003. function getNumMatchingEvents(receipt, eventName, args) {
  1004. let matchCnt = 0;
  1005. for (let log of receipt.logs) {
  1006. if (log.event === eventName) {
  1007. let match = true;
  1008. for (let argKey in args) {
  1009. if (log.args[argKey].toString() !== args[argKey].toString()) {
  1010. match = false;
  1011. break;
  1012. }
  1013. }
  1014. if (match) {
  1015. matchCnt++;
  1016. }
  1017. }
  1018. }
  1019. return matchCnt;
  1020. }
  1021. function expectEventNotEmittedWithArgs(receipt, eventName, args) {
  1022. const matches = getNumMatchingEvents(receipt, eventName, args);
  1023. assert(
  1024. matches === 0,
  1025. `Expected no matching emitted event. But found ${matches}.`
  1026. );
  1027. }
  1028. function expectEventMultipleTimes(receipt, eventName, args, cnt) {
  1029. const matches = getNumMatchingEvents(receipt, eventName, args);
  1030. assert(matches === cnt, `Expected ${cnt} event matches, found ${matches}.`);
  1031. }
  1032. async function expectRevertCustomError(promise, reason) {
  1033. try {
  1034. await promise;
  1035. expect.fail("Expected promise to throw but it didn't");
  1036. } catch (revert) {
  1037. if (reason) {
  1038. const reasonId = web3.utils.keccak256(reason + "()").substr(0, 10);
  1039. expect(
  1040. JSON.stringify(revert),
  1041. `Expected custom error ${reason} (${reasonId})`
  1042. ).to.include(reasonId);
  1043. }
  1044. }
  1045. }