Best JavaScript code snippet using tracetest
proof_generation_utils.js
Source:proof_generation_utils.js
1// Copyright 2019 OpenST Ltd.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//15// ----------------------------------------------------------------------------16//17// http://www.simpletoken.org/18//19// ----------------------------------------------------------------------------20const TestLibUtils = require('../test/test_lib/utils.js');21const Gateway = require('./helper/gateway');22const CoGateway = require('./helper/co_gateway');23/**24 * Object contains input parameter for confirmStakingIntent.25 *26 * @typedef {Object} StakeParams27 * @property {string} staker Staker address.28 * @property {string} nonce Staker nonce.29 * @property {string} beneficiary Beneficiary address.30 * @property {string} amount Stake amount.31 * @property {string} gasPrice Gas price.32 * @property {string} gasLimit Gas limit.33 * @property {string} hashLock Hash lock34 * @property {string} blockHeight Block height.35 * @property {string} rlpParentNodes RLP encoded proof data.36 * @property {string} unlockSecret Unlock secret.37 * @property {string} facilitator Facilitator address.38 * @property {string} storageRoot Storage root for proof.39 */40/**41 * Object contains input parameter needed for confirmRedeemIntent.42 *43 * @typedef {object} RedeemParams44 * @property {string} redeemer Redeemer address.45 * @property {string} redeemerNonce Redeemer nonce.46 * @property {string} beneficiary Address where the redeemed tokens47 * will be transferred.48 * @property {string} amount Redeem amount.49 * @property {string} gasPrice Gas price that redeemer is ready to pay to50 * get the redeem and unstake process done.51 * @property {string} gasLimit Gas limit that redeemer is ready to pay.52 * @property {string} blockHeight Block number for which the proof is valid.53 * @property {string} hashLock Hash lock.54 * @property {string} rlpParentNodes RLP encoded proof data.55 * @property {string} storageRoot Storage root for proof.56 * @property {string} facilitator Facilitator address for progress mint.57 */58/**59 * The class encapsulates data collection logic for different flows of stake & mint60 * and redeem & unstake.61 */62class ProofGenerationUtils {63 /**64 * Constructor65 *66 * @param registeredContracts {object} Deployed contracts.67 * @param stakeParams {StakeParams} Contains data needed for staking.68 * @param redeemParams {RedeemParams} Contains data needed for redeeming.69 * @param proofUtils {object} Proof utils object.70 */71 constructor(registeredContracts, stakeParams, redeemParams, proofUtils) {72 this.registeredContracts = registeredContracts;73 this.gateway = new Gateway(registeredContracts);74 this.coGateway = new CoGateway(registeredContracts);75 this.stakeParams = stakeParams;76 this.redeemParams = redeemParams;77 this.proofUtils = proofUtils;78 this.resetProofData();79 }80 /**81 * Get address of all deployed contracts.82 *83 * @returns {Object} An object containing the deployed contract address.84 */85 getContractAddresses() {86 const addresses = {};87 Object.keys(this.registeredContracts).map((key) => {88 if (this.registeredContracts[key].address) {89 addresses[key] = this.registeredContracts[key].address;90 }91 });92 return addresses;93 }94 /**95 * Resets proof data variable.96 */97 resetProofData() {98 this.proofData = {};99 }100 /**101 * Initialize proof data with default data.102 *103 * @returns {Promise<void>}104 */105 async initializeProofData() {106 this.proofData.contracts = this.getContractAddresses(this.registeredContracts);107 this.proofData.gateway = {};108 this.proofData.gateway.constructor = await this.gateway.getConstructorParams();109 this.proofData.co_gateway = {};110 this.proofData.co_gateway.constructor = await this.coGateway.getConstructorParams();111 this.messageBoxOffset = await this.gateway.getMessageBoxOffset();112 }113 /**114 * Populates proof data after calling stake.115 *116 * @returns {Promise<{stakeProofData, stakeResult: void}>}117 */118 async populateStakeProofData() {119 const generatedHashLock = TestLibUtils.generateHashLock();120 this.stakeParams.hashLock = generatedHashLock.l;121 this.stakeParams.unlockSecret = generatedHashLock.s;122 const stakeResult = await this.gateway.stake(this.stakeParams);123 const stakeProofData = await this.proofUtils.getOutboxProof(124 this.gateway.address,125 [stakeResult.returned_value.messageHash_],126 this.messageBoxOffset,127 );128 const stake = {};129 stake.params = this.stakeParams;130 stake.return_value = stakeResult;131 stake.proof_data = stakeProofData;132 this.proofData.gateway.stake = stake;133 return {134 stakeProofData,135 stakeResult,136 };137 }138 /**139 * Populates proof data after calling confirmStakingIntent.140 *141 * @param stakeProofData {object} Contains proof data after calling stake.142 *143 * @returns {Promise<{confirmStakeIntentResult}>}144 */145 async populateConfirmStakeIntentProofData(stakeProofData) {146 const confirmStakeIntentParams = Object.assign({}, this.stakeParams);147 confirmStakeIntentParams.blockHeight = stakeProofData.block_number;148 confirmStakeIntentParams.rlpParentNodes = stakeProofData.storageProof[0].serializedProof;149 confirmStakeIntentParams.facilitator = this.stakeParams.staker;150 confirmStakeIntentParams.storageRoot = stakeProofData.storageHash;151 // confirmStakeIntent also sets/anchors storage root for a block number.152 const confirmStakeIntentResult = await this.coGateway.confirmStakeIntent(153 confirmStakeIntentParams,154 );155 const confirmStakeIntentProofData = await this.proofUtils.getInboxProof(156 this.coGateway.address,157 [confirmStakeIntentResult.returned_value.messageHash_],158 this.messageBoxOffset,159 );160 const confirmStakeIntent = {};161 confirmStakeIntent.params = confirmStakeIntentParams;162 confirmStakeIntent.return_value = confirmStakeIntentResult;163 confirmStakeIntent.proof_data = confirmStakeIntentProofData;164 this.proofData.co_gateway.confirm_stake_intent = confirmStakeIntent;165 return {166 confirmStakeIntentResult,167 };168 }169 /**170 * Populates proof data after calling progressStake.171 *172 * @param stakeResult {object} Result after calling staking.173 * @param confirmStakeIntentResult {object} Result after calling confirmStakeIntent174 *175 * @returns {Promise<{progressStakeParams}>}176 */177 async populateProgressStakeProofData(stakeResult, confirmStakeIntentResult) {178 const progressStakeParams = {};179 progressStakeParams.messageHash = stakeResult.returned_value.messageHash_;180 progressStakeParams.unlockSecret = this.stakeParams.unlockSecret;181 progressStakeParams.facilitator = this.stakeParams.staker;182 const progressStakeResult = await this.gateway.progressStake(progressStakeParams);183 const progressStakeProofData = await this.proofUtils.getOutboxProof(184 this.gateway.address,185 [confirmStakeIntentResult.returned_value.messageHash_],186 this.messageBoxOffset,187 );188 const progressStake = {};189 progressStake.params = progressStakeParams;190 progressStake.return_value = progressStakeResult;191 progressStake.proof_data = progressStakeProofData;192 this.proofData.gateway.progress_stake = progressStake;193 return {194 progressStakeParams,195 };196 }197 /**198 * Populates proof data after calling progressMint.199 *200 * @param progressStakeParams {StakeParams} Contains data needed for progressStake.201 * @param confirmStakeIntentResult {object} Result after calling confirmStakeIntent.202 *203 * @returns {Promise<void>}204 */205 async populateProgressMintProofData(206 progressStakeParams,207 confirmStakeIntentResult,208 ) {209 const progressMintParams = Object.assign({}, progressStakeParams);210 const progressMintResult = await this.coGateway.progressMint(progressMintParams);211 const progressMintProofData = await this.proofUtils.getInboxProof(212 this.coGateway.address,213 [confirmStakeIntentResult.returned_value.messageHash_],214 this.messageBoxOffset,215 );216 const progressMint = {};217 progressMint.params = progressMintParams;218 progressMint.return_value = progressMintResult;219 progressMint.proof_data = progressMintProofData;220 this.proofData.co_gateway.progress_mint = progressMint;221 }222 /**223 * Populates proof data after calling revert stake.224 *225 * @param stakeResult {object} Result after calling stake.226 * @param confirmStakeIntentResult {object} Result after calling confirmStakeIntent.227 *228 * @returns {Promise<{revertStakeProofData, revertStakeParams}>}229 */230 async populateRevertStakeProofData(stakeResult, confirmStakeIntentResult) {231 const revertStakeParams = {};232 revertStakeParams.messageHash = confirmStakeIntentResult.returned_value.messageHash_;233 revertStakeParams.staker = this.stakeParams.staker;234 const revertStakeResult = await this.gateway.revertStake(revertStakeParams);235 const revertStakeProofData = await this.proofUtils.getOutboxProof(236 this.gateway.address,237 [stakeResult.returned_value.messageHash_],238 this.messageBoxOffset,239 );240 const revertStake = {};241 revertStake.params = revertStakeParams;242 revertStake.return_value = revertStakeResult;243 revertStake.proof_data = revertStakeProofData;244 this.proofData.gateway.revert_stake = revertStake;245 return {246 revertStakeProofData,247 revertStakeParams,248 };249 }250 /**251 * Populates proof data after calling confirm revert stake.252 *253 * @param revertStakeParams {StakeParams} Contains revert stake parameters.254 * @param revertStakeProofData {object} Contains revert stake proof data.255 *256 * @returns {Promise<{confirmRevertStakeProofData}>}257 */258 async populateConfirmRevertStakeProofData(revertStakeParams, revertStakeProofData) {259 const confirmRevertStakeParams = {};260 confirmRevertStakeParams.messageHash = revertStakeParams.messageHash;261 confirmRevertStakeParams.blockHeight = revertStakeProofData.block_number;262 confirmRevertStakeParams.rlpParentNodes = revertStakeProofData263 .storageProof[0].serializedProof;264 confirmRevertStakeParams.facilitator = this.stakeParams.staker;265 confirmRevertStakeParams.storageRoot = revertStakeProofData.storageHash;266 const confirmRevertStakeResult = await this.coGateway.confirmRevertStakeIntent(267 confirmRevertStakeParams,268 );269 const confirmRevertStakeProofData = await this.proofUtils.getInboxProof(270 this.coGateway.address,271 [confirmRevertStakeParams.messageHash],272 this.messageBoxOffset,273 );274 const confirmRevertStakeIntent = {};275 confirmRevertStakeIntent.params = confirmRevertStakeParams;276 confirmRevertStakeIntent.return_value = confirmRevertStakeResult;277 confirmRevertStakeIntent.proof_data = confirmRevertStakeProofData;278 this.proofData.co_gateway.confirm_revert_stake_intent = confirmRevertStakeIntent;279 return {280 confirmRevertStakeProofData,281 };282 }283 /**284 * Populates proof data after calling progress revert stake.285 *286 * @param revertStakeParams {StakeParams} Contains revert stake data.287 * @param confirmRevertStakeProofData {object} Contains confirm revert stake proof data.288 *289 * @returns {Promise<void>}290 */291 async populateProgressRevertStakeProofData(revertStakeParams, confirmRevertStakeProofData) {292 const progressRevertStakeParams = {};293 progressRevertStakeParams.messageHash = revertStakeParams.messageHash;294 progressRevertStakeParams.blockHeight = confirmRevertStakeProofData.block_number;295 progressRevertStakeParams.rlpParentNodes = confirmRevertStakeProofData296 .storageProof[0].serializedProof;297 progressRevertStakeParams.facilitator = this.stakeParams.staker;298 progressRevertStakeParams.storageRoot = confirmRevertStakeProofData.storageHash;299 const progressRevertStakeResult = await this.gateway.progressRevertStake(300 progressRevertStakeParams,301 );302 const progressRevertStakeProofData = await this.proofUtils.getOutboxProof(303 this.gateway.address,304 [progressRevertStakeParams.messageHash],305 this.messageBoxOffset,306 );307 const progressRevertStakeIntent = {};308 progressRevertStakeIntent.params = progressRevertStakeParams;309 progressRevertStakeIntent.return_value = progressRevertStakeResult;310 progressRevertStakeIntent.proof_data = progressRevertStakeProofData;311 this.proofData.gateway.progress_revert_stake_intent = progressRevertStakeIntent;312 }313 /**314 * Populates proof data after calling redeem.315 *316 * @returns {Promise<{redeemProofData, redeemResult}>}317 */318 async populateRedeemProofData() {319 const generatedHashLock = TestLibUtils.generateHashLock();320 this.redeemParams.hashLock = generatedHashLock.l;321 this.redeemParams.unlockSecret = generatedHashLock.s;322 const redeemResult = await this.coGateway.redeem(this.redeemParams);323 const redeemProofData = await this.proofUtils.getOutboxProof(324 this.coGateway.address,325 [redeemResult.returned_value.messageHash_],326 this.messageBoxOffset,327 );328 const redeem = {};329 redeem.params = this.redeemParams;330 redeem.return_value = redeemResult;331 redeem.proof_data = redeemProofData;332 this.proofData.co_gateway.redeem = redeem;333 return {334 redeemProofData,335 redeemResult,336 };337 }338 /**339 * Contains proof data after calling confirm redeem intent.340 *341 * @param redeemProofData {object} Contains redeem proof data.342 *343 * @returns {Promise<{confirmRedeemIntentResult}>}344 */345 async populateConfirmRedeemIntentProofData(redeemProofData) {346 const confirmRedeemIntentParams = Object.assign({}, this.redeemParams);347 confirmRedeemIntentParams.blockNumber = redeemProofData.block_number;348 confirmRedeemIntentParams.storageProof = redeemProofData.storageProof[0].serializedProof;349 confirmRedeemIntentParams.facilitator = redeemProofData.staker;350 confirmRedeemIntentParams.storageRoot = redeemProofData.storageHash;351 confirmRedeemIntentParams.facilitator = this.redeemParams.redeemer;352 // confirmRedeemIntent also anchors/sets storage root.353 const confirmRedeemIntentResult = await this.gateway.confirmRedeemIntent(354 confirmRedeemIntentParams,355 );356 const confirmRedeemIntentProofData = await this.proofUtils.getInboxProof(357 this.gateway.address,358 [confirmRedeemIntentResult.returned_value.messageHash_],359 this.messageBoxOffset,360 );361 const confirmRedeemIntent = {};362 confirmRedeemIntent.params = confirmRedeemIntentParams;363 confirmRedeemIntent.return_value = confirmRedeemIntentResult;364 confirmRedeemIntent.proof_data = confirmRedeemIntentProofData;365 this.proofData.gateway.confirm_redeem_intent = confirmRedeemIntent;366 return {367 confirmRedeemIntentResult,368 };369 }370 /**371 * Populates proof data after calling progress redeem.372 *373 * @param confirmRedeemIntentResult {object} Result after calling confirm redeem intent.374 *375 * @returns {Promise<{progressRedeemParams}>}376 */377 async populateProgressRedeemProofData(confirmRedeemIntentResult) {378 const progressRedeemParams = {};379 progressRedeemParams.messageHash = confirmRedeemIntentResult.returned_value.messageHash_;380 progressRedeemParams.unlockSecret = this.redeemParams.unlockSecret;381 progressRedeemParams.facilitator = this.redeemParams.redeemer;382 const progressRedeemResult = await this.coGateway.progressRedeem(383 progressRedeemParams,384 );385 const progressRedeemProofData = await this.proofUtils.getOutboxProof(386 this.coGateway.address,387 [progressRedeemParams.messageHash],388 this.messageBoxOffset,389 );390 const progressRedeem = {};391 progressRedeem.params = progressRedeemParams;392 progressRedeem.return_value = progressRedeemResult;393 progressRedeem.proof_data = progressRedeemProofData;394 this.proofData.co_gateway.progress_redeem = progressRedeem;395 return {396 progressRedeemParams,397 };398 }399 /**400 * Populates proof data after calling progress unstake.401 *402 * @param progressRedeemParams {RedeemParams} Contains data needed for progress redeem.403 *404 * @returns {Promise<void>}405 */406 async populateProgressUnstakeProofData(progressRedeemParams) {407 const progressUnstakeParams = Object.assign({}, progressRedeemParams);408 progressUnstakeParams.unstakeAmount = this.redeemParams.amount;409 const progressUnstakeResult = await this.gateway.progressUnstake(410 progressUnstakeParams,411 );412 const progressUnstakeProofData = await this.proofUtils.getInboxProof(413 this.gateway.address,414 [progressUnstakeParams.messageHash],415 this.messageBoxOffset,416 );417 const progressUnstake = {};418 progressUnstake.params = progressUnstakeParams;419 progressUnstake.return_value = progressUnstakeResult;420 progressUnstake.proof_data = progressUnstakeProofData;421 this.proofData.gateway.progress_unstake = progressUnstake;422 }423 /**424 * Populates proof data after calling revert redeem.425 *426 * @param redeemResult {object} Result after calling redeem.427 *428 * @returns {Promise<{revertRedeemProofData, revertRedeemResult, revertRedeemParams}>}429 */430 async populateRevertRedeemProofData(redeemResult) {431 const revertRedeemParams = {};432 revertRedeemParams.messageHash = redeemResult.returned_value.messageHash_;433 revertRedeemParams.redeemer = this.redeemParams.redeemer;434 const revertRedeemResult = await this.coGateway.revertRedeem(435 revertRedeemParams,436 );437 const revertRedeemProofData = await this.proofUtils.getOutboxProof(438 this.coGateway.address,439 [revertRedeemParams.messageHash],440 this.messageBoxOffset,441 );442 const revertRedeem = {};443 revertRedeem.params = revertRedeemParams;444 revertRedeem.return_value = revertRedeemResult;445 revertRedeem.proof_data = revertRedeemProofData;446 this.proofData.co_gateway.revert_redeem = revertRedeem;447 return {448 revertRedeemProofData,449 revertRedeemResult,450 revertRedeemParams,451 };452 }453 /**454 * Populates proof data after calling confirm revert redeem.455 *456 * @param revertRedeemParams {RedeemParams} Contains data needed for calling revert redeem.457 * @param revertRedeemProofData {object} Contains revert redeem proof data.458 *459 * @returns {Promise<{confirmRevertRedeemProofData, confirmRevertRedeemIntentParams}>}460 */461 async populateConfirmRevertRedeemProofData(462 revertRedeemParams,463 revertRedeemProofData,464 ) {465 const confirmRevertRedeemIntentParams = {};466 confirmRevertRedeemIntentParams.messageHash = revertRedeemParams.messageHash;467 confirmRevertRedeemIntentParams.blockNumber = revertRedeemProofData.block_number;468 confirmRevertRedeemIntentParams.rlpParentNodes = revertRedeemProofData469 .storageProof[0].serializedProof;470 confirmRevertRedeemIntentParams.facilitator = this.redeemParams.redeemer;471 confirmRevertRedeemIntentParams.storageRoot = revertRedeemProofData.storageHash;472 const confirmRevertRedeemResult = await this.gateway.confirmRevertRedeemIntent(473 confirmRevertRedeemIntentParams,474 );475 const confirmRevertRedeemProofData = await this.proofUtils.getInboxProof(476 this.gateway.address,477 [confirmRevertRedeemIntentParams.messageHash],478 this.messageBoxOffset,479 );480 const confirmRevertRedeemIntent = {};481 confirmRevertRedeemIntent.params = confirmRevertRedeemIntentParams;482 confirmRevertRedeemIntent.return_value = confirmRevertRedeemResult;483 confirmRevertRedeemIntent.proof_data = confirmRevertRedeemProofData;484 this.proofData.gateway.confirm_revert_redeem_intent = confirmRevertRedeemIntent;485 return {486 confirmRevertRedeemProofData,487 confirmRevertRedeemIntentParams,488 };489 }490 /**491 * Populates proof data after calling progress revert redeem.492 *493 * @param revertRedeemParams {RedeemParams} Contains data needed for calling revert redeem.494 * @param confirmRevertRedeemProofData {object} Contains revert redeem proof data.495 *496 * @returns {Promise<void>}497 */498 async populateProgressRevertRedeemProofData(499 revertRedeemParams,500 confirmRevertRedeemProofData,501 ) {502 const progressRevertRedeemParams = {};503 progressRevertRedeemParams.messageHash = revertRedeemParams.messageHash;504 progressRevertRedeemParams.blockHeight = confirmRevertRedeemProofData.block_number;505 progressRevertRedeemParams.rlpParentNodes = confirmRevertRedeemProofData506 .storageProof[0].serializedProof;507 progressRevertRedeemParams.facilitator = this.redeemParams.redeemer;508 progressRevertRedeemParams.storageRoot = confirmRevertRedeemProofData.storageHash;509 const progressRevertRedeemResult = await this.coGateway.progressRevertRedeem(510 progressRevertRedeemParams,511 );512 const progressRevertRedeemProofData = await this.proofUtils.getOutboxProof(513 this.coGateway.address,514 [progressRevertRedeemParams.messageHash],515 this.messageBoxOffset,516 );517 const progressRevertRedeem = {};518 progressRevertRedeem.params = progressRevertRedeemParams;519 progressRevertRedeem.return_value = progressRevertRedeemResult;520 progressRevertRedeem.proof_data = progressRevertRedeemProofData;521 this.proofData.co_gateway.progress_revert_redeem = progressRevertRedeem;522 }523}...
progress_revert_redeem.js
Source:progress_revert_redeem.js
1// Copyright 2019 OpenST Ltd.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//15// ----------------------------------------------------------------------------16//17// http://www.simpletoken.org/18//19// ----------------------------------------------------------------------------20const EIP20CoGateway = artifacts.require('TestEIP20CoGateway');21const MockUtilityToken = artifacts.require('MockUtilityToken');22const BN = require('bn.js');23const config = require('../../test_lib/config.js');24const messageBus = require('../../test_lib/message_bus.js');25const Utils = require('../../test_lib/utils.js');26const web3 = require('../../test_lib/web3.js');27const EventDecoder = require('../../test_lib/event_decoder');28const CoGatewayUtils = require('./helpers/co_gateway_utils.js');29const StubData = require('../../../test/data/redeem_revoked_0.json');30const ZeroBytes = Utils.ZERO_BYTES32;31const { MessageStatusEnum } = messageBus;32const PENALTY_MULTIPLIER = 1.5;33contract('EIP20CoGateway.progressRevertRedeem()', (accounts) => {34 let utilityToken;35 let cogateway;36 let revertRedeemParams;37 let bountyAmount;38 let penaltyAmount;39 let owner;40 let facilitator;41 beforeEach(async () => {42 owner = accounts[0];43 facilitator = accounts[1];44 const redeemRequest = StubData.co_gateway.redeem.params;45 const confirmRedeemRequest = StubData.gateway.confirm_revert_redeem_intent;46 revertRedeemParams = {47 redeemer: redeemRequest.redeemer,48 amount: new BN(redeemRequest.amount, 16),49 beneficiary: redeemRequest.beneficiary,50 gasPrice: new BN(redeemRequest.gasPrice, 16),51 gasLimit: new BN(redeemRequest.gasLimit, 16),52 nonce: new BN(redeemRequest.nonce, 16),53 hashLock: redeemRequest.hashLock,54 rlpParentNodes:55 confirmRedeemRequest.proof_data.storageProof[0].serializedProof,56 blockHeight: new BN(confirmRedeemRequest.proof_data.block_number, 16),57 storageRoot: confirmRedeemRequest.proof_data.storageHash,58 messageStatus: MessageStatusEnum.Declared,59 };60 const token = accounts[9];61 const symbol = 'DUM';62 const name = 'Dummy';63 const organization = accounts[2];64 utilityToken = await MockUtilityToken.new(65 token,66 symbol,67 name,68 config.decimals,69 organization,70 { from: owner },71 );72 bountyAmount = new BN(StubData.co_gateway.constructor.bounty);73 penaltyAmount = bountyAmount.muln(PENALTY_MULTIPLIER);74 cogateway = await EIP20CoGateway.new(75 StubData.co_gateway.constructor.valueToken,76 utilityToken.address,77 StubData.co_gateway.constructor.stateRootProvider,78 bountyAmount,79 StubData.co_gateway.constructor.organization,80 StubData.co_gateway.constructor.gateway,81 accounts[8], // burner82 new BN(100),83 );84 await setupContractPreCondition(85 revertRedeemParams,86 cogateway,87 accounts,88 bountyAmount,89 penaltyAmount,90 utilityToken,91 owner,92 );93 await cogateway.setStorageRoot(94 revertRedeemParams.blockHeight,95 revertRedeemParams.storageRoot,96 );97 });98 it('should progress revert redeem', async () => {99 await cogateway.progressRevertRedeem(100 revertRedeemParams.messageHash,101 revertRedeemParams.blockHeight,102 revertRedeemParams.rlpParentNodes,103 );104 });105 it('should return correct response', async () => {106 const response = await cogateway.progressRevertRedeem.call(107 revertRedeemParams.messageHash,108 revertRedeemParams.blockHeight,109 revertRedeemParams.rlpParentNodes,110 );111 assert.strictEqual(112 response.redeemer_,113 revertRedeemParams.redeemer,114 `Expected redeemer ${115 revertRedeemParams.redeemer116 } is different from redeemer from 117 event ${response.redeemer_}`,118 );119 assert.strictEqual(120 response.redeemerNonce_.eq(revertRedeemParams.nonce),121 true,122 `Expected stakerNonce ${revertRedeemParams.nonce.toString(123 10,124 )} is different from nonce from 125 event ${response.redeemerNonce_.toString(10)}`,126 );127 assert.strictEqual(128 response.amount_.eq(revertRedeemParams.amount),129 true,130 `Expected amount ${revertRedeemParams.amount.toString(131 10,132 )} is different from amount from 133 event ${response.amount_.toString(10)}`,134 );135 });136 it('should emit `RedeemReverted` event', async () => {137 const tx = await cogateway.progressRevertRedeem(138 revertRedeemParams.messageHash,139 revertRedeemParams.blockHeight,140 revertRedeemParams.rlpParentNodes,141 );142 const event = EventDecoder.getEvents(tx, cogateway);143 const eventData = event.RedeemReverted;144 assert.isDefined(145 event.RedeemReverted,146 'Event `RedeemReverted` must be emitted.',147 );148 assert.strictEqual(149 eventData._messageHash,150 revertRedeemParams.messageHash,151 `Message hash from the event must be equal to ${152 revertRedeemParams.messageHash153 }.`,154 );155 assert.strictEqual(156 eventData._redeemer,157 revertRedeemParams.redeemer,158 `Redeemer address from the event must be equal to ${159 revertRedeemParams.redeemer160 }.`,161 );162 assert.strictEqual(163 eventData._redeemerNonce.eq(revertRedeemParams.nonce),164 true,165 `Redeemer nonce from the event ${eventData._redeemerNonce.toString(10)}166 must be equal to ${revertRedeemParams.nonce.toString(10)}.`,167 );168 assert.strictEqual(169 eventData._amount.eq(revertRedeemParams.amount),170 true,171 `Redeem amount from the event ${eventData._amount.toString(10)} 172 must be equal to ${revertRedeemParams.amount.toString(10)}.`,173 );174 });175 it('should burn bounty', async () => {176 const burnerAddress = await cogateway.burner.call();177 const cogatewayInitialTokenBalance = await Utils.getBalance(178 cogateway.address,179 );180 const redeemerInitialTokenBalance = await Utils.getBalance(181 revertRedeemParams.redeemer,182 );183 const burnerInitialTokenBalance = await Utils.getBalance(burnerAddress);184 await cogateway.progressRevertRedeem(185 revertRedeemParams.messageHash,186 revertRedeemParams.blockHeight,187 revertRedeemParams.rlpParentNodes,188 );189 const cogatewayFinalTokenBalance = await Utils.getBalance(190 cogateway.address,191 );192 const redeemerFinalTokenBalance = await Utils.getBalance(193 revertRedeemParams.redeemer,194 );195 const burnerFinalTokenBalance = await Utils.getBalance(burnerAddress);196 const expectedCoGatewayBalance = cogatewayInitialTokenBalance.sub(197 bountyAmount,198 );199 assert.strictEqual(200 cogatewayFinalTokenBalance.eq(expectedCoGatewayBalance),201 true,202 `CoGateway final balance ${cogatewayFinalTokenBalance.toString(10)} 203 must be equal to ${expectedCoGatewayBalance.toString(10)}.`,204 );205 assert.strictEqual(206 redeemerFinalTokenBalance.eq(redeemerInitialTokenBalance),207 true,208 `Redeemer final balance ${redeemerFinalTokenBalance.toString(10)} must 209 be equal to ${redeemerInitialTokenBalance.toString(10)}.`,210 );211 const expectedBurnerBalance = burnerInitialTokenBalance.add(212 bountyAmount,213 );214 assert.strictEqual(215 burnerFinalTokenBalance.eq(expectedBurnerBalance),216 true,217 `Burner final balance ${burnerFinalTokenBalance.toString(10)} 218 must be equal to ${expectedBurnerBalance.toString(10)}.`,219 );220 });221 it('should transfer ERC20 redeem amount to redeemer', async () => {222 const burnerAddress = await cogateway.burner.call();223 const cogatewayInitialTokenBalance = await utilityToken.balanceOf(224 cogateway.address,225 );226 const redeemerInitialTokenBalance = await utilityToken.balanceOf(227 revertRedeemParams.redeemer,228 );229 const burnerInitialTokenBalance = await utilityToken.balanceOf(230 burnerAddress,231 );232 await cogateway.progressRevertRedeem(233 revertRedeemParams.messageHash,234 revertRedeemParams.blockHeight,235 revertRedeemParams.rlpParentNodes,236 );237 const cogatewayFinalTokenBalance = await utilityToken.balanceOf(238 cogateway.address,239 );240 const redeemerFinalTokenBalance = await utilityToken.balanceOf(241 revertRedeemParams.redeemer,242 );243 const burnerFinalTokenBalance = await utilityToken.balanceOf(244 burnerAddress,245 );246 const coGatewayExpectedBalance = cogatewayInitialTokenBalance.sub(247 revertRedeemParams.amount,248 );249 assert.strictEqual(250 cogatewayFinalTokenBalance.eq(coGatewayExpectedBalance),251 true,252 `Gateway final balance ${cogatewayFinalTokenBalance.toString(10)} 253 must be equal to ${coGatewayExpectedBalance.toString(10)}.`,254 );255 const expectedRedeemerBalance = redeemerInitialTokenBalance.add(256 revertRedeemParams.amount,257 );258 assert.strictEqual(259 redeemerFinalTokenBalance.eq(expectedRedeemerBalance),260 true,261 `Redeemer final balance ${redeemerFinalTokenBalance.toString(10)} 262 must be equal to ${expectedRedeemerBalance.toString(10)}.`,263 );264 assert.strictEqual(265 burnerFinalTokenBalance.eq(burnerInitialTokenBalance),266 true,267 `Burner final balance ${burnerFinalTokenBalance.toString(10)} 268 must be equal to ${burnerInitialTokenBalance.toString(10)}.`,269 );270 });271 it('should fail when message hash is zero', async () => {272 await Utils.expectRevert(273 cogateway.progressRevertRedeem(274 ZeroBytes,275 revertRedeemParams.blockHeight,276 revertRedeemParams.rlpParentNodes,277 ),278 'Message hash must not be zero.',279 );280 });281 it('should fail when storage proof zero', async () => {282 await Utils.expectRevert(283 cogateway.progressRevertRedeem(284 revertRedeemParams.messageHash,285 revertRedeemParams.blockHeight,286 '0x',287 ),288 'RLP parent nodes must not be zero.',289 );290 });291 it('should fail when storage proof is invalid', async () => {292 await Utils.expectRevert(293 cogateway.progressRevertRedeem(294 revertRedeemParams.messageHash,295 revertRedeemParams.blockHeight,296 '0x1245',297 ),298 'VM Exception while processing transaction: revert',299 );300 });301 it('should fail when storage root is not committed for given block height', async () => {302 await Utils.expectRevert(303 cogateway.progressRevertRedeem(304 revertRedeemParams.messageHash,305 revertRedeemParams.blockHeight.addn(1),306 revertRedeemParams.rlpParentNodes,307 ),308 'Storage root must not be zero.',309 );310 });311 it('should fail when message is undeclared', async () => {312 await Utils.expectRevert(313 cogateway.progressRevertRedeem(314 web3.utils.sha3('dummy'),315 revertRedeemParams.blockHeight,316 revertRedeemParams.rlpParentNodes,317 ),318 'RedeemIntentHash must not be zero.',319 );320 });321 it('should fail when message is progressed', async () => {322 await cogateway.setOutboxStatus(323 revertRedeemParams.messageHash,324 MessageStatusEnum.Progressed,325 );326 await Utils.expectRevert(327 cogateway.progressRevertRedeem(328 revertRedeemParams.messageHash,329 revertRedeemParams.blockHeight,330 revertRedeemParams.rlpParentNodes,331 ),332 'Message status on source must be DeclaredRevocation.',333 );334 });335 it('should fail when target chain merkle proof verification failed', async () => {336 const blockHeight = new BN(337 StubData.co_gateway.redeem.proof_data.block_number,338 16,339 );340 const storageRoot = StubData.co_gateway.redeem.proof_data.storageHash;341 await cogateway.setStorageRoot(blockHeight, storageRoot);342 await Utils.expectRevert(343 cogateway.progressRevertRedeem(344 revertRedeemParams.messageHash,345 blockHeight,346 StubData.co_gateway.redeem.proof_data.storageProof[0].serializedProof,347 ),348 'Merkle proof verification failed.',349 );350 });351});352async function setupContractPreCondition(353 revertRedeemParams,354 cogateway,355 accounts,356 bountyAmount,357 penaltyAmount,358 utilityToken,359 owner,360) {361 const redeemIntentHash = CoGatewayUtils.hashRedeemIntent(362 revertRedeemParams.amount,363 revertRedeemParams.beneficiary,364 StubData.contracts.coGateway,365 );366 const messageHash = messageBus.messageDigest(367 redeemIntentHash,368 revertRedeemParams.nonce,369 revertRedeemParams.gasPrice,370 revertRedeemParams.gasLimit,371 revertRedeemParams.redeemer,372 revertRedeemParams.hashLock,373 );374 await cogateway.setMessage(375 redeemIntentHash,376 revertRedeemParams.nonce,377 revertRedeemParams.gasPrice,378 revertRedeemParams.gasLimit,379 revertRedeemParams.redeemer,380 revertRedeemParams.hashLock,381 );382 revertRedeemParams.messageHash = messageHash;383 await cogateway.setRedeem(384 revertRedeemParams.messageHash,385 revertRedeemParams.beneficiary,386 revertRedeemParams.amount,387 );388 // Send penalty and bounty to co-gateway.389 await web3.eth.sendTransaction({390 to: cogateway.address,391 from: accounts[0],392 value: bountyAmount.add(penaltyAmount),393 });394 // Set co-gateway to owner so that increase supply can be called.395 await utilityToken.setCoGatewayAddress(owner);396 // Send redeem amount to co-gateway.397 await utilityToken.increaseSupply(398 cogateway.address,399 revertRedeemParams.amount,400 { from: owner },401 );402 await utilityToken.setCoGatewayAddress(cogateway.address);403 await cogateway.setOutboxStatus(404 revertRedeemParams.messageHash,405 MessageStatusEnum.DeclaredRevocation,406 );...
user.js
Source:user.js
1// åå§åè·¯ç±å¯¹è±¡2const express = require('express')3const router = express.Router()4// å¼å
¥ç¨æ·è¡¨5var User = require('../models/list/user') 6// // å¼å
¥éªè¯ç 表7var Code = require('../models/list/code')8// å¼å
¥å·¥å
·9// åééªè¯ç çæ¹æ³10var { sendCode } = require('../public/js/sendCode')11var { resRevert } = require('../public/js/resRevert')12// å¼å
¥æ£å13var { emailRegex, pwdRegex } = require('../public/js/getRegex')14// å¼å
¥md5å å¯15var { encrypt } = require('../public/js/cryptoHandle')16// éªè¯ç 17router.post('/sendCode', (req, res) => {18 sendCode(req.body).then(code => {19 resRevert(res, 200, 200, 'éªè¯ç åéæåï¼')20 }).catch(err => {21 console.log(err)22 resRevert(res, 200, 0, 'åé失败ï¼')23 })24})25// 注å26router.post('/addUser', (req, res) => {27 // å½å请æ±code对åºå
·ä½é®é¢28 // 0 æå¡å¨é®é¢29 // 1 è´¦å·é®é¢30 // 2 å¯ç é®é¢31 // 3 éªè¯ç é®é¢32 // 200 注åæå33 if (!emailRegex.test(req.body.email)) {34 return resRevert(res, 200, 1, 'é®ç®±æ ¼å¼é误ï¼')35 }36 if (!pwdRegex.test(req.body.password)) {37 return resRevert(res, 200, 2, 'å¯ç åºç±6-16ä½åæ¯ãæ°åãç¹æ®å符ç»æ.')38 }39 User.findOne({ email: req.body.email }).then(data => {40 if (data) {41 return resRevert(res, 200, 1, 'è´¦å·å·²åå¨ï¼')42 }43 Code.findOne({ account: req.body.email }).then(doc => {44 if (!doc) {45 return resRevert(res, 200, 3, 'éªè¯ç ä¸åå¨æå·²è¿æï¼')46 }47 if (req.body.code != doc.value) {48 return resRevert(res, 200, 3, 'éªè¯ç é误ï¼')49 }50 new User(Object.assign({}, req.body, {51 // å å¯å¹¶è¦çææå¯ç 52 password: encrypt(req.body.password)53 })).save().then(() => {54 return resRevert(res, 200, 200, '注åæåï¼')55 })56 })57 }).catch(err => {58 resRevert(res, 200, 0, "ç¨æ·å建失败ï¼")59 })60})61// ç»å½62router.post('/login', (req, res) => {63 if (!emailRegex.test(req.body.email)) {64 return resRevert(res, 200, 1, 'é®ç®±æ ¼å¼é误ï¼')65 }66 if (!pwdRegex.test(req.body.password)) {67 return resRevert(res, 200, 2, 'å¯ç åºç±6-16ä½åæ¯ãæ°åãç¹æ®å符ç»æ.')68 }69 User.findOne({ email: req.body.email}).then(res => {70 if (!res) {71 // æªæ¾å°å¹é
è´¦å·å¯ç 72 return resRevert(res, 200, 1, 'è´¦å·ä¸åå¨ï¼')73 }74 if (encrypt(req.body.password) !== res.password) {75 // å¯ç ä¸å¹é
76 return resRevert(res, 200, 2, 'å¯ç é误ï¼')77 }78 resRevert(res, 200, 200, 'ç»å½æåï¼')79 }).catch(err => {80 resRevert(res, 200, 0, 'æå¡å¨å¼å°å·®äºï¼è¯·ç¨åéè¯~')81 })82})83// éç½®å¯ç 84router.post('/resetPsw', (req, res) => {85 if (!emailRegex.test(req.body.email)) {86 return resRevert(res, 200, 1, 'é®ç®±æ ¼å¼é误ï¼')87 }88 if (!pwdRegex.test(req.body.password)) {89 return resRevert(res, 200, 2, 'å¯ç åºç±6-16ä½åæ¯ãæ°åãç¹æ®å符ç»æ.')90 }91 User.findOne({ email: req.body.email}).then(res => {92 if (!res) {93 // æªæ¾å°å¹é
è´¦å·å¯ç 94 return resRevert(res, 200, 1, 'è´¦å·ä¸åå¨ï¼')95 }96 if (encrypt(req.body.password) !== res.password) {97 // å¯ç ä¸å¹é
98 return resRevert(res, 200, 2, 'å¯ç é误ï¼')99 }100 resRevert(res, 200, 200, 'ç»å½æåï¼')101 }).catch(err => {102 resRevert(res, 200, 0, 'æå¡å¨å¼å°å·®äºï¼è¯·ç¨åéè¯~')103 })104})105// æµè¯ç¨106router.get('/test', (req, res) => {107 let str = encrypt(req.query.key)108 // console.log(str)109 // console.log(decrypt(str))110})...
Using AI Code Generation
1const tracetest = require('./build/contracts/TraceTest.json');2const contract = require('truffle-contract');3const Web3 = require('web3');4const tracetestContract = contract(tracetest);5tracetestContract.setProvider(provider);6tracetestContract.deployed().then(function(instance) {7 tracetestContractInstance = instance;8 return tracetestContractInstance.revert();9}).then(function(result) {10 console.log(result);11}).catch(function(err) {12 console.log(err.message);13});14module.exports = {15 networks: {16 development: {17 }18 }19};
Using AI Code Generation
1var tracetest = artifacts.require("./tracetest.sol");2module.exports = function(callback) {3 tracetest.deployed().then(function(instance){4 return instance.revertMethod.call();5 }).then(function(result){6 console.log("result: " + result);7 }).catch(function(e) {8 console.log(e);9 });10}11contract.methods.myFunction().call({from: myAddress}).then(function(result) {12 console.log(result);13});14contract.methods.myFunction().call({from: myAddress}, function(error, result) {15 console.log(result);16});17contract.methods.myFunction().call({from: myAddress}, function(error, result) {18 console.log(result);19});20contract.methods.myFunction().call({from: myAddress}, function(error, result) {21 console.log(result);22});23contract.methods.myFunction().call({from: myAddress}, function(error, result) {24 console.log(result);25});26contract.methods.myFunction().call({from: myAddress}, function(error, result) {27 console.log(result);28});29contract.methods.myFunction().call({from: myAddress}, function(error, result) {30 console.log(result);31});32contract.methods.myFunction().call({from: myAddress}, function(error, result) {33 console.log(result);34});
Using AI Code Generation
1const tracetest = require('./build/contracts/tracetest.json');2const Web3 = require('web3');3const contract = new web3.eth.Contract(tracetest.abi,'0x2c2b9c9a4a25e24b174f26114e8926a9f2128fe4');4async function main() {5 let accounts = await web3.eth.getAccounts();6 console.log(accounts);7 await contract.methods.revert().send({from: accounts[0]});8}9main();
Using AI Code Generation
1var tracetest = require('./tracetest');2var trace = new tracetest();3trace.revert();4console.log("test.js is called");5var trace = require('./trace');6module.exports = function () {7 this.revert = function () {8 trace.revert();9 }10}11module.exports = {12 revert: function () {13 console.log("trace.js is called");14 }15}
Using AI Code Generation
1const traceTest = require('./tracetest.js');2Recommended Posts: Node.js | trace() method3Node.js | untrace() method4Node.js | unwatchFile() method5Node.js | watchFile() method6Node.js | get() method7Node.js | set() method8Node.js | unref() method9Node.js | ref() method10Node.js | exec() method11Node.js | execFile() method12Node.js | send() method13Node.js | unshift() method14Node.js | shift() method15Node.js | pop() method16Node.js | push() method17Node.js | unshift() method18Node.js | splice() method19Node.js | reverse() method20Node.js | sort() method21Node.js | slice() method22Node.js | join() method23Node.js | indexOf() method24Node.js | lastIndexOf() method25Node.js | forEach() method26Node.js | map() method27Node.js | reduce() method28Node.js | reduceRight() method29Node.js | filter() method30Node.js | every() method31Node.js | some() method32Node.js | find() method33Node.js | findIndex() method34Node.js | fill() method35Node.js | copyWithin() method36Node.js | keys() method37Node.js | values() method38Node.js | entries() method39Node.js | includes() method40Node.js | flat() method41Node.js | flatMap() method42Node.js | from() method43Node.js | of() method44Node.js | isArray() method45Node.js | isBuffer() method46Node.js | isDate() method47Node.js | isError() method48Node.js | isMap() method49Node.js | isRegExp() method50Node.js | isSet() method51Node.js | isTypedArray() method52Node.js | isView() method53Node.js | toSource() method54Node.js | toLocaleString() method55Node.js | toString() method56Node.js | valueOf() method
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!