ERC 20 token issue - erc20

I need to test erc20 token transaction in localhost. For that I had run Etherium wallet on my terminal using rpc. I had an error of unknown address. Below is my code.
I had given all details like contract address, others address in the script directly. I am using web3js.
<?php
$abi_get=file_get_contents('https://api.etherscan.io/api?module=contract&action=getabi&address=0xf5e7f08c91b5d8579746eaad70ac509e94e2f1d3&apikey=5N8DNJPJJH5J7X7IN3VHSBBCHDIE9SV3GA');
$abi_result = json_decode($abi_get,true);
$abi=$abi_result['result'];
?>
<script src="<?php echo js_url();?>/web3.min.js"></script>
<script>
transfer();
var http = require('http');
var Web3 = require('web3');
var Tx = require('ethereumjs-tx');
var Bf=require('Buffer');
function transfer()
{
//var Web3 = require("web3");
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8585"));
}
//var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var from_address = "0x26650Af2BF9093A32e0E8361F89dB1e7B7609442";
var toAddress = "0xabef6c10571f45ceaf245dddf98894527c87677f";
var value = 10;
var abiArray = <?php echo $abi; ?>;
var contractAddress = "0xf5e7f08c91b5d8579746eaad70ac509e94e2f1d3";
var contract = web3.eth.contract(abiArray).at(contractAddress);
var bal=web3.fromWei(contract.balanceOf(from_address),"ether");
console.log(bal);
var trans=contract.transfer(toAddress,web3.toWei(1,"ether"),{from:from_address});
var rawTransaction = {
"from": from_address,
"nonce": web3.toHex(count),
"gasPrice": "0x04e3b29200",
"gasLimit": "0x7458",
"to": contractAddress,
"value": "0x0",
"data": contract.transfer.getData(toAddress, 10, {from: from_address}),
"chainId": 0x03
};
var privKey = new Buffer('83c737e4e5030e1fe3a2ed4762147cf9d9da80132d904d424460ed41d4591afd', 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
console.log(hash);
else
console.log(err);
});
}
</script>

Sorry low rep or I would comment:
You might need to sign the transaction. Sending data is different on etherium than viewing data. Specifically if you aren't using something like metamask as your provider (you are using local host) you will have to manually sign transactions.
Also I'm not sure if this is a throwaway wallet but never post your private key!

Related

Unable to deploy NFT in terminal

