MerkleTreeJS - Leaf resolve error for whitelist verification - smartcontracts

We are using MerkleTreeJS to save our community gas fees when minting our NFTs. However, when we send the proof to the contract we get this error:
index.js:238 Uncaught (in promise) TypeError: t.substring is not a function
at c.formatParam (index.js:238:23)
at index.js:217:36
at Array.map (<anonymous>)
at c.formatParam (index.js:217:22)
at index.js:99:22
at Array.map (<anonymous>)
at c.encodeParameters (index.js:93:21)
at index.js:462:20
at Array.map (<anonymous>)
at Object.y._encodeMethodABI (index.js:461:8)
Do you have any idea how we can resolve the array correctly?
This is our code:
const leaves = [
"0x9811e43A71C85CC5f9BdA9822A7459d43A932dd9",
"0x0b371Cf8550923F67e90e5Bb26371e7A7b085b27",
"0xdc0cf0dFF9569209ba0F433e34743A8027A3c9E8",
"0xc4702bfea6410c082f3908fa270b3730fbc33e38"
].map(x => SHA256(x));
const tree = new MerkleTree(leaves, SHA256);
const root = tree.getRoot().toString('hex');
const leaf = SHA256(localStorage.userWallet);
proof = tree.getProof(leaf);
if (tree.verify(proof, leaf, root) === true) {
// address whitelisted
} else {
// not on whitelist
}

Related

Can not call the function Aggregate - Multicall2.sol on BSC testnet

I already deployed the multicall2.sol smart contract on BSC Testnet
https://testnet.bscscan.com/address/0x8F3273Fb89B075b1645095ABaC6ed17B2d4Bc576#code
then call the contract by using the following typescript code:
try {
const multi = getMulticallContract(options.web3 || web3NoAccount)
const itf = new Interface(abi)
const calldata = calls.map((call) => [call.address.toLowerCase(), itf.encodeFunctionData(call.name, call.params)])
const { returnData } = await multi.methods.aggregate(calldata).call(undefined, options.blockNumber)
const res = returnData.map((call, i) => itf.decodeFunctionResult(calls[i].name, call))
return res
} catch (error) {
throw new Error(error)
}
}
I got the error
Uncaught (in promise) Error: Error: Returned error: execution reverted: Multicall aggregate: call failed
It's weird. Because the function works properly on Mainnet. Can anyone help me?
The author found his solution but just to complete the troubleshooting I suggest making sure you have:
Have the contract deployed on testnet
Switch your RPC Node Url to the correct network. For example: BSC testnet's is https://data-seed-prebsc-1-s2.binance.org:8545
in my case, i resolved the issue by simply switching the rpc from https://data-seed-prebsc-1-s3.binance.org:8545/ to https://data-seed-prebsc-1-s2.binance.org:8545/
looks like they have some substantial inconsistency between nodes

Reference Error with module exports event discord.js

