AssertionError: Specified args not emitted - Solidity Hardhat - javascript

I have a smart contract that I'm testing the first functions of, and so far everything seems fine apart from one argument of an event not being properly passed.
The contract :
// SPDX-License-Identifier: MIT
// contract that mints 10 NFTs that will then be sold on the market place
pragma solidity ^0.8.7;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
contract MintNFT is ERC721, ERC721URIStorage, Ownable {
//Helpers
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string[] public _allTokenURIs;
mapping(uint256 => string) public _IDtoURI;
event NFTMinted(uint256 indexed tokenId, string uri);
constructor() ERC721("Plot On Mars", "POM") {}
function bulkMint(string[] memory uris)
public
onlyOwner
{
_allTokenURIs = uris;
address to = msg.sender;
for (uint i = 0; i < uris.length; i++) {
safeMint(to, uris[i]);
}
}
function safeMint(address to, string memory uri)
internal
onlyOwner
{
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
_IDtoURI[tokenId]=uri;
emit NFTMinted(tokenId, uri);
}
function getTokenId() public view returns(uint256){
return _tokenIds.current();
}
// function to view a specific URI related to a tokenID
function viewURIs(uint256 i) public view returns(string memory){
string memory unique = _allTokenURIs[i];
return unique;
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
}
The test script :
const { assert, expect, expectEvent } = require("chai")
const { network, deployment, ethers, deployments } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")
//Arrange-Act-Assert (AAA)
// if we have defined an error in our solidity code, we must wrap the logic corresponding
//in a catch/try{}
//skip test if on localhost/hardhat
!developmentChains.includes(network.name)
? describe.skip
: describe("Basic NFT minting tests", function () {
let mintNFT, deployer
let _name = "Plot On Mars"
let _symbol = "POM"
let tokensUris = [
"ipfs://QmaGmVJianGd3wzdfRNFZXWA9UeMdLFMBX5cZZSZjNeckP",
"ipfs://QmaGV6P2knFkPdStvPsNXjJjehEysfnK7e4tShJAvpuPrx",
"ipfs://QmcdbzSUFhRF98ppNHf83yhPJ2jHjP5Lpuov9Wzi4aYZF4",
"ipfs://QmP8W1KEC2td2VPn3tbEYjFBZ2yV6jZh5Fbe2rGjzqCMwS",
"ipfs://QmdL2QjcLPjd1RLwHK1GNuNQSt5b4ZXupuaGYtUi3Lqqz5",
"ipfs://QmaJqsMKbFLLTZszY2rprPRncDReLTnhHVdz2U7aScxFNS",
"ipfs://QmYeioLfMcTUNSABndwqJz7sjaeA7quF1fMGq2tziSE2T3",
"ipfs://QmW7nRHE7J5L36n9NvxspwNfSbEPRcFvDF4kUkscZHehyZ",
"ipfs://QmUcCwpskbvQydNa3rcSpCftsPAmBgovn6WnZYTeZw4NpU",
"ipfs://QmdyTVfRymf2kFrrfdNq2FGHYX4gx5YDT1DvgmkccSee1U",
]
//deploys the contract and gets an instance of it to work with
beforeEach(async () => {
accounts = await ethers.getSigners()
deployer = accounts[0]
user = accounts[1]
await deployments.fixture(["mintnft"])
mintNFT = await ethers.getContract("MintNFT")
})
// constructor
describe("Deployment", function () {
it("Should have the correct name and symbol", async function () {
expect(await mintNFT.name()).to.equal(_name)
expect(await mintNFT.symbol()).to.equal(_symbol)
})
it("should set the right owner", async function () {
expect(await mintNFT.owner()).to.equal(deployer.address)
})
})
// bulkMint()
describe("It mints 10NFTs", function () {
it("Should be reverted as caller is not owner", async function () {
await expect(mintNFT.connect(user).bulkMint(tokensUris)).to.be.revertedWith(
"Ownable: caller is not the owner"
)
})
it("Should emit the NFtMinted event after each token minted", async function () {
for (i = 0; i < tokensUris.length; i++) {
let index = i
await expect(mintNFT.bulkMint(tokensUris))
.to.emit(mintNFT, "NFTMinted")
.withArgs(tokensUris[i], index)
}
})
describe("View token ID to check that counter is at 10", function () {
let tokencounter = 10
it("Should return a token counter of 10 if all NFTs have been successfully minted", async function () {
await mintNFT.bulkMint(tokensUris)
expect(await mintNFT.getTokenId()).to.equal(tokencounter)
})
})
//after calling buklMint(), grab the tokenURIs and test them individually = getURI(0)="ipfs://..."
describe("Each token URI is properly initialized", function () {
it("Should set the token URIs to their correct ipfs addresses", async function () {
await mintNFT.bulkMint(tokensUris)
//assumes that the bulkMint() is correctly working. If it is, it will initialize _allTokenURIs and viewUris() will return them
for (i = 0; i < tokensUris.length; i++) {
expect(await mintNFT.viewURIs(i)).to.equal(tokensUris[i])
console.log(await mintNFT.viewURIs(i), "is equal to", tokensUris[i])
}
})
})
})
})
When running tests, here are the results :
anne#AnneSager:~/HAAAAAAAA/newTry$ yarn hardhat test
yarn run v1.22.15
warning package.json: No license field
warning ../../package.json: No license field
$ /home/anne/HAAAAAAAA/newTry/node_modules/.bin/hardhat test
Compiled 1 Solidity file successfully
Basic NFT minting tests
Deployment
✔ Should have the correct name and symbol (40ms)
✔ should set the right owner
It mints 10NFTs
✔ Should be reverted as caller is not owner (74ms)
1) Should emit the NFtMinted event after each token minted
View token ID to check that counter is at 10
✔ Should return a token counter of 10 if all NFTs have been successfully minted (174ms)
Each token URI is properly initialized
ipfs://QmaGmVJianGd3wzdfRNFZXWA9UeMdLFMBX5cZZSZjNeckP is equal to ipfs://QmaGmVJianGd3wzdfRNFZXWA9UeMdLFMBX5cZZSZjNeckP
ipfs://QmaGV6P2knFkPdStvPsNXjJjehEysfnK7e4tShJAvpuPrx is equal to ipfs://QmaGV6P2knFkPdStvPsNXjJjehEysfnK7e4tShJAvpuPrx
ipfs://QmcdbzSUFhRF98ppNHf83yhPJ2jHjP5Lpuov9Wzi4aYZF4 is equal to ipfs://QmcdbzSUFhRF98ppNHf83yhPJ2jHjP5Lpuov9Wzi4aYZF4
ipfs://QmP8W1KEC2td2VPn3tbEYjFBZ2yV6jZh5Fbe2rGjzqCMwS is equal to ipfs://QmP8W1KEC2td2VPn3tbEYjFBZ2yV6jZh5Fbe2rGjzqCMwS
ipfs://QmdL2QjcLPjd1RLwHK1GNuNQSt5b4ZXupuaGYtUi3Lqqz5 is equal to ipfs://QmdL2QjcLPjd1RLwHK1GNuNQSt5b4ZXupuaGYtUi3Lqqz5
ipfs://QmaJqsMKbFLLTZszY2rprPRncDReLTnhHVdz2U7aScxFNS is equal to ipfs://QmaJqsMKbFLLTZszY2rprPRncDReLTnhHVdz2U7aScxFNS
ipfs://QmYeioLfMcTUNSABndwqJz7sjaeA7quF1fMGq2tziSE2T3 is equal to ipfs://QmYeioLfMcTUNSABndwqJz7sjaeA7quF1fMGq2tziSE2T3
ipfs://QmW7nRHE7J5L36n9NvxspwNfSbEPRcFvDF4kUkscZHehyZ is equal to ipfs://QmW7nRHE7J5L36n9NvxspwNfSbEPRcFvDF4kUkscZHehyZ
ipfs://QmUcCwpskbvQydNa3rcSpCftsPAmBgovn6WnZYTeZw4NpU is equal to ipfs://QmUcCwpskbvQydNa3rcSpCftsPAmBgovn6WnZYTeZw4NpU
ipfs://QmdyTVfRymf2kFrrfdNq2FGHYX4gx5YDT1DvgmkccSee1U is equal to ipfs://QmdyTVfRymf2kFrrfdNq2FGHYX4gx5YDT1DvgmkccSee1U
✔ Should set the token URIs to their correct ipfs addresses (383ms)
5 passing (2s)
1 failing
1) Basic NFT minting tests
It mints 10NFTs
Should emit the NFtMinted event after each token minted:
AssertionError: Specified args not emitted in any of 10 emitted "NFTMinted" events
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I've run the same code with only changing the arguments in the NFTMinted event, passing it only the uri variable, and the 6 tests passed successfully.
So my problem comes from my tokenId... I've tried not using Counters and initializing my own uint256 tokenId, but the error was the same, AssertionError: Specified args not emitted in any of 10 emitted "NFTMinted" events.
Any help would be greatly appreciated :)
Other info:
package.json :
{
"devDependencies": {
"#nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers",
"#nomiclabs/hardhat-etherscan": "^3.1.0",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"#openzeppelin/contracts": "^4.7.2",
"#pinata/sdk": "^1.1.26",
"chai": "^4.3.6",
"dotenv": "^16.0.1",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.9",
"hardhat": "^2.10.1",
"hardhat-contract-sizer": "^2.6.1",
"hardhat-deploy": "^0.11.12",
"hardhat-gas-reporter": "^1.0.8",
"path": "^0.12.7",
"prettier": "^2.7.1",
"prettier-plugin-solidity": "^1.0.0-dev.23",
"solhint": "^3.3.7",
"solidity-coverage": "^0.7.21"
}
}
running on Linux Ubuntu 20.4
using VSCode
UPDATE
Derawi's comment made me run through my code again to try to figure out how to not call the bulkMint() function 10 times.
I have not managed to fix it yet, but the changes I made brought a new error that allows me to push my thought process forward.
Changes
modified my bulkMint()
function bulkMint(string[] memory uris)
public
onlyOwner
{
_allTokenURIs = uris;
address to = msg.sender;
for (uint256 i = 0; i < _allTokenURIs.length; i++) {
string memory uri = _allTokenURIs[i];
safeMint(to, uri);
}
}
mint-unit.js test file :
describe("It mints 10NFTs", function () {
it("Should be reverted as caller is not owner", async function () {
await expect(mintNFT.connect(user).bulkMint(tokensUris)).to.be.revertedWith(
"Ownable: caller is not the owner"
)
})
it("Should emit the NFtMinted event after each token minted", async function () {
await mintNFT.bulkMint(tokensUris)
for (i = 0; i < tokensUris.length; i++) {
let index = i
let uri = tokensUris[index]
await expect(mintNFT.safeMint(deployer.address, uri))
.to.emit(mintNFT, "NFTMinted")
.withArgs(index, uri)
}
})
Now the error message is :
1) Basic NFT minting tests
It mints 10NFTs
Should emit the NFtMinted event after each token minted:
AssertionError: Expected "11" to be equal 0
at assertArgsArraysEqual (node_modules/#ethereum-waffle/chai/dist/cjs/matchers/emit.js:58:54)
at tryAssertArgsArraysEqual (node_modules/#ethereum-waffle/chai/dist/cjs/matchers/emit.js:65:20)
at /home/anne/HAAAAAAAA/newTry/node_modules/#ethereum-waffle/chai/dist/cjs/matchers/emit.js:77:13
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at listOnTimeout (node:internal/timers:528:9)
at processTimers (node:internal/timers:502:7)
at Context.<anonymous> (test/mint-unit.js:61:13)
Any help is still appreciated, I can tell I've messed somewhere, but still can't figure out if it's on the contract, on the test, or on both :/

Related

How to test if localStorage receives item I set in a function?

Currently trying to run a unit test for a authentication function. I've written a dummy function that basically does what the authentication function for the sake of abiding by NDA.
Authentication.js
export const myTestFunction = param => {
console.log(param);
localStorage.setItem("Test", param)
}
index.test.js
import {myTestFunction} from "../../redux/actions/ApiAuthAction";
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
test("Test to see myTestFunction sets localStorage to the param value", () => {
let param = "Hello"
myTestFunction(param);
expect(localStorageMock.setItem).toBeCalledWith("Test");
});
When I run the test, this is what it returns:
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with:
["Test"]
But it was not called.
73 | let param = "Hello"
74 | myTestFunction(param);
> 75 | expect(localStorageMock.setItem).toBeCalledWith("Test");
| ^
at Object.toBeCalledWith (src/__tests__/reducers/index.test.js:75:38)
I am not sure what I am doing wrong here. I am creating a mock localStorage. I threw the function into the test and it still throws this failed test of it not being called. Help?
EDIT: The whole point of this test is to see if that localStorage.setItem("Test, param); gets called or not.
The solution I ended up using was: expect(localStorage.getItem("Test")).toBeDefined(); but I am happy to hear if anyone has a more dynamic solution.

Use chance plugin in cypress

Is it possible to use chance plugin with cypress.io?
https://chancejs.com
I installed plugin via npm to node_modules\chance and edited /plugins/index.js file, but still get error from cypress - Can't start, The plugins file is missing or invalid.
If using this plugin is impossible - what do you recommend to write tests basing on registration new users? I planned to use chance to generate "random: emails and passwords.
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
module.exports = on => {
on("task", {
chance: require("chance"),
});
};
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
}
Just install chancejs with npm:
npm install chance
Then just use it in your test for example:
/// <reference types="cypress" />
import Chance from 'Chance';
const chance = new Chance();
describe('Testing chance', function (){
const company =chance.company();
it('type company in duckduckgo.com', function () {
cy.visit('https://duckduckgo.com/')
cy.get('#search_form_input_homepage')
.should('be.visible')
.type(company)
})
})
cypress/support/index.js:
Override the default task command so that you can supply multiple arguments as you'd normally.
Cypress.Commands.overwrite('task', (origFn, name, ...args) => {
return origFn(name, args);
});
// if you're gonna use `chance` plugin a lot, you can also add a custom command
Cypress.Commands.add('chance', (...args) => {
return cy.task('chance', ...args);
});
cypress/plugins/index.js:
Wrap the tasks in function that will spread the arguments, and also handle a case when the task doesn't return anything and return null instead, so that cypress doesn't complain.
const chance = require('chance').Chance();
// lodash should be installed alongside with cypress.
// If it doesn't resolve, you'll need to install it manually
const _ = require('lodash');
on('task', _.mapValues(
{
chance ( method, ...args ) {
return chance[method](...args);
}
},
func => args => Promise.resolve( func(...args) )
// ensure we return null instead of undefined to satisfy cy.task
.then( val => val === undefined ? null : val )
));
In your spec file:
describe('test', () => {
it('test', () => {
cy.document().then( doc => {
doc.body.innerHTML = `<input class="email">`;
});
cy.task('chance', 'email', {domain: 'example.com'}).then( email => {
cy.get('.email').type(email);
});
// or use the custom `chance` command we added
cy.chance('email', {domain: 'test.com'}).then( email => {
cy.get('.email').type(email);
});
});
});

Call Function From Solidity With Web3

I am having trouble calling a simple function from my solidity contract. Here's how the code is structured so far:
In my web3Api.js file I have:
export function getContract(contractDefinition) {
initWeb3();
const contract = initContract(contractDefinition);
contract.setProvider(web3.currentProvider);
if (typeof contract.currentProvider.sendAsync !== 'function') {
contract.currentProvider.sendAsync = function () {
return contract.currentProvider.send.apply(
contract.currentProvider, arguments
);
};
}
return contract.deployed();
}
Then in my projectApi.js file I have:
import { getContract } from './web3Api';
import CompiledContract '../../../build/contracts/compiledContract.json';
let globalVariable;
export async function testing123() {
const contractInstance = await getContract(CompiledContract)
globalVariable = contractInstance;
}
Note: When I call the global variable throughout this file it successfully returns all my contract's functions
TruffleContract {constructor: ƒ, abi: Array(33), contract: Contract, PracticeEvent: ƒ, Transfer: ƒ, …}
So this next part is where I'm running into trouble.
For this post's sake, I am just trying to call this simple function from my contract:
function smartContractFunction() public {
emit PracticeEvent("practice event has been called");
}
Now back in my projectApi.js file I am using the globalVariable to try grab this function from my contract. Here's what I wrote:
export async function practiceInteract() {
const submitTest = await globalVariable.smartContractFunction().call();
console.log(submitTest);
}
When I run the app I get an error saying "formatters.js:274 Uncaught (in promise) Error: invalid address"
Any ideas why I cannot call this solidity function in my projectAPI.js file?
Happy to clarify this if I did not clearly write out my problem.
Thank You!
Your issue is that your are simply not defining an address that is calling the function. You need to defined who is calling the function if you are using web3 in the manner that you are. The correct code would be:
export async function practiceInteract() {
const submitTest = await globalVariable.smartContractFunction().call({from: web3.eth.accounts[0]});
console.log(submitTest);
}
You can do it like this:
const contract = new web3.eth.Contract(ABI, address)
const returnValue = await contract.methods.someFunc(someArg).call()
For more information about how to interact with smart contracts using web3.js, read this article

Firebase Cloud Function with Firestore returning "Deadline Exceeded"

I took one of the sample functions from the Firestore documentation and was able to successfully run it from my local firebase environment. However, once I deployed to my firebase server, the function completes, but no entries are made in the firestore database. The firebase function logs show "Deadline Exceeded." I'm a bit baffled. Anyone know why this is happening and how to resolve this?
Here is the sample function:
exports.testingFunction = functions.https.onRequest((request, response) => {
var data = {
name: 'Los Angeles',
state: 'CA',
country: 'USA'
};
// Add a new document in collection "cities" with ID 'DC'
var db = admin.firestore();
var setDoc = db.collection('cities').doc('LA').set(data);
response.status(200).send();
});
Firestore has limits.
Probably “Deadline Exceeded” happens because of its limits.
See this. https://firebase.google.com/docs/firestore/quotas
Maximum write rate to a document 1 per second
https://groups.google.com/forum/#!msg/google-cloud-firestore-discuss/tGaZpTWQ7tQ/NdaDGRAzBgAJ
In my own experience, this problem can also happen when you try to write documents using a bad internet connection.
I use a solution similar to Jurgen's suggestion to insert documents in batch smaller than 500 at once, and this error appears if I'm using a not so stable wifi connection. When I plug in the cable, the same script with the same data runs without errors.
I have written this little script which uses batch writes (max 500) and only write one batch after the other.
use it by first creating a batchWorker let batch: any = new FbBatchWorker(db);
Then add anything to the worker batch.set(ref.doc(docId), MyObject);. And finish it via batch.commit().
The api is the same as for the normal Firestore Batch (https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes) However, currently it only supports set.
import { firestore } from "firebase-admin";
class FBWorker {
callback: Function;
constructor(callback: Function) {
this.callback = callback;
}
work(data: {
type: "SET" | "DELETE";
ref: FirebaseFirestore.DocumentReference;
data?: any;
options?: FirebaseFirestore.SetOptions;
}) {
if (data.type === "SET") {
// tslint:disable-next-line: no-floating-promises
data.ref.set(data.data, data.options).then(() => {
this.callback();
});
} else if (data.type === "DELETE") {
// tslint:disable-next-line: no-floating-promises
data.ref.delete().then(() => {
this.callback();
});
} else {
this.callback();
}
}
}
export class FbBatchWorker {
db: firestore.Firestore;
batchList2: {
type: "SET" | "DELETE";
ref: FirebaseFirestore.DocumentReference;
data?: any;
options?: FirebaseFirestore.SetOptions;
}[] = [];
elemCount: number = 0;
private _maxBatchSize: number = 490;
public get maxBatchSize(): number {
return this._maxBatchSize;
}
public set maxBatchSize(size: number) {
if (size < 1) {
throw new Error("Size must be positive");
}
if (size > 490) {
throw new Error("Size must not be larger then 490");
}
this._maxBatchSize = size;
}
constructor(db: firestore.Firestore) {
this.db = db;
}
async commit(): Promise<any> {
const workerProms: Promise<any>[] = [];
const maxWorker = this.batchList2.length > this.maxBatchSize ? this.maxBatchSize : this.batchList2.length;
for (let w = 0; w < maxWorker; w++) {
workerProms.push(
new Promise((resolve) => {
const A = new FBWorker(() => {
if (this.batchList2.length > 0) {
A.work(this.batchList2.pop());
} else {
resolve();
}
});
// tslint:disable-next-line: no-floating-promises
A.work(this.batchList2.pop());
}),
);
}
return Promise.all(workerProms);
}
set(dbref: FirebaseFirestore.DocumentReference, data: any, options?: FirebaseFirestore.SetOptions): void {
this.batchList2.push({
type: "SET",
ref: dbref,
data,
options,
});
}
delete(dbref: FirebaseFirestore.DocumentReference) {
this.batchList2.push({
type: "DELETE",
ref: dbref,
});
}
}
I tested this, by having 15 concurrent AWS Lambda functions writing 10,000 requests into the database into different collections / documents milliseconds part. I did not get the DEADLINE_EXCEEDED error.
Please see the documentation on firebase.
'deadline-exceeded': Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.
In our case we are writing a small amount of data and it works most of the time but loosing data is unacceptable. I have not concluded why Firestore fails to write in simple small bits of data.
SOLUTION:
I am using an AWS Lambda function that uses an SQS event trigger.
# This function receives requests from the queue and handles them
# by persisting the survey answers for the respective users.
QuizAnswerQueueReceiver:
handler: app/lambdas/quizAnswerQueueReceiver.handler
timeout: 180 # The SQS visibility timeout should always be greater than the Lambda function’s timeout.
reservedConcurrency: 1 # optional, reserved concurrency limit for this function. By default, AWS uses account concurrency limit
events:
- sqs:
batchSize: 10 # Wait for 10 messages before processing.
maximumBatchingWindow: 60 # The maximum amount of time in seconds to gather records before invoking the function
arn:
Fn::GetAtt:
- SurveyAnswerReceiverQueue
- Arn
environment:
NODE_ENV: ${self:custom.myStage}
I am using a dead letter queue connected to my main queue for failed events.
Resources:
QuizAnswerReceiverQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: ${self:provider.environment.QUIZ_ANSWER_RECEIVER_QUEUE}
# VisibilityTimeout MUST be greater than the lambda functions timeout https://lumigo.io/blog/sqs-and-lambda-the-missing-guide-on-failure-modes/
# The length of time during which a message will be unavailable after a message is delivered from the queue.
# This blocks other components from receiving the same message and gives the initial component time to process and delete the message from the queue.
VisibilityTimeout: 900 # The SQS visibility timeout should always be greater than the Lambda function’s timeout.
# The number of seconds that Amazon SQS retains a message. You can specify an integer value from 60 seconds (1 minute) to 1,209,600 seconds (14 days).
MessageRetentionPeriod: 345600 # The number of seconds that Amazon SQS retains a message.
RedrivePolicy:
deadLetterTargetArn:
"Fn::GetAtt":
- QuizAnswerReceiverQueueDLQ
- Arn
maxReceiveCount: 5 # The number of times a message is delivered to the source queue before being moved to the dead-letter queue.
QuizAnswerReceiverQueueDLQ:
Type: "AWS::SQS::Queue"
Properties:
QueueName: "${self:provider.environment.QUIZ_ANSWER_RECEIVER_QUEUE}DLQ"
MessageRetentionPeriod: 1209600 # 14 days in seconds
If the error is generate after around 10 seconds, probably it's not your internet connetion, it might be that your functions are not returning any promise. In my experience I got the error simply because I had wrapped a firebase set operation(which returns a promise) inside another promise.
You can do this
return db.collection("COL_NAME").doc("DOC_NAME").set(attribs).then(ref => {
var SuccessResponse = {
"code": "200"
}
var resp = JSON.stringify(SuccessResponse);
return resp;
}).catch(err => {
console.log('Quiz Error OCCURED ', err);
var FailureResponse = {
"code": "400",
}
var resp = JSON.stringify(FailureResponse);
return resp;
});
instead of
return new Promise((resolve,reject)=>{
db.collection("COL_NAME").doc("DOC_NAME").set(attribs).then(ref => {
var SuccessResponse = {
"code": "200"
}
var resp = JSON.stringify(SuccessResponse);
return resp;
}).catch(err => {
console.log('Quiz Error OCCURED ', err);
var FailureResponse = {
"code": "400",
}
var resp = JSON.stringify(FailureResponse);
return resp;
});
});

Solidity - EVM Invalid JUMP when using webpack app

I am creating a frontend app based on Truffle + Webpack, following this tuto : http://truffleframework.com/tutorials/building-testing-frontend-app-truffle-3, and have no uderstanding of JavaScript at all.
The code works on truffle console and the app globally works, except for the function "append_buy_brent", adding a new element to a struct array called buy_orderbook_brent
Solidity :
contract Petroleum{
// Initialisations
address _creator;
uint user_number;
struct Baril_order {
uint price;
uint quantity;
address addr;
}
Baril_order[] buy_orderbook_brent;
mapping(address => uint) account_map;
mapping(uint => uint) user_balance;
mapping(uint => uint) number_of_brent;
function Petroleum() payable{
_creator=msg.sender;
user_number=0;
test=0;
account_map[_creator]=0;
account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]=1;
user_balance[account_map[msg.sender]]=100000;
number_of_brent[account_map[msg.sender]]=5;
number_of_wti[account_map[msg.sender]]=2;
debt[account_map[msg.sender]]=20;
user_balance[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=200000;
number_of_brent[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=7;
number_of_wti[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=10;
debt[account_map[0x7f8105da4dd1af61da7bf587766103ba8534fcdc]]=3;
}
function append_buy_brent(uint price, uint quantity, address addr) payable {
buy_orderbook_brent.push(
Baril_order({
price:price,
quantity: quantity,
addr: addr,
})
);
}
}
JavaScript :
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import Petroleum_artifacts from '../../build/contracts/Petroleum.json'
var Petroleum = contract(Petroleum_artifacts);
var accounts;
var account;
var account1;
window.App = {
start: function() {
var self = this;
Petroleum.setProvider(web3.currentProvider);
web3.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts.");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
accounts = accs;
account = accounts[0];
account1 = accounts[1];
self.refreshBalance1();
self.refreshBalance2();
});
},
append_buy_brent: function(){
var self = this;
var price_buy_brent= parseInt(document.getElementById("price_buy_brent").value);
var quantity_buy_brent=parseInt(document.getElementById("quantity_buy_brent").value);
this.setStatus("Initiating transaction... (please wait)");
var petro;
Petroleum.deployed().then(function(instance) {
petro = instance;
return petro.append_buy_brent(price_buy_brent,quantity_buy_brent, account, {from: account, value: web3.toWei(1000, "ether")});
}).then(function(value) {
self.setStatus("Transaction complete!");
self.refreshBalance1();
self.refreshBalance2();
}).catch(function(e) {
console.log(e);
self.setStatus("Error placing buy_brent; see log.");
});
},
}
Log :
Error: VM Exception while processing transaction: invalid JUMP at
d8abbe98e23bfa2cd66729f537c8dd23bb72c25425af350243627a30533c3b73/a8c9aca1a9b5fd638a6aa025545e1274787f3456:790
I hope I gave enough information, first time here. Thanks a lot.
it looks like a EVM bug. Could you try without putting both the contract deployment and the function call in 2 different transactions ?
https://github.com/ethereumjs/testrpc/issues/196

Categories

Resources