hardhat deploy method not working anymore with fund how to fund the contract? - smartcontracts

So I have written the same code as the hardhat documentation suggest here for deploying with funding maybe.
import hre from "hardhat";
const main = async () => {
const currentTimestampInSeconds = Math.round(Date.now() / 1000);
const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60;
const unlockTime = currentTimestampInSeconds + ONE_YEAR_IN_SECS;
const lockedAmount = hre.ethers.utils.parseEther("1");
const waveContractFactory = await hre.ethers.getContractFactory("WavePortal");
const waveContract = await waveContractFactory.deploy(unlockTime,
{ value: lockedAmount }
);
await waveContract.deployed();
console.log("Contract deployed to:", waveContract.address);
}
but the problem is it will give me an error about the argument.
even if it's the same code that the documentation suggest here: https://hardhat.org/hardhat-runner/docs/guides/deploying.
First I have written code in a different manner from buildspace website as a part of learning about web3.
// from buildspace website
const main = async () => {
const waveContractFactory = await hre.ethers.getContractFactory("WavePortal");
const waveContract = await waveContractFactory.deploy({
value: hre.ethers.utils.parseEther("0.001"),
});
await waveContract.deployed();
console.log("WavePortal address: ", waveContract.address);
};
This above code from buildspace but the problem is it will also give the error and I thought it could be the old deprecated code so I look into docs.

The JS deploy() function accepts N required params, followed by 1 optional:
N arguments of the Solidity constructor
1 optional object that overridesĀ default params of the deploying transaction (in your case the value)
Based on the error message "Expected 0-1 arguments", the WavePortal constructor expects 0 params. Which makes the deploy() function to expect 0 constructor params, plus the 1 optional overriding object.
However your code is trying to pass unlockTime as the constructor param.
Solution: Remove the unlockTime from the JS code - or accept it in the Solidity code.

Related

Shopify Storage Redis Issue with Node React App

I have added session storage in serve.js as follows :-
import SessionHandler from "./SessionHandler";
const sessionStorage = new SessionHandler();
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.October21,
IS_EMBEDDED_APP: false,
// This should be replaced with your preferred storage strategy
//SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
SESSION_STORAGE: new Shopify.Session.CustomSessionStorage(
sessionStorage.storeCallback,
sessionStorage.loadCallback,
sessionStorage.deleteCallback
),
});
My router get function is
router.get("(.*)", async (ctx) => {
const shop = ctx.query.shop;
let documentQuery = { shop: shop };
let data = await SessionStorage.findOne(documentQuery); //this finds the store in the session table
if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
if (data == null) {
ctx.redirect(`/auth?shop=${shop}`);
} else {
await handleRequest(ctx);
}
} else {
await handleRequest(ctx);
}
});
and than in the SessionHandler file added code as attached in file ,
but when I run install the app it goes to the storeCallback , loadcallback and deletecallback function multiple times
StoreCallback Function Code
Load and delete callback function code
sorry I have edited my answer as I think its incorrect . all I can say for now is to look at this example:https://github.com/Shopify/shopify-api-node/blob/main/docs/usage/customsessions.md
if you havent already..

How to execute strings of expression in an array with Ramda