I am very confused by this error. In my code I have /events/ and /commands/ this is in /events/ I made sure that everything else works but this I can't figure out. The code down below is meant to work as a server count for a website. Anybody know? Thank you.
const Discord = require('discord.js');
var db = require('mysql');
var con = db.createConnection({
host: "localhost",
user: "",
password: "",
database: ""
});
module.exports = (client, guildCreate) => {
//welcome embed
const welcomeEmbed = new Discord.MessageEmbed()
.setColor('#858884')
.setTitle('Hello!')
.setAuthor('DHL Bot', 'https://cdn.discordapp.com/app-icons/708717412391845988/967e1b05f7b8aeca1d6b4649dc5530c8.png')
.setDescription(`Hello I am DHL, I am devoloped by Den#0762. Please do !setup. For support you can join our support server https://discord.com/invite`)
.setTimestamp()
.setFooter('By: Den#0762', 'https://cdn.discordapp.com/avatars/407206318911258628/e972b589e0ea4c45064d39b0380d77fd.png')
guild.owner.send(welcomeEmbed)
//db for scount
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE scount SET servercount = servercount + 1";
con.query(sql, function (err, result) {
console.log(result.affectedRows + " new server");
});
});
}
(node:1949) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
at module.exports (/root/dc/DHL/events/guildCreate.js:23:1)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_CREATE] (/root/node_modules/discord.js/src/client/websocket/handlers/GUILD_CREATE.js:33:14)
at WebSocketManager.handlePacket (/root/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/root/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/root/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/root/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (/root/node_modules/ws/lib/websocket.js:797:20)
at Receiver.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1949) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1949) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
You're referencing guild, but it isn't declared. Based on other code I've seen, I think you need something along these lines:
module.exports = (client, guildCreate) => {
//welcome embed
const welcomeEmbed = new Discord.MessageEmbed() [...]
client.on("guildCreate", guild => {
guild.owner.send(welcomeEmbed)
});
[...]

Express js Route.get() requires a callback function but got a [object Undefined]

Attempting to learn Expresss.js via this tutorial and I am at the point of adding routes. I believe I have followed the tutorial exactly, but I am getting this error:
[nodemon] starting `node ./bin/www`
/Users/dariusgoore/development/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object Undefined]
at Route.(anonymous function) [as get] (/Users/dariusgoore/development/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:202:15)
at Function.proto.(anonymous function) [as get] (/Users/dariusgoore/development/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:510:19)
at Object.<anonymous> (/Users/dariusgoore/development/express-locallibrary-tutorial/routes/catalog.js:86:8)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/dariusgoore/development/express-locallibrary-tutorial/app.js:9:21)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
[nodemon] app crashed - waiting for file changes before starting...
Here are the relevant files:
routes/catalog.js
var express = require('express');
var router = express.Router();
// Require controller modules.
var book_controller = require('../controllers/bookController');
var author_controller = require('../controllers/authorController');
var genre_controller = require('../controllers/genreController');
var book_instance_controller = require('../controllers/bookinstanceController');
/// BOOK ROUTES ///
// GET catalog home page.
router.get('/', book_controller.index);
// GET request for creating a Book. NOTE This must come before routes that display Book (uses id).
router.get('/book/create', book_controller.book_create_get);
// POST request for creating Book.
router.post('/book/create', book_controller.book_create_post);
// GET request to delete Book.
router.get('/book/:id/delete', book_controller.book_delete_get);
// POST request to delete Book.
router.post('/book/:id/delete', book_controller.book_delete_post);
// GET request to update Book.
router.get('/book/:id/update', book_controller.book_update_get);
// POST request to update Book.
router.post('/book/:id/update', book_controller.book_update_post);
// GET request for one Book.
router.get('/book/:id', book_controller.book_detail);
// GET request for list of all Book items.
router.get('/books', book_controller.book_list);
/// AUTHOR ROUTES ///
// GET request for creating Author. NOTE This must come before route for id (i.e. display author).
router.get('/author/create', author_controller.author_create_get);
// POST request for creating Author.
router.post('/author/create', author_controller.author_create_post);
// GET request to delete Author.
router.get('/author/:id/delete', author_controller.author_delete_get);
// POST request to delete Author.
router.post('/author/:id/delete', author_controller.author_delete_post);
// GET request to update Author.
router.get('/author/:id/update', author_controller.author_update_get);
// POST request to update Author.
router.post('/author/:id/update', author_controller.author_update_post);
// GET request for one Author.
router.get('/author/:id', author_controller.author_detail);
// GET request for list of all Authors.
router.get('/authors', author_controller.author_list);
/// GENRE ROUTES ///
// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
router.get('/genre/create', genre_controller.genre_create_get);
//POST request for creating Genre.
router.post('/genre/create', genre_controller.genre_create_post);
// GET request to delete Genre.
router.get('/genre/:id/delete', genre_controller.genre_delete_get);
// POST request to delete Genre.
router.post('/genre/:id/delete', genre_controller.genre_delete_post);
// GET request to update Genre.
router.get('/genre/:id/update', genre_controller.genre_update_get);
// POST request to update Genre.
router.post('/genre/:id/update', genre_controller.genre_update_post);
// GET request for one Genre.
router.get('/genre/:id', genre_controller.genre_detail);
// GET request for list of all Genre.
router.get('/genres', genre_controller.genre_list);
/// BOOKINSTANCE ROUTES ///
// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id).
router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get);
// POST request for creating BookInstance.
router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post);
// GET request to delete BookInstance.
router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get);
// POST request to delete BookInstance.
router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post);
// GET request to update BookInstance.
router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get);
// POST request to update BookInstance.
router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post);
// GET request for one BookInstance.
router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail);
// GET request for list of all BookInstance.
router.get('/bookinstances', book_instance_controller.bookinstance_list);
module.exports = router;
in app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var catalogRouter = require('./routes/catalog'); //Import routes for "catalog" area of site
var app = express();
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://dariusgoore:654321cg#ds145704.mlab.com:45704/local_library_dg';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/catalog', catalogRouter); // Add catalog routes to middleware chain.
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
By process of elimination (and referenced in the error trace), the route that is causing the error is this one:
// GET request for one Genre.
router.get('/genre/:id', genre_controller.genre_detail);
Commenting out that route eliminates the error, but I can't tell why.
Figured this out. the controller spelled the action differently.
The router line above references genre_controller.genre_detail
whereas the controller exported genre_details
changing details to detail in the controller solves this issue.