I already deployed my smart contract to my wallet and connected it to my Alchemy account.
Here are my codings (Note that my contract address, PUBLIC_KEY, PRIVATE_KEY, API_URL and alchemy address are edited for security purposes).
mint-nft.js
require('dotenv').config();
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json");
const contractAddress = "My_Contract_Adress";
const nftContract = new web3.eth.Contract(contract.abi, contractAddress);
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()
};
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
signPromise.then((signedTx) => {
web3.eth.sendSignedTransaction(signedTx.rawTransaction, function(err, hash) {
if (!err) {
console.log("The hash of your transaction is: ", hash, "\nCheck Alchemy's Mempool to view the status of your transaction!");
} else {
console.log("Something went wrong when submitting your transaction:", err)
}
});
}).catch((err) => {
console.log(" Promise failed:", err);
});
}
mintNFT("https://gateway.pinata.cloud/ipfs/My_NFT_Picture_Hash");
alchemyContext.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeAlchemyContext = void 0;
var tslib_1 = require("tslib");
var sturdy_websocket_1 = tslib_1.__importDefault(require("sturdy-websocket"));
var websocket_1 = require("websocket");
var jsonRpc_1 = require("../util/jsonRpc");
var version_1 = require("../version");
var alchemySendHttp_1 = require("./alchemySendHttp");
var alchemySendWebSocket_1 = require("./alchemySendWebSocket");
var httpProvider_1 = require("./httpProvider");
var sendPayload_1 = require("./sendPayload");
var webSocketProvider_1 = require("./webSocketProvider");
var NODE_MAX_WS_FRAME_SIZE = 100 * 1024 * 1024; // 100 MB
function makeAlchemyContext(url, config) {
var makePayload = jsonRpc_1.makePayloadFactory();
if (/^https?:\/\//.test(url)) {
var alchemySend = alchemySendHttp_1.makeHttpSender(url);
var _a = sendPayload_1.makePayloadSender(alchemySend, config), sendPayload = _a.sendPayload, setWriteProvider = _a.setWriteProvider;
var senders = jsonRpc_1.makeSenders(sendPayload, makePayload);
var provider = httpProvider_1.makeAlchemyHttpProvider(sendPayload);
return { provider: provider, senders: senders, setWriteProvider: setWriteProvider };
}
else if (/^wss?:\/\//.test(url)) {
var protocol = isAlchemyUrl(url) ? "alchemy-web3-" + version_1.VERSION : undefined;
var ws = new sturdy_websocket_1.default(url, protocol, {
wsConstructor: getWebSocketConstructor(),
});
var alchemySend = alchemySendWebSocket_1.makeWebSocketSender(ws);
var _b = sendPayload_1.makePayloadSender(alchemySend, config), sendPayload = _b.sendPayload, setWriteProvider = _b.setWriteProvider;
var senders = jsonRpc_1.makeSenders(sendPayload, makePayload);
var provider = new webSocketProvider_1.AlchemyWebSocketProvider(ws, sendPayload, senders);
return { provider: provider, senders: senders, setWriteProvider: setWriteProvider };
}
else {
throw new Error("Alchemy URL protocol must be one of http, https, ws, or wss. Recieved: " + url);
}
}
exports.makeAlchemyContext = makeAlchemyContext;
function getWebSocketConstructor() {
return isNodeEnvironment()
? function (url, protocols) {
return new websocket_1.w3cwebsocket(url, protocols, undefined, undefined, undefined, {
maxReceivedMessageSize: NODE_MAX_WS_FRAME_SIZE,
maxReceivedFrameSize: NODE_MAX_WS_FRAME_SIZE,
});
}
: WebSocket;
}
function isNodeEnvironment() {
return (typeof process !== "undefined" &&
process != null &&
process.versions != null &&
process.versions.node != null);
}
function isAlchemyUrl(url) {
return url.indexOf("alchemyapi.io") >= 0;
}
.env
API_URL = "https://eth-rinkeby.alchemyapi.io/v2/KEY"
PRIVATE_KEY = "MY_PRIVATE_KEY"
PUBLIC_KEY = "MY_PUBLIC_KEY"
But then I was trying to deploy my NFT with metadata and nft-mint.js, I got these error.
Can anyone please tell me what was the error about?
Your issue may be with dotenv not reading in the values in your .env.
If you add console.log(API_URL), is it correct or is it undefined?
If it is undefined, I was able to resolve the issue by adding the path to my .env like so:
require('dotenv').config({path:"../.env"});
(In my case my mint-nft.js was in scripts/mint-nft.js
and .env is in the root directory.)

Sending a transaction results in "invalid sender"

