Failing to send an ERC20 token using web3.js - blockchain

I've been struggling to send a token transaction using web3 still after I've read several posts and guides. I'm using human-standard-token-abi to get the ERC20 abi. I'm just trying to transfer 10 ZRX from one address of mine to another.
Here's the function that is failing.
var Tx = require('ethereumjs-tx');
const abi = require('human-standard-token-abi')
import * as Web3 from 'web3';
const fromAddress = '0xB03...'.toLowerCase();
const secondaryAddress = '0xF75...'.toLowerCase();
const zrxAddress = '0xe41d...';
deposit(zrxAddress, secondaryAddress, '10');
function deposit(tokenAddress:string, depositAddress:string, amount:string) {
var count = web3.eth.getTransactionCount(fromAddress);
var contract = web3.eth.contract(abi).at(tokenAddress);
console.log('Contract Address :' + contract.address);
try {
var rawTransaction = {
"from": fromAddress,
"nonce": web3.toHex(count),
"gasPrice": "0x04e3b29200",
"gasLimit": "0x7458",
"to": contract.address,
"value": "0x0",
"data": contract.transfer(depositAddress, size),
"chainId": "0x01"
}
console.log(rawTransaction);
var privKey = new Buffer(key, 'hex');
var tx = new Tx(rawTransaction);
console.log(tx);
//tx.sign(privKey);
var serializedTx = tx.serialize();
} catch (err) {
console.log('\n\nfailed to build');
console.log(err);
}
try {
console.log('\n\nAttempting to send tx');
web3.eth.sendTransaction(tx, function(err, hash) {
if(!err)
console.log(hash);
else
console.log(err);
});
} catch (err) {
console.log('\nfailed to send');
console.log(err);
}
}
I'm currently failing at just building the raw transaction. Here is the error output.
Error: invalid address
at inputAddressFormatter (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/formatters.js:279:11)
at inputTransactionFormatter (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/formatters.js:101:20)
at /home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:90:28
at Array.map (<anonymous>)
at Method.formatInput (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:88:32)
at Method.toPayload (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:116:23)
at Eth.send [as sendTransaction] (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/method.js:141:30)
at SolidityFunction.sendTransaction (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/function.js:170:26)
at SolidityFunction.execute (/home/jall/ZeroExTrading/node_modules/web3/lib/web3/function.js:256:37)
at deposit (/home/jall/ZeroExTrading/lib/Transfer.js:56:30)
It seems to be rejecting one of the addresses I'm feeding it but I'm not sure which one. When I log out the tokenAddress, contract.address, and my two addresses they're all defined. But in the web3 source code I added a print statement to see which address it was saying is invalid and the address it gets is 'undefined'.

Your data portion in the tx object is not correct (there may be other issues as well, but that part stands out). You need to pass in the encoded string for your method call. You're actually trying to call the transfer method when setting data.
var rawTransaction = {
"from": fromAddress,
"nonce": web3.toHex(count),
"gasPrice": "0x04e3b29200",
"gasLimit": "0x7458",
"to": contract.address,
"value": "0x0",
"data": contract.transfer.getData(depositAddress, amount),
"chainId": "0x01"
}
(I also changed size to amount. Not sure where size came from.)

Related

How to create signature as an input for type Vec<u8> on smart contract

I'm trying to create a signature for my function in smart contract but it return "invalid type: map, expected a sequence" error.
Here is the code:
async function onSign() {
const nearConfig = getConfig('development')
// Initialize connection to the NEAR testnet
const near = await connect(Object.assign({ deps: { keyStore: new keyStores.BrowserLocalStorageKeyStore() } }, nearConfig))
window.near = near
// Initializing Wallet based Account. It can work with NEAR testnet wallet that
// is hosted at https://wallet.testnet.near.org
window.walletConnection = new WalletConnection(near)
// Getting the Account ID. If still unauthorized, it's just empty string
window.accountId = window.walletConnection.account()
let account = window.accountId;
const realSigner = account.connection.signer
let key2 = await realSigner.keyStore.getKey(account.connection.networkId, account.accountId)
let mess = 'zxczxvzvx';
let encodedMess = str2ab(mess);
let signature = await key2.sign(encodedMess);
console.log(signature);
let a = await wallet.callMethod({
contractId: "dev-1668740733204-48404403176628",
method: "ft_transfer_call",
args: {
"receiver_id": "dev-1669022432132-58804567266197",
"amount": "0",
"memo": "None",
"msg": "create_room",
"_advisor": "dev-1669018198583-29903555965521",
"_amount_per_minute": "1",
"_room_id": "1",
"_minutes_lasts": 5,
"_signature": Buffer.from(signature.signature, 'hex'),
"_signer": "tungleanh.testnet",
}
})
}
Here is the parameters on smart contract:
&mut self,
receiver_id: AccountId,
amount: U128,
memo: Option,
msg: String,
_advisor: Option,
_amount_per_minute: Option,
_room_id: Option,
_minutes_lasts: Option,
_signature: Option<Vec>,
_signer: Option<Vec>,
How can I fix this?