Truffle test fails with Error: Could not find artifacts

I learn the demo: Code is come from: https://truffleframework.com/tutorials/pet-shop, when I test:
$ truffle.cmd test
Using network 'development'.
Compiling .\test\TestAdoption.sol...
TestAdoption
1) "before all" hook: prepare suite
0 passing (30s)
1 failing
1) TestAdoption
"before all" hook: prepare suite:
Error: Could not find artifacts for /E/blockchain/pet-
shop/contracts/Adoption.sol from any sources
at Resolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-resolver\index.js:37:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at TestResolver.require (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\testresolver.js:17:1)
at dependency_paths.forEach.dependency_path (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:203:1)
at Array.forEach (<anonymous>)
at deployer.deploy.then (D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-core\lib\testing\soliditytest.js:202:1)
at D:\nvm\v10.14.2\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deferredchain.js:20:1
at process._tickCallback (internal/process/next_tick.js:68:7)
I updated my nodejs lastest, and installed window-build-tools,it does not work.
TestAdoption.sol:
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption());
function testUserCanAdoptPet() public {
uint returnedId = adoption.adopt(expectedPetId);
Assert.equal(returnedId, expectedPetId);
}
uint expectedPetId = 8;
address expectedAdopter = address(this);
function testGetAdopterAddressByPetId() public {
address adopter = adoption.adopters(expectedPetId);
Assert.equal(adopter, expectedAdopter, "Owner of the expected pet should be this contract");
}
function testGetAdopterAddressByPetIdInArray() public {
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract");
}
}
2_deploy_contracts.sol:
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
And import "truffle/Assert.sol"; vscode say: Source "truffle/Assert.sol" not found: File import callback not supported.My friend's version is 0.4.14 and work well, may be a version problem?
Here is project dir(just a demo from https://truffleframework.com/tutorials/pet-shop):
This error DOESN'T happen (currently) in the version v5.1.10 of truffle.
My full error was:
TypeError: Error parsing C:/Users/PATH/yourSmartContract.sol: Cannot destructure property 'body' of 'undefined' as it is undefined.
My solution is to downgrade the version like so:
$ npm uninstall -g truffle
$ npm install -g truffle#v5.1.10
(Developing in BC is hard because of version control and managment. Keep the good the work.)
The problem is the name of the artifact is defined according to the contract's name. This is your contract:
contract TestAdoption {
}
So;
2_deploy_contracts.sol:
// not artifactsrequire(Adoption)
var Adoption = artifacts.require("TestAdoption");
module.exports = function(deployer) {
deployer.deploy(Adoption);
};
Try these files:
1_initial_migration.js:
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
2_deploy_contracts.js:
const YourContractName = artifacts.require("YourContractName");
module.exports = function(deployer) {
deployer.deploy(YourContractName);
};
Tips:
Do not change the name of the files (1_initial_migration.js and 2_deploy_contracts.js);
Use the exactly name of your contract in the "2_deploy_contracts" file (if it is called BatatinhaFrita123, you need to specify BatatinhaFrita123 inside the artifacts.require()).

Aurelia startup error - Invalid resource path: function Compose

After upgrading my Aurelia Framework in my application via:
"aurelia-bootstrapper": "^2.3.0"
I'm getting error at the application startup (stack trace at the bottom).
Returning to:
"aurelia-bootstrapper": "2.2.0"
fixes the error. In release notes for version of Aurelia in question, there is note about additional functionality of setRoot method, but nothing that could be breaking change Aurelia Release Notes - June 2018.
I just use default:
aurelia.start().then(() => aurelia.setRoot());
This is details stack trace of startup error:
vendor-bundle.js:1398 Unhandled rejection Error: Invalid resource path [function Compose(element, container, compositionEngine, viewSlot, viewResources, taskQueue) {
_initDefineProp(this, 'model', _descriptor, this);
_initDefineProp(this, 'view', _descriptor2, this);
_initDefineProp(this, 'viewModel', _descriptor3, this);
_initDefineProp(this, 'swapOrder', _descriptor4, this);
this.element = element;
this.container = container;
this.compositionEngine = compositionEngine;
this.viewSlot = viewSlot;
this.viewResources = viewResources;
this.taskQueue = taskQueue;
this.currentController = null;
this.currentViewModel = null;
this.changes = Object.create(null);
}]. Resources must be specified as relative module IDs.
at FrameworkConfiguration.globalResources (http://localhost/scripts/vendor-bundle.js:69284:17)
at Object.configure (http://localhost/scripts/vendor-bundle.js:62319:12)
at http://localhost/scripts/vendor-bundle.js:69140:36
From previous event:
at _loadPlugin (http://localhost/scripts/vendor-bundle.js:69138:42)
at http://localhost/scripts/vendor-bundle.js:69131:16
From previous event:
at loadPlugin (http://localhost/scripts/vendor-bundle.js:69130:75)
at next (http://localhost/scripts/vendor-bundle.js:69392:20)
From previous event:
at next (http://localhost/scripts/vendor-bundle.js:69392:56)
at http://localhost/scripts/vendor-bundle.js:69399:16
From previous event:
at FrameworkConfiguration.apply (http://localhost/scripts/vendor-bundle.js:69384:44)
at Aurelia.start (http://localhost/scripts/vendor-bundle.js:69000:39)
at Object.<anonymous> (http://localhost/scripts/app-bundle.js:5811:33)
at step (http://localhost/scripts/app-bundle.js:51:23)
at Object.next (http://localhost/scripts/app-bundle.js:32:53)
at fulfilled (http://localhost/scripts/app-bundle.js:23:58)
From previous event:
at step (http://localhost/scripts/app-bundle.js:25:124)
at http://localhost/scripts/app-bundle.js:26:9
From previous event:
at __awaiter (http://localhost/scripts/app-bundle.js:22:12)
at Object.configure (http://localhost/scripts/app-bundle.js:5793:16)
at http://localhost/scripts/vendor-bundle.js:70930:29
From previous event:
at config (http://localhost/scripts/vendor-bundle.js:70925:56)
at http://localhost/scripts/vendor-bundle.js:70961:14
From previous event:
at bootstrap (http://localhost/scripts/vendor-bundle.js:70960:26)
at http://localhost/scripts/vendor-bundle.js:70947:9
From previous event:
at run (http://localhost/scripts/vendor-bundle.js:70942:61)
at Object.<anonymous> (http://localhost/scripts/vendor-bundle.js:70967:37)
at Object.execCb (http://localhost/scripts/vendor-bundle.js:8724:33)
at Module.check (http://localhost/scripts/vendor-bundle.js:7911:51)
at Module.enable (http://localhost/scripts/vendor-bundle.js:8204:22)
at Object.enable (http://localhost/scripts/vendor-bundle.js:8585:39)
at Module.<anonymous> (http://localhost/scripts/vendor-bundle.js:8189:33)
at http://localhost/scripts/vendor-bundle.js:7162:23
at each (http://localhost/scripts/vendor-bundle.js:7087:31)
at Module.enable (http://localhost/scripts/vendor-bundle.js:8141:17)
at Module.init (http://localhost/scripts/vendor-bundle.js:7816:26)
at http://localhost/scripts/vendor-bundle.js:8488:36
printWarning # vendor-bundle.js:1398