I'm attempting to call a function on my smart contract (Ropsten) using web3 via an Infura node. I've created a test account in Metmask and have exported the account address and private key. The details look correct, however I am getting the error {"code":-32000,"message":"invalid sender"}. I'm guessing this is a problem with the signing of the transaction?
Here's my code
const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;
const fs = require('fs');
const pk = Buffer.from('PRIVATE KEY FROM METAMASK', 'hex')
const sourceAccount = 'ACCOUNT ADDRESS FROM METAMASK'
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/API_KEY"));
const consumerAddress = '0xc36577aa0171f649be6bd7205148ed83c07198ee';
web3.eth.defaultAccount = sourceAccount;
//Get Consumer contract instance
const consumerAbi = JSON.parse(fs.readFileSync('rental-contract-abi.json', 'utf8'));
let consumerContract = new web3.eth.Contract(consumerAbi, consumerAddress);
const myData = consumerContract.methods.checkDate("e716efba3b404da98e28faaa2939c0fd","2019-06-04","AU-NSW").encodeABI();
web3.eth.getTransactionCount(sourceAccount, (err, txCount) => {
// Build the transaction
const txObject = {
nonce: web3.utils.toHex(txCount),
to: consumerAddress,
from: sourceAccount,
chainId: 3,
value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),
gasLimit: web3.utils.toHex(2100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
data: myData
}
// Sign the transaction
const tx = new Tx(txObject);
tx.sign(pk);
const feeCost = tx.getUpfrontCost()
console.log('Total Amount of ETH needed:' + web3.utils.fromWei(feeCost.toString(), 'ether'))
console.log('---Serialized TX----')
console.log(tx.serialize().toString('hex'))
console.log('--------------------')
const serializedTx = tx.serialize();
const raw = '0x' + serializedTx.toString('hex');
// Broadcast the transaction
const transaction = web3.eth.sendSignedTransaction(raw, (err, tx) => {
console.log(tx);
console.log(err);
});
});
You need to add network information while signing the transaction. Refer to latest web3 docs. Change signing transaction code to :
const tx = new Tx(txObject,{'chain':'ropsten'});

Node.js - How to get callback function's variable out of function?

balance.js
var CoinStack = require('coinstack-sdk-js')
var accessKey = 'c7dbfacbdf1510889b38c01b8440b1';
var secretKey = '10e88e9904f29c98356fd2d12b26de';
var client = new CoinStack(accessKey, secretKey);
client.getBalance(address, function(err, balance) {
console.log('balance', balance)
});
I have a this code, then i want to get var balance out of function
i don't know what to do, i want fixed code
i need your helps
You can not, consider using Promises like this :
var CoinStack = require('coinstack-sdk-js')
var accessKey = 'c7dbfacbdf1510889b38c01b8440b1';
var secretKey = '10e88e9904f29c98356fd2d12b26de';
var client = new CoinStack(accessKey, secretKey);
let balancePromise = new Promise((resolve, reject)=>{
client.getBalance(address, function(err, balance) {
if(err)
reject(err)
else
resolve(balance);
});
})
// how to get balance value
balancePromise.then((balance)=>{
console.log('balance', balance)
}).catch((error)=>{
console.log('error', error)
})

Node js client for grpc server

I have GRPC server running using openssl - static way and I am trying to connect to server using nodejs client
I do not see any error but I do not see its connecting to server either.
Please share if you have any sample.
Please refer code below:
var rootCertPath = path.join('.','.', 'server-root.PEM');
var privateCertPath = path.join('.','.', 'server-private.PEM');
var domainCertPath = path.join('.','.', 'server-domain.PEM');
var rootCert = fs.readFileSync(rootCertPath);
var privateCert = fs.readFileSync(privateCertPath);
var domainCert = fs.readFileSync(domainCertPath);
var buf1 = new Buffer('rootCert');
var buf2 = new Buffer('privateCert');
var buf3 = new Buffer('domainCert');
var chat_proto = grpc.load("Chat.proto").com.company.grpc;
var client = new chat_proto.ChatService('https://servervip:443',grpc.credentials.createSsl(buf1,buf2,buf3));
Chat.proto
syntax = "proto3";
// Service definition.
service ChatService {
// Sends a chat
rpc chat(stream ChatMessage) returns (stream ChatMessageFromServer) {}
}
// The request message containing the user's name.
message ChatMessage {
string name = 1;
string message = 2;
}
// The response message containing the greetings
message ChatMessageFromServer {
string name = 1;
string message = 2;
}
//Code to make a request
var username = process.argv[2];
var stdin = process.openStdin();
function main() {
console.log("starting");
console.log(client); // prints { '$channel': Channel {} }
var chat=client.chat();
chat.on('data', function(msg) {
console.log(msg.name + ': ' + msg.message);
console.log("after message");
});
stdin.addListener('data',function(input) {
chat.write({ name: username, message: input.toString().trim()
});
});
}
main();
so good new is - below thing worked for me
var rootCertPath = path.join('.','.', 'roots.PEM');
var rootCert = fs.readFileSync(rootCertPath);
var chat_proto = grpc.load("Chat.proto").com.americanexpress.grpc.chat;
var client = new chat_proto.ChatService('servervip:443',grpc.credentials.createSsl(rootCert));
Looks like an issue with the cert - I used the default roots.PEM in grpc client and it worked for me. will look internally to have correct root of my servervip CA certificate chain.
Thanks all for your support