Eth private chain sent transaction to smartcontract error "Transaction has been reverted by the EVM"

I'm newbie and now in progress for develop some smartcontract use on ethereum private chain.
I have created KeepPolicy.sol for keep policy data to blockchain, and have dapp for call method in KeepPolicy.sol.
The problem is I got error message in response when call the method. The error message is
{
"message": "Transaction has been reverted by the EVM:\n{\n "blockHash": "0x11378a4cdaa39bf77b68d8a522d6f337eb897182f6110844e4b6b0b6ea14ef54",\n "blockNumber": 4349,\n "contractAddress": null,\n "cumulativeGasUsed": 23144,\n "effectiveGasPrice": 0,\n "from": "0x2013291683023bae332f1e47d378f50265c3d88e",\n "gasUsed": 23144,\n "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",\n "status": false,\n "to": "0xd16ea25805abf4e6defad30e6669fe68dd176aed",\n "transactionHash": "0xaab5b843ba14d2a4ff63a1a91e64f4fed7bbbdee8c7f13870d2f6132155f8d4a",\n "transactionIndex": 0,\n "type": "0x0",\n "events": {}\n}"
}
and i have some related code here.
send transaction, call setPolicy
return new Promise(function (resolve, reject) {
contract.methods.setPolicy(hashId, hashHospitalString, encHospitalString, encPub).send({ from: admin, gas: 100000 })
.then(function (receipt) {
if (receipt) {
console.log('transaction receipt', receipt)
resolve(receipt)
}
resolve({result: false})
}).catch(function (err) {
return reject(err)
})
})
KeepPolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
contract KeepPolicy {
struct Policy {
string hashId;
string hashHospitalString;
string encHospitalString;
string encPub;
}
uint256 countId;
mapping (uint256 => Policy) public policies;
receive() external payable {}
function setPolicy(string memory _hashId, string memory _hashHospitalString, string memory _encHospitalString, string memory _encPub)
external payable {
uint256 count = countId++;
policies[count].hashId = _hashId;
policies[count].hashHospitalString = _hashHospitalString;
policies[count].encHospitalString = _encHospitalString;
policies[count].encPub = _encPub;
}
}
The function is payable. Please try to add value argument to your transaction or remove payable from the contract. E.g.: .send({ from: admin, gas: 100000, value: 0 })
I close this issue, the problem is about problem when deploy smart contract.

How to properly set an API call in QML using XMLHttpRequest

I am building a small weather API as exercise to use QML and properly operate an API call using OpenWeather and you can see there a typical API response.
The problem I am having is that I can't get the API call to work. After setting a minimal example with some cities that you can see below, right next to the city it should appear the symbol of the weather, but it does not happen. The list of the icon can be found here. Source code of the MVE can be found here for completeness.
The error from the compiler: qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error
This is what is happening
This is what is expected
Typical API JSON response can be found both here and below:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
Below a snippet of code related to the API call:
main.qml
// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
var res
var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
var doc = new XMLHttpRequest()
// parse JSON data and put code result into codeList
doc.onreadystatechange = function() {
if(doc.readyState === XMLHttpRequest.DONE) {
res = doc.responseText
// parse data
var obj = JSON.parse(res) // <-- Error Here
if(typeof(obj) == 'object') {
if(obj.hasOwnProperty('query')) {
var ch = onj.query.results.channel
var item = ch.item
codeList[index] = item.condition["code"]
}
}
}
}
doc.open('GET', url, true)
doc.send()
}
In order to solve this problem I consulted several sources, first of all : official documentation and the related function. I believe it is correctly set, but I added the reference for completeness.
Also I came across this one which explained how to simply apply XMLHttpRequest.
Also I dug more into the problem to find a solution and also consulted this one which also explained how to apply the JSON parsing function. But still something is not correct.
Thanks for pointing in the right direction for solving this problem.
Below the answer to my question. I was not reading properly the JSON file and after console logging the problem the solution is below. code was correct from beginning, only the response needed to be reviewed properly and in great detail being the JSON response a bit confusing:
function getCondition() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=key', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
Hope that helps!
In your code, your url shows this: "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}". You need to replace {city id} and {your api key} with real values.
You can solve it by providing an actual city ID and API key in your request URL

