Fail to swap ETH to dai using uniswap sdk with web3.js - solidity

I am coming across an issue swapping weth to dai using uniswap Node.js SDK with web3.js.
My code is below:
const dai = await Fetcher.fetchTokenData(net, daiAddress);
const weth = await Fetcher.fetchTokenData(net, wethAddress);
const pair = await Fetcher.fetchPairData(dai, weth);
const route = new Route([pair], weth);
console.log(route.midPrice.toSignificant(6))
console.log(route.midPrice.invert().toSignificant(6))
const trade = new Trade(route, new TokenAmount(weth, "1000000000000000000"), TradeType.EXACT_INPUT)
console.log(trade.executionPrice.toSignificant(6))
const slippageTollerance = new Percent("10", "10000")
const amountOutMin = trade.minimumAmountOut(slippageTollerance)
// const amountOutMin = web3.current.utils.toBN(amountOutMinRaw)
const path = [weth.address, dai.address]
const deadline = Math.floor(Date.now() / 1000 ) + 60*20
const amountIn = trade.inputAmount.raw
const to = ""
uniSwapRouter.current = new web3.current.eth.Contract(
uniRouterAbi,
"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
);
const tx = await uniSwapRouter.current.methods.swapExactETHForTokens(
// amountIn,
1,
to,
path,
deadline
).send({
from:accounts[0],
gasLimit: 8000000,
gasPrice: web3.current.utils.toWei('100', 'Gwei'),
value: web3.current.utils.toWei('1', 'Ether')
})
console.log(tx.hash)
And it turns error:
Unhandled Rejection (Error): expected array value (argument="path", value="", code=INVALID_ARGUMENT, version=abi/5.0.7)
Anyone helps let me know which part I mess up. I have been struggling with it for two days.
I am running it on kovan testnet and I am sure that I have some DAI(11.647) & ETH(2.4845) in my kovan metamask wallet.

I think I found out where the thing gone wrong.
The deadline might be too short to go through the transaction.
It turned out ok after expending the deadline.

Related

Solidity calling payable function with arguments with hardhat ethers.js