I've got an array where strings of expression are listed.
const newPIXI = ["container1 = new PIXI.Container();","container2 = new PIXI.Container();","container3 = new PIXI.Container();"]
I managed to run this with (Function(...newPIXI))()
How can I do this with Ramda?
I tried R.forEach , but didn't work.
These are strings, and not functions. To run them you need to evaluate them using eval() (or Function and then run them). Each string is an expression, and not an actual function. Running the expression will create global variables (container1, container2, and container3).
You've probably heard that eval() is evil. Using eval() is a security risk, and hurts performance, and Function is only slightly less so (read more here):
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension. More importantly, a third-party code can see the
scope in which eval() was invoked, which can lead to possible attacks
in ways to which the similar Function is not susceptible.
Function's advantage is that it runs in the global scope, and can't access variables in the scope it was called in. However, Function still allows running arbitrary code.
Eval example:
const PIXI = {
Container: function () {
this.example = 'Container';
}
};
const newPIXI = ["container1 = new PIXI.Container();","container2 = new PIXI.Container();","container3 = new PIXI.Container();"]
newPIXI.forEach(x => eval(x))
console.log({ container1, container2, container3 });
Function example:
const PIXI = {
Container: function () {
this.example = 'Container';
}
};
const newPIXI = ["container1 = new PIXI.Container();","container2 = new PIXI.Container();","container3 = new PIXI.Container();"]
newPIXI.forEach(x => Function(x)())
console.log({ container1, container2, container3 });
It's better to pass data that tells the browser what you want to do (a command), and not how to do it. Then in the code you can decide how to interpret the command. For example:
const PIXI = {
Container: function () {
this.example = 'Container';
}
};
const newPIXI = [{ type: 'PIXIContainer', name: 'container1' }, { type: 'PIXIContainer', name: 'container2' }, { type: 'PIXIContainer', name: 'container3' }]
const result = {};
newPIXI.forEach(({ type, name }) => {
switch(type) {
case 'PIXIContainer':
result[name] = new PIXI.Container();
break;
default:
throw new Error(`Type ${type} not found`);
}
})
console.log(result);

Cloud function stop executing when Batch object is being used

I'm using Google Cloud Function to execute a query on bigQuery and store the result if firestore.
My problem is that as soon as I try to use the firestore batch object, the cloud function stop executing.
Using dichotomy, I think it's when I inclue the batch object code that the function suddenly stop working.
I've tried to increase the memory of the function to 1GB without luck. (currently it's using 128mb)
const {BigQuery} = require('#google-cloud/bigquery');
const {Firestore} = require('#google-cloud/firestore');
const bigquery = new BigQuery ();
const firestore = new Firestore ();
const fsCollectionName = 'ul_queteur_stats_per_year';
const queryStr = "the bigquery query";
function handleError(err){
//skipped
}
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* #param {!Object} event Event payload.
* #param {!Object} context Metadata for the event.
*/
exports.ULQueteurStatsPerYear = (event, context) => {
const pubsubMessage = event.data;
const parsedObject = JSON.parse(Buffer.from(pubsubMessage, 'base64').toString());
console.log("Recieved Message : "+JSON.stringify(parsedObject));
//{ ul_id:parsedObject.ul_id }
const queryObj = {
query: queryStr,
params: {
ul_id: parsedObject.ul_id
}
};
bigquery
.query(queryObj)
.then((data) => {
console.log("Query Successful, # rows : "+data.length+" data[0].length:"+data[0].length);
//rows : [{"amount":367.63,"weight":2399.3,"time_spent_in_minutes":420}]
const rows = data[0];
console.log("Query Successful");
const batch = firestore.batch();
console.log("Batch Created ");
console.log("Getting Collection");
const collection = firestore.collection(fsCollectionName);
console.log("Getting Collection '"+fsCollectionName+"' retrieved");
//#####################################
for(let i=0;i<rows.length;i++)
{
console.log("getting a new DocId");
const docRef = collection.doc();
console.log("Adding to docRef='"+docRef.id+"' : "+JSON.stringify(rows[i]));
batch.set(docRef, rows[i]);
console.log("Added to batch");
}
console.log("Commiting batch insert");
batch.commit().then(() => {
console.log('Successfully executed batch');
});
//#####################################
})
.catch(err => {
handleError(err);
});
};
Expected:
data inserted in Firestore
Actual result :
If I remove the code between the
//#####################################
Then I get each log in stackdriver.
(The first one saying there's 420 rows)
If I let the code between
//#####################################
(or just the batch.commit() part, or just the for loop part)
I only get the first log, and then nothing.
Query Successful, # rows : 1 data[0].length:420
Even if I put the whole code in a try/catch block with a console.log of the exception, I see no error in stack driver.
Solution
the solution is to return the bigquery promise.
So the above code should be changed to :
return bigquery
.query(queryObj)
.then(...);
Thanks Doug for the help !
You need to return a promise that resolves when all the asynchronous work is complete. Right now, you're returning nothing, which means the function will terminate and shut down almost immediately, before your query is done.
You'll need to pay attention to all the promises that your code is using, including the query, and all the batch commits. You can't ignore any promise returned by any API, else the work will be terminated before it's done.

How we can use facebook AppEventsLogger add to cart event in react native

I am trying to implement facebook SDK to track Add to cart event in my application but it was not working here is my code
First, I import facebook SDK in my application react-native-fbsdk which was installed successfully and login function are working well.
Now in product screen, I import facebook AppEventsLogger and AppEventsConstants from SDK
const FBSDK = require('react-native-fbsdk');
const {
AppEventsLogger,
AppEventsConstants
} = FBSDK;
And when user add product successfully to its carts i need to track this event in log, I try below code but it was not working
var params = {};
params[AppEventsConstants.CONTENT] = "Sample Product 1";
params[AppEventsConstants.CONTENT_ID] = "1";
params[AppEventsConstants.CONTENT_TYPE] = "Product";
params[AppEventsConstants.CURRENCY] = "INR";
AppEventsLogger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_TO_WISHLIST, 40, params)
Above code give me an undefined error. Please help me how to implement this.
Unfortunately, react-native-fbsdk doesn't provide constants of standard event names and parameter names. After some research, I found actual names are listed in Marketing API documentation (why not App Events?).
I don't know if it is the right place, but you can refer to https://developers.facebook.com/docs/marketing-api/app-event-api/ for actual standard event names and parameter names. At least it worked in my case. Here's my Add to Cart event code:
function logAddToCart(totalPrice, contentType, contentId, currency) {
const params = {
'fb_content_type': contentType,
'fb_content_id': contentId,
'fb_currency': currency
};
AppEventsLogger.logEvent('fb_mobile_add_to_cart', totalPrice, params);
}
u can read from the docs react-native-fbsdk
https://github.com/facebook/react-native-fbsdk/blob/17af77b48ad6ea62fa3c0f552cd8f6a699ef6a64/src/FBAppEventsLogger.js#L92
and u can find constant from this
https://github.com/facebook/facebook-android-sdk/blob/master/facebook-core/src/main/java/com/facebook/appevents/AppEventsConstants.java#L33-L312
// helpers
import { AppEventsLogger } from 'react-native-fbsdk'
export const FB_ADDED_TO_CART = 'fb_mobile_add_to_cart'
export async function logAdsEvent(eventName, ...args) {
let valueToSum = 0
if (typeof args[0] === 'number') {
valueToSum = args.shift()
}
let parameters = null
if (typeof args[0] === 'object') {
parameters = toSnakeCase(args[0])
}
AppEventsLogger.logEvent(eventName, valueToSum, parameters)
}
implementation
import helpers
logAdsEvent(FB_ADDED_TO_CART, result.stores[0].subTotal || 0, {
fbContent: JSON.stringify(result.stores[0]),
fbCurrency: 'IDR'
})