Cognito UnknownError after turn on device registration

As per requirement, I need to turn on device registration to Always. However, our SRP flow starts failing with the below issue.
{ code: 'UnknownError', message: 'Unknown error, the response body from fetch is: undefined' }
After doing some research, I found one similar post, but it seems like the only solution is to turn device registration off.
It's failing while running node get-token.js script to retrieve token for our CI/CD testing pipeline.
cognitoUser.authenticateUser(authCfg, {
onSuccess: function (result) {
console.log("Result : ", result);
const token = result.getAccessToken().getJwtToken();
resolve(token)
},
onFailure: function(err) {
console.error("Failure : ", err);
console.log(new Error().stack);
reject(new Error("An error occurred: " + err))
},
newPasswordRequired: function (userAttributes, requiredAttributes) {
cognitoUser.completeNewPasswordChallenge(p, userAttributes, this);
},
});
Seems like I missed the point mentioned in this post . Adding the below code works.
const WindowMock = require('window-mock');
global.window = {localStorage: WindowMock.localStorage};
global.navigator = () => null;

Alexa function works in AWS lamda, but not from the Service Simulator

I am relatively new to AWS and Alexa skills. I am building a simple custom skill that gives you a dressing advice depending on the weather.
I have 2 custom intents : dressingTodayIntent & dressingTomorrowIntent. In the Service Simulator of the developer portal, my two intents don't work, I do get a lambda response though, but with an undefined outputSpeech, like this:
{
"version": "1.0",
"response": {
"outputSpeech": {
"type": "SSML",
"ssml": "<speak> undefined </speak>"
},
"card": null,
"reprompt": null,
"speechletResponse": {
"outputSpeech": {
"id": null,
"ssml": "<speak> undefined </speak>"
},
"card": null,
"directives": null,
"reprompt": null,
"shouldEndSession": true
}
},
"sessionAttributes": {}
}
Could it be a scope issue in my intent code?
'DressingTodayIntent': function() {
var dressingAdvice;
var speechOutput = getJSON('https://api.darksky.net/forecast/9e0495a835ed823a705a9a567eee982a/48.861317,2.348764?units=si&exclude=currently,minutely,hourly,alerts,flags',
function(err, forecast) {
if (err) {
console.log('Error occurred while trying to retrieve weather data', err);
} else {
dressingAdvice = getDressingAdvice(forecast, true);
console.log("one " + dressingAdvice);
}
console.log("two " + dressingAdvice);
return dressingAdvice;
});
console.log("three " + speechOutput);
this.response.cardRenderer("Your dressing advice for today:", speechOutput);
this.response.speak(speechOutput);
this.emit(':responseReady');
},
In AWS Lambda, I see a correct output for the first 2 logs, and an error for the 3rd one:
first log: "one " + dressingAdvice, as expected
second log: "two " + dressingAdvice, as expected
third log: "three " + undefined
Thank you for you help!
When you say "tested from AWS Lambda", I assume that you mean using the AWS console to send a JSON test message to the Lambda, then looking at the response JSON to determine if it is correct?
If so, make sure that it matches the JSON sent to/from the Alexa test page in the dev portal. Sounds like they might be different.
Also, make sure that you are linked to the correct ARN in the Alexa skill.
The undefined is likely a variable scope issue in the code.
I noticed in your response that you don't have any sessionAttributes. Is your code setting or pulling the value for the response from a session value? If so, the values need to be sent back with the sessionAttributes.
I figured out what was wrong, I needed to move the response code into the callback function, like this:
'DressingTodayIntent': function() {
var speechOutput;
var self = this;
var dressingAdvice = getJSON('https://api.darksky.net/forecast/9e0495a835ed823a705a9a567eee982a/48.861317,2.348764?units=si!ude=currently,minutely,hourly,alerts,flags',
function(err, forecast) {
if (err) {
console.log('Error occurred while trying to retrieve weather data', err);
} else {
speechOutput = getDressingAdvice(forecast, true);
}
self.response.cardRenderer("Your dressing advice for today:", speechOutput);
self.response.speak(speechOutput);
self.emit(':responseReady');
});
},