Authenticated Commands With MtGox's Streaming API

I am using nodejs with socket.io-client to connect to the MtGox Streaming API described here: https://en.bitcoin.it/wiki/MtGox/API/Streaming#Authenticated_commands
The examples are written in php and I tried my best to convert them to JS but I keep getting a response from the server "Invalid call"
var sec_key_buffer = Buffer(secret_key, 'base64');
var hmac = crypto.createHmac('sha512', sec_key_buffer);
var nonce = Date.now() + "";
var id = crypto.createHash('md5').update(nonce).digest('hex');
var query = {
"call": 'private/info',
"id": id,
"nonce": nonce
};
var body = JSON.stringify(query);
var sign = hmac.update(body).digest('binary');
// The 'api_key' field has already stripped of the '-' character
var callBody = new Buffer(api_key + sign + body).toString('base64');
// 'connection' is the socket.io connection to 'https://socketio.mtgox.com/mtgox'
connection.json.send({
"op": "call",
"id": id,
"call": callBody,
"context": 'mtgox.com'
});
Any help would be appreciated.
Here's what seemed to work for me:
var io = require('socket.io-client');
var crypto = require('crypto');
var socket = io.connect('https://socketio.mtgox.com/mtgox');
var MTGOX_API_INFO = {
key: '<YOUR_KEY>',
secret: '<YOUR_SECRET>'
}
var MTGOX_CHANNELS = {
trade: 'dbf1dee9-4f2e-4a08-8cb7-748919a71b21',
depth: '24e67e0d-1cad-4cc0-9e7a-f8523ef460fe',
ticker: 'd5f06780-30a8-4a48-a2f8-7ed181b4a13f'
}
// unsubscribe from depth and trade messages
socket.emit('message', {
op: 'unsubscribe',
channel: MTGOX_CHANNELS.trade
});
socket.emit('message', {
op: 'unsubscribe',
channel: MTGOX_CHANNELS.depth
});
socket.emit('message', {
op: 'unsubscribe',
channel: MTGOX_CHANNELS.ticker
});
var getNonce = function() {
return ((new Date()).getTime() * 1000).toString();
}
var nonce = getNonce();
var requestId = crypto.createHash('md5').update(nonce).digest('hex');
var query = {
id: requestId,
call: 'private/info',
nonce: nonce
// params: {},
// item: 'BTC',
// currency: 'USD'
};
var queryJSON = JSON.stringify(query);
var signedQuery = crypto.createHmac('sha512', new Buffer(MTGOX_API_INFO.secret, 'base64')).update(queryJSON).digest('binary');
var binKey = (new Buffer(MTGOX_API_INFO.key.replace(/-/g, ''), 'hex')).toString('binary');
var buffer = new Buffer(binKey + signedQuery + queryJSON, 'binary');
var call = buffer.toString('base64');
var command = {
op: 'call',
id: requestId,
call: call,
context: 'mtgox.com'
};
console.log("REQUEST:", command);
socket.emit('message', command);
socket.on('message', function(data) {
console.log(data);
});
UPDATE: I've also abstracted it into a simple node module.
You must hex decode the api key to raw bytes before appending the hash and message content.
Not familiar enough with node.js to provide code, but in Java (using Guava) it's:
byte[] apiKey = BaseEncoding.base16().lowerCase().decode(API_KEY.replace("-", ""));

Resources