Solidity test case to check "withdraw" function in a contract?

I want to write a test case to check if my withdraw function works correctly. The code looks like this:
function withdraw(uint _amount, address _to) public onlyAuthors {
require(!isNullAddress(_to));
require(_amount <= this.balance);
_to.transfer(_amount);
}
But in a test case, it looks like this.balance or [some_address].balance are not available. Is there any good way to test this kind of function in a unit test?
1) make a contract factory:
import web3 from './web3';
import contractFactory from './build/ContractFactory.json';
const instance = new web3.eth.Contract(
JSON.parse(contractFactory.interface),
'<address of deployed contract>'
);
export default instance;
2)In your test you new up a contract and do the required actions to get the balance in a state that you want to test against. In your test file:
const compiledFactory = require('../ethereum/build/ContractFactory.json');
const compiledContract = require('../ethereum/build/Contract.json');
beforeEach(async () => {
accounts = await web3.eth.getAccounts();
factory = await new web3.eth.Contract(JSON.parse(compiledFactory.interface))
.deploy({ data : compiledFactory.bytecode })
.send({ from : accounts[0], gas : '1000000' });
factory.setProvider(provider);
await factory.methods.createContract('100').send({
from : accounts[ 0 ],
gas : '1000000'
});
ect. This step will vary according to your contract.
3)Try to interact with the contract(E.G. attempt to withdrawal more than the amount you are allowed or whatever. Then expect the behavior you are testing for.
I think you can use web3.eth.getBalance(address) to retrieve contract balance.