I have the following code to call a smart contract function:
async function addManager(){
const networkId = await web3.eth.net.getId();
var deployedNetwork = MarketplaceArtifact.networks[networkId];
var marketplace = new web3.eth.Contract(
MarketplaceArtifact.abi,
deployedNetwork.address,
);
var address = document.getElementById('addressField').value;
const { AddManager } = marketplace.methods;
const response = await AddManager(address, { from: this.account }).call();
console.log(response);
}
Why is the console.log giving me such a response Shouldn't the call return the return value form the smart contract?
Related
I'm creating a generator that uses your google catchall domain to generate a list of email accounts and how I'm going about it, is that a function will generate a random first & last name from an array and merges it together with the catchall domain. Essentially the result would be fname + lname + domain = johndoe#domain.com, but for some reason I'm getting an error. The terminal says "Fetch is not defined" but when I define it by either the node-fetch package (const fetch = require('node-fetch');, it then says "fetch is not a function". I was attempting to use the built in Fetch API to fetch the data because the script I'm basing it off of instructed to do so, after the terminal said it wasn't defined, I tried using the node-fetch package to define the variable fetch in hopes of it fixing it, but no luck either. Does anyone have a solution on why I'm getting both fetch is not a function and fetch is not defined?
const prompt = require("prompt-sync") ({sigint: true });
const fs = require("fs").promises;
const request = require('request');
// const fetch = require('node-fetch');
const random_useragent = require('random-useragent');
const { Webhook, MessageBuilder } = require('discord-webhook-node');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
( async () => {
const browser = await puppeteer.launch({
headless: false,
executablePath: `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,
userDataDir: `/Users/bran_d0_n/Library/Application Support/Google/Chrome/Default`,
ignoreHTTPSErrors: true,
ignoreDefaultArgs: ['--enable-automation'],
args: [
`--disable-blink-features=AutomationControlled`,
`--enable-blink-feautres=IdleDetection`,
`--window-size=1920,1080`,
`--disable-features=IsolateOrigins,site-per-process`,
`--blink-settings=imagesEnabled=true`
]
});
//------------------ Random Password Generator Function ------------------//
function generatePassword() {
let pass = '';
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz0123456789##$';
for ( let i = 1; i <= 8; i++) {
var char = Math.floor(Math.random() * str.length + 1);
pass += str.charAt(char)
}
return pass;
}
//------------------ First & Last Name Generator Function ------------------//
async function fetchData(url) {
const response = await fetch(url);
return response.json();
}
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network Response Invalid');
}
return response.json();
} catch (error) {
console.error('Unable To Fetch Data:', error)
}
}
function fetchNames(nameType) {
return fetchData(`https://www.randomlists.com/data/names-${nameType}.json`);
}
function pickRandom(list) {
return list[Math.floor(Math.random() * list.length)];
}
async function generateName(gender) {
try {
const response = await Promise.all ([
fetchNames(gender || pickRandom(['male', 'female'])),
fetchNames('surnames')
]);
const [ firstNames, lastNames] = response;
const firstName = pickRandom(firstNames.data);
const lastName = pickRandom(lastNames.data);
return `${firstName} ${lastName}`;
} catch (error) {
console.error('Unable To Generate Name:', error);
}
}
console.log('Loading Browser...');
// Account Values
var bDayval = '01/05/22' + (Math.floor((Math.random() * ( 99-55 )) + 55 )).toString();
var passwordVal = generatePassword();
var fnameVal = generateName();
var lnameVal = generateName();
var info;
var themessage;
var phoneNum;
var userpass;
Loading and configuring the module
node-fetch from v3 is an ESM-only module - you are not able to import it with require().
If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.
You should either use
import fetch from 'node-fetch';
(Remember to add "type": "module" to the package.json)
Or install the older version
npm install node-fetch#2
I am attempting an axios POST, using Node js.
making a call to the api is in two steps, first doing a post to get an access token, then a get with that access token.
I have accomplished the call in c#
var baseUri = new Uri("www.example.com");
var requestToken = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(baseUri, "oauth/token"),
Content = new StringContent("grant_type=client_credentials&client_id=someIDnumHere&client_secret=somePassword")
};
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.SendAsync(requestToken).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(json);
var accessy = jsonData.access_token;
accessTokens.Add(accessy.ToString());
}
}
and even Firefox REST Client
but I have failed (bad request) in node JS
this is what I tried.
let urly = 'https://example.com';
const newPost = {
body: 'grant_type=client_credentials&client_id=someIDHereclient_secret=somePasswordHere'
};
const sendPostRequest = async () => {
try {
const resp = await axios.post(urly, newPost);
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendPostRequest();
any help is appreciated.
Thanks to # zemaj
let urly = "https://example.com";
const sendPostRequest = async () => {
try {
const resp = await axios.post(
urly,
"grant_type=client_credentials&client_id=someIDHereclient_secret=somePasswordHere"
);
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendPostRequest();
I have a problem calling a read only function from my frontend. When I try to call it metamask ask me to pay gas fee
and the output of this transaction doesn't have any sense.
The solidity smart contract: https://rinkeby.etherscan.io/address/0xcf781c136ce1534d00db67c4ec488a6c4e01bbef
This is the solidity function : viewregistro
function compile_registro (string memory new_reg) public returns (bool registration){
registro[ultima] = new_reg;
ultima = ultima +1;
registration = true;
return registration;
}
function viewregistro(uint where) public view returns (string memory here){
here = registro[where];
return here;
}
This is the javascript code:
const enable = async () =>{
await window.ethereum.enable();
provider = new ethers.providers.Web3Provider(window.ethereum);
signer = await provider.getSigner();
address = await signer.getAddress();
console.log(provider);
return provider, signer, address
}
const contractConnection2 = async () => {
rank = new ethers.Contract( address_, rankingabi_ ,signer);
console.log(rank);
return rank;
}
const addmember = async() => {
rank.compile_registro("pluto");
}
I everyone, I'm trying to call a function called 'safeMint' on an ERC721 contract deployed on Rinkeby testnet but I'm getting this error:
Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.5.0)
This is the code I'm using to call the function
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
setAccount(accounts[0]);
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner();
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(account, props.cidOfJsonInIpfs);
console.log(trx);
} catch(err) {
console.log(err);
}
}
}
I've tried to print the parameters passed but they seem to be right, what am I doing wrong?
I solved it with the following code
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner(accounts[0]);
console.log(signer._address)
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(accounts[0], `https://gateway.pinata.cloud/ipfs/${props.cidOfFile}`);
let receipt = await trx.wait();
console.log(receipt);
} catch(err) {
console.log(err);
}
}
What I was missing: I was using setState function to set the 'account' state variable with the first account of metamask, instead, I started using account[0] directly and it worked!
I will accept this as solution in 2 days
I'm stuck in async hell:
function convertToDomainUsers(dbUsers: Array<UserDB>): Array<UserDomain> {
// iterate each DB user and convert them to domain user types
const domainUsers: Array<UserDomain> = dbUsers.map( async (dbUser: UserDB) => {
// first convert the DB user to a Domain User
const domainUser: UserDomain = newUserDomainModel(dbUser);
// Now we need to get their user links from the DB
const dbUserLinks: Array<UserLinkDB> = await findDBUserLinks(dbUser.user_id);
// convert their user links to Domain user links
const domainUserLinks: Array<UserLinkDomain> = convertToUserLinks(dbUserLinks);
// now merry up the domain user links to the domain user
domainUser.links = domainUserLinks;
return domainUser;
});
return domainUsers;
}
function newUserDomainModel(user: UserDB): UserDomain {
const domainUser: UserDomain = {
username: user.user_username,
firstName: user.user_name_first,
lastName: user.user_name_last
};
return domainUser;
}
async function findDBUserLinks(userId: bigint): Promise<Array<UserLinkDB>> {
const dbUserLinks: Array<UserLinkDB> = await getUserLinks(userId);
return dbUserLinks;
}
async function getUserLinks(id: bigint): Promise<Array<UserLinkDB>> {
setDB();
await client.connect();
const query = `
select
link_url,
social_type_id
from user_links
WHERE user_id = ${id}`;
const res = await client.query(query);
const links: Array<UserLinkDB> = res.rows;
return Promise.resolve(links);
}
Error (happening on const domainUsers: in the convertToDomainUsers function):
TS2322: Type 'Promise<UserDomain>[]' is not assignable to type 'UserDomain[]'. Type 'Promise<UserDomain>' is missing the following properties from type 'UserDomain': username, firstName, lastName, fullName, and 6 more
comments were added for the sake of making this stack post easier to follow. I don't normally write comments, they're cruft.
Calling:
const domainUsers = await Promise.all(convertToDomainUsers(dbUsers));
Working implementation:
function convertToDomainUsers(dbUsers: Array<UserDB>): Array<Promise<UserDomain>> {
const domainUsers: Array<Promise<UserDomain>> = dbUsers.map( async (dbUser: UserDB) => {
const domainUser: UserDomain = newUserDomainModel(dbUser);
const dbUserLinks: Array<UserLinkDB> = await findDBUserLinks(dbUser.user_id);
const domainUserLinks: Array<UserLinkDomain> = convertToUserLinks(dbUserLinks);
domainUser.links = domainUserLinks;
return domainUser;
});
return domainUsers;
}