I'm testing this function:
function Deposit(uint256 StopLoss) public payable {//Deposita quantity i es registre
//Pay subscription
if (msg.value == 0){
revert Quantity_zero();
}
//Add wallet to the s_Wallets
s_Wallets.push(payable(msg.sender));
//Start subscription time
Dades storage dades = s_Registre[msg.sender];
dades.Quantity += msg.value;
dades.Stop = StopLoss;
}
When sending value and StopLoss argument it allways send me some error.
This is the js testing code being 1850 the argument StopLoss value and sending a 5 ETH value.
describe("Subscription", async function () {//PriceConversion
it("Subscribes the deployer", async function () {
await MarketOrder.Deposit(1850, {value: ethers.utils.parseEther("5")})
const Quantity = await MarketOrder.CallQuantity()
console.log(`Q: ${Quantity}`)
const Stop = await MarketOrder.CallStop()
console.log(`S: ${Stop}`)
assert.equal(Quantity.toString(), 1850)
assert.equal(Stop.toString(), 5)
}
})
This is the error:
1) MarketOrder Unit Tests
Subscription
Subscribes the deployer:
Error: invalid BigNumber value (argument="value", value=[1850], code=INVALID_ARGUMENT, version=bignumber/5.6.2)
at Logger.makeError (node_modules/#ethersproject/logger/src.ts/index.ts:261:28)
at Logger.throwError (node_modules/#ethersproject/logger/src.ts/index.ts:273:20)
at Logger.throwArgumentError (node_modules/#ethersproject/logger/src.ts/index.ts:277:21)
at Function.BigNumber.from (node_modules/#ethersproject/bignumber/src.ts/bignumber.ts:289:23)
at NumberCoder.encode (node_modules/#ethersproject/abi/src.ts/coders/number.ts:25:27)
at /home/oriok/hh-ff/1.uniswapV3/node_modules/#ethersproject/abi/src.ts/coders/array.ts:71:19
at Array.forEach (<anonymous>)
at pack (node_modules/#ethersproject/abi/src.ts/coders/array.ts:54:12)
at TupleCoder.encode (node_modules/#ethersproject/abi/src.ts/coders/tuple.ts:54:20)
at AbiCoder.encode (node_modules/#ethersproject/abi/src.ts/abi-coder.ts:111:15)
error Command failed with exit code 1.
Does anyone know how to send argument + value properly?? I have tryed many codes but not working.
Ty guys!
ethers.utils.parseEther returns object with BigNumber in it..
you have to convert it into string before using it in the test..
Eg:
ethers.utils.parseEther("5").toString()
Refer.. https://docs.ethers.io/v5/api/utils/display-logic/#utils-parseEther

req.query returns nothing

Trying to get variable from http://localhost:3000/categories/subcategories?category_id=13 but req.query returns empty result.
app.get('/subcategories', (req, res) => {
let category_id = req.query.category_id
console.log(req.query)
db.query('SELECT subcategory_name FROM subcategories WHERE category_id=(?)',
[category_id],
(err, result) =>{
res.send({category_id})
});
})
Is this possibly a problem with the way I've set up my server?
See how you are passing the data , directly entering the data or from another URL you are passing the data.
Ensuring you are not sending data via req.body. Ref :
Empty req.query on ExpressJS
or check res.send({category_id}) . Try printing res.send({"category_id": category_id}) . or see console.log(JSON.stringify(req.query))
Or Extract Query Parameters Without Express
const url = require('url');
const querystring = require('querystring');
let rawUrl = 'https://stackabuse.com/?page=2&limit=3';
let parsedUrl = url.parse(rawUrl);
let parsedQs = querystring.parse(parsedUrl.query);
https://stackabuse.com/get-query-strings-and-parameters-in-express-js/

Forge Data Visualization not working on Revit rooms [ITA]

I followed the tutorials from the Forge Data Visualization extension documentation: https://forge.autodesk.com/en/docs/dataviz/v1/developers_guide/quickstart/ on a Revit file. I used the generateMasterViews option to translate the model and I can see the Rooms on the viewer, however I have problems coloring the surfaces of the floors: it seems that the ModelStructureInfo has no rooms.
The result of the ModelStructureInfo on the viewer.model is:
t {model: d, rooms: null}
Here is my code, I added the ITA localized versions of Rooms as 3rd parameter ("Locali"):
const dataVizExtn = await this.viewer.loadExtension("Autodesk.DataVisualization");
// Model Structure Info
let viewerDocument = this.viewer.model.getDocumentNode().getDocument();
const aecModelData = await viewerDocument.downloadAecModelData();
let levelsExt;
if (aecModelData) {
levelsExt = await viewer.loadExtension("Autodesk.AEC.LevelsExtension", {
doNotCreateUI: true
});
}
// get FloorInfo
const floorData = levelsExt.floorSelector.floorData;
const floor = floorData[2];
levelsExt.floorSelector.selectFloor(floor.index, true);
const model = this.viewer.model;
const structureInfo = new Autodesk.DataVisualization.Core.ModelStructureInfo(model);
let levelRoomsMap = await structureInfo.getLevelRoomsMap();
let rooms = levelRoomsMap.getRoomsOnLevel("2 - P2", false);
// Generates `SurfaceShadingData` after assigning each device to a room (Rooms--> Locali).
const shadingData = await structureInfo.generateSurfaceShadingData(devices, undefined, "Locali");
// Use the resulting shading data to generate heatmap from.
await dataVizExtn.setupSurfaceShading(model, shadingData, {
type: "PlanarHeatmap",
placePosition: "min",
usingSlicing: true,
});
// Register a few color stops for sensor values in range [0.0, 1.0]
const sensorType = "Temperature";
const sensorColors = [0x0000ff, 0x00ff00, 0xffff00, 0xff0000];
dataVizExtn.registerSurfaceShadingColors(sensorType, sensorColors);
// Function that provides a [0,1] value for the planar heatmap
function getSensorValue(surfaceShadingPoint, sensorType, pointData) {
const { x, y } = pointData;
const sensorValue = computeSensorValue(x, y);
return clamp(sensorValue, 0.0, 1.0);
}
const sensorType = "Temperature";
dataVizExtn.renderSurfaceShading(floor.name, sensorType, getSensorValue);
How can I solve this issue? Is there something else to do when using a different localization?
Here is a snapshot of what I get from the console:
Which viewer version you're using? There was an issue causing ModelStructureInfo cannot produce the correct LevelRoomsMap, but it gets fixed now. Please use v7.43.0 and try again. Here is the snapshot of my test:
BTW, if you see t {model: d, rooms: null} while constructing the ModelStructureInfo, it's alright, since the room data will be produced after you called ModelStructureInfo#getLevelRoomsMap or ModelStructureInfo#getRoomList.

Why my JSONP Code doesn't save results into PDF file after converting from template in Google App Script

I'm trying to save my results into PDF file after google sheet calculation. Here's my google sheet file: Google sheet(img)
After someone submit my form J Column sum all answers and gets 39. Then I want to convert my template file template(img) to PDF, so I wrote this code:
function afterFormSubmit(e) {
Logger.log(JSON.stringify(e));
var formValues = e.namedValues;
Logger.log(formValues);
const info = e.namedValues;
createPDF(info);
}
function createPDF(info){
const pdfFolder = DriveApp.getFolderById("1YPyX8gv3W-JXR0uovMdr");
const tempFolder = DriveApp.getFolderById("1m9Xcc9hmhJjc83cSgCW26u");
const templateDoc = DriveApp.getFileById("1r4m3-FtzMzlO_SmGMPuGraJhEIBsQA");
const newTempFile = templateDoc.makeCopy(tempFolder);
const openDoc = DocumentApp.openById(newTempFile.getId())
const body = openDoc.getBody();
body.replaceText("{T}", info['Timestamp'][0]);
body.replaceText("{A2}" ,info['answer2'][0]);
body.replaceText("{A3}" ,info['answer3'][0]);
body.replaceText("{A4}" ,info['answer4'][0]);
body.replaceText("{A5}" ,info['answer5'][0]);
body.replaceText("{A6}" ,info['answer6'][0]);
body.replaceText("{A7}" ,info['answer7'][0]);
body.replaceText("{E}", info['Email'][0]);
body.replaceText("{R}" ,info['Results'][0]); //Please fix it: PDF Not showing/Saving Results
openDoc.saveAndClose();
const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName("Quiz finish time:"+" "+ info['Timestamp'][0]);
tempFolder.removeFile(newTempFile);
}
But when this code converts my template file to PDF he don't show/save my result {R} PDF(img), but all other body.replaceText(); works well. Maybe someone know how to deal with that (how to save/show Result into PDF file)?
I get response that my google app script code is only for google form responses... So my first code didn't works to get Results... But this one is what I'm looked for:
function afterFormSubmit() {
var ss= SpreadsheetApp.openById("YOUR_SHEET_ID").getSheetByName("SHEET_NAME");
ss.getLastRow();
var info=ss.getRange("A"+ss.getLastRow()+":J"+ss.getLastRow()).getValues()[0];
Logger.log(info);
createPDF(info);
}
function createPDF(info){
const pdfFolder = DriveApp.getFolderById("FOLDER_ID");
const tempFolder = DriveApp.getFolderById("FOLDER_ID");
const templateDoc = DriveApp.getFileById("DOC_ID");
const newTempFile = templateDoc.makeCopy(tempFolder);
const openDoc = DocumentApp.openById(newTempFile.getId())
const body = openDoc.getBody();
var dt=Utilities.formatDate(info[0],"GMT"-5.00,"MM/dd/YYYY HH:mm:ss");
body.replaceText("{T}", dt);
body.replaceText("{A3}" ,info[2]);
body.replaceText("{A4}" ,info[3]);
body.replaceText("{A5}" ,info[4]);
body.replaceText("{A6}" ,info[5]);
body.replaceText("{A7}" ,info[6]);
body.replaceText("{E}", info[7]);
body.replaceText("{A2}" ,info[8]);
body.replaceText("{R}" ,info[9]);
openDoc.saveAndClose();
const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName("Quiz finish time:"+" "+ dt);
tempFolder.removeFile(newTempFile);
}
````

HTML5 player not working on chrome

I'm new to Stackoverflow and this will be my first question. My HTML5 player works fine on Internet Explorer but doesn't work on google chrome. I'm using a PlayReady stream which is encrypted with CENC. How can I let this work on chrome? I don't have access to the servers, they're run by third parties.
Thanks
Technically it is possible to support Widevine while you're stream is PlayReady. This is possible since you use CENC. Since you don't have access to the servers like you mentioned you can use a technique called PSSH Forging. It basically replaces the pieces to make chrome think it's Widevine, since it's CENC the CDM will decrypt the video and the stream will play.
For the sake of ease i'm going to assume you use DASH.
We have here a PSSH Box:
const widevinePSSH = '0000005c7073736800000000edef8ba979d64acea3c827dcd51d21ed0000003c080112101c773709e5ab359cbed9512bc27755fa1a087573702d63656e63221848486333436557724e5a792b32564572776e64562b673d3d2a003200';
You need to replace 1c773709e5ab359cbed9512bc27755fa with your KID.
And then at the part where you insert you'r segment in the SourceBuffer (before appendSegment) you can do the following:
let segment = args[0];
segment = new Uint8Array(segment);
const newPssh = widevinePSSH.replace('1c773709e5ab359cbed9512bc27755fa', psshKid);
const subArray = new Uint8Array(DRMUtils.stringToArrayBuffer('70737368'));
let index = 0;
const found = subArray.every((item) => {
const masterIndex = segment.indexOf(item, index);
if (~masterIndex) {
index = masterIndex;
return true;
}
});
if (found) {
return originalSourceBufferAppendBuffer.apply(this, [].slice.call(args));
}
segment = DRMUtils.uInt8ArrayToHex(segment);
// Inject the forged signal
// 70737368 = pssh
segment = segment.substr(0, segment.lastIndexOf('70737368') - 8) + newPssh + segment.substr(segment.lastIndexOf('70737368') - 8);
// Fix the MOOV atom length
// 6d6f6f76 = moov
const header = segment.substr(0, segment.indexOf('6d6f6f76') - 8);
const payload = segment.substr(segment.indexOf('6d6f6f76') - 8);
const newLength = Math.floor(payload.length / 2);
segment = header + DRMUtils.intToHex(newLength, 8) + payload.substr(8);
segment = decode(segment).b;
Sadly i can only share bits and pieces but this is roughly what you should do to get it working.