Call smart contract function by web3.js without response - javascript

I was watching the tutorial on Youtube and following the instruction:
https://www.youtube.com/watch?time_continue=1350&v=msT3tpwnyv8
When I try to call the function with the js file below, it returned nothing on the console. Does anyone know what happened?
I am using,
web3.js 1.0.0 beta. 52
infura to connect
var Tx = require('ethereumjs-tx')
const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/project_id')
const contractAddress = '0xd03696B53924972b9903eB17Ac5033928Be7D3Bc'
const contractABI = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"standard","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]
var contract = new web3.eth.Contract(contractABI, contractAddress)
contract.methods.totalSupply().call((err, result)=> {
console.log(result)
})

Try:
contract.methods.totalSupply().call().then((result) => {console.log(result) });
It should return a BigNumber.

Related

Calling a smart contract function using metamask with ether.js

I'm completely new to both blockchain and JavaScript.
I'm trying to create a simple web page where people could generate a "wedding" smart contract that basically store their 2 names. For this I have created a WeddingCerficate contract which store the names and have a getter function, and a WeddingCertificateFactory That enable me to generate a WeddingCertificate. You can find the code of the smart contracts in solidity below.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract WeddingCertificate{
string private spouse1;
string private spouse2;
constructor(string memory _spouse1, string memory _spouse2) {
spouse1 = _spouse1;
spouse2 = _spouse2;
}
function getSpouses() public view returns (string memory,string memory) {
return (spouse1,spouse2);
}
}
contract WeddingCertificateFactory{
event Wedding(string _spouse1, string _spouse2, address indexed contract_adress );
function Unite(string memory _spouse1, string memory _spouse2)public returns (bool success) {
WeddingCertificate wedding = new WeddingCertificate(_spouse1, _spouse2);
emit Wedding(_spouse1,_spouse2 , address(wedding));
return true ;
}
}
I deployed the WeddingCertificateFactory on Goerli Tesnet. And now I'm trying to make a function in javascript (using ether.js) to enable a user to create his own weddingCertificate directly on a web interface.
For this I wrote the function below but for some reasons this only generates the new Wedding certificate once out 20. And even when it actually work, the two last print aren't visible in the console.
I do not get any error (at least that I can see in the console) when I test the function and nothing happen.
I'm not familiar with async in JavaScript, I also tried the .then( syntax but I didn't notice any difference.
async function CreateWedding(){
const spouse1 = document.getElementById("spouse1").value;
const spouse2 = document.getElementById("spouse2").value;
if (spouse1.length > 0 && spouse2.length >0) {
console.log(`spouse 1: ${spouse1} , spouse2 : ${spouse2} `);
const ethereum = window.ethereum ;
const accounts = await ethereum.request({
method: "eth_requestAccounts",
});
const provider = new ethers.providers.Web3Provider(ethereum, "any");
const walletAddress = accounts[0];
const signer = provider.getSigner(walletAddress);
let abi = [
" function Unite(string memory _spouse1, string memory _spouse2)"
];
const contractAddress = "0x2556Ff7f7F1c013bBB60bD120E1828032Cd84cc4"; //WeddingFactory Contract
const contract = new ethers.Contract(contractAddress, abi, signer);
console.log("sending the contract");
tx = await contract.Unite(spouse1,spouse2);
console.log(tx);
console.log("finished");
} else {
alert("Please enter 2 names");
}
}
Try creating your abi method in web3client.app.
It has code generater for ether.js which yoy can use directly in your app.
If there is an actual issue in your contract it would fail there itself.

Invalid Amount Error from Metamask mobile app during USDT transaction using web3js

I am facing Invalid Amount Error from meta mask (mobile app) during USDT transaction using web3js the error looks like below
My code looks like this
var provider = new WalletConnectProvider.default({
infuraId : "fe1de0f178274481ae79b8b8k44ca8La"
});
var address = "0xC888423179C22fD57dEB32e38d9e6C31462687C2"
var connectWC = async () => {
await provider.enable();
// Create Web3 instance
const web3 = new Web3(provider);
window.w3 = web3
var accounts = await web3.eth.getAccounts(); // get all connected accounts
account = accounts[0]; // get the primary account
contractTokenTransfer();
}
let contractTokenTransfer = async()=>{
let abi =[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}]
let contractInstance = new w3.eth.Contract(abi,"0x110a13FC3efE6A245B50102D2d79B3E76125Ae83");
let amount = 0.001 * 10 ** 6;
const gasPrice = await w3.eth.getGasPrice();
contractInstance.methods.transfer(address, amount).send({from: account, gas: gasPrice},function (error, result){ //get callback from function which is your transaction key
if(!error){
console.log(result);
handleSuccessTrue();
} else{
console.log(error);
}
});
}
Kindly assist me with why this error happen

Uniswap JS SDK and Ethers js trying to swap eth for tokens

I am trying to swap tokens using a js script that can be used to swap ethereum for any token. The problem is that some of the tokens I try and swap for will provide the error "UnhandledPromiseRejectionWarning: InsufficientInputAmountError". However, if I try and swap for a different token it works as it should. I know the token that raises the error is compatible with uniswap since I have bought some through their website and received no error.
const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent, Token} = require('#uniswap/sdk');
const {ethers} = require("ethers");
let Web3 = require('web3');
let web3 = new Web3(new Web3.providers.HttpProvider("INFURA_KEY"));
function toHex(Amount) {
return `0x${Amount.raw.toString(16)}`;
}
const chainId = ChainId.MAINNET;
const tokenAddress = '0x094F00Cb5e31Ab6164E3CAcb654e8D6c2b3b471C';
const provider = new ethers.providers.EtherscanProvider('homestead', 'ETHERSCAN_KEYY');
const init = async () => {
const gas = await web3.eth.getGasPrice();
const token = await Fetcher.fetchTokenData(chainId, tokenAddress, provider);
const weth = WETH[token.chainId];
const pair = await Fetcher.fetchPairData(token, weth, provider);
const amountIn = '10000000000000000';
const route = new Route([pair], weth);
const trade = new Trade(route, new TokenAmount(weth, amountIn), TradeType.EXACT_INPUT);
const slippageTolerance = new Percent('1', '100');
const amountOutMin = toHex(trade.minimumAmountOut(slippageTolerance));
const path = [weth.address, token.address];
const to = 'MY_KEY';
const deadline = Math.floor(Date.now()/1000) + 60*20;
const value = toHex(trade.inputAmount);
const signer = new ethers.Wallet('MY_PRIVATE_KEY');
const account = signer.connect(provider);
const uniswap = new ethers.Contract(
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
['function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)'],
account
);
const tx = await uniswap.swapExactETHForTokens(
amountOutMin,
path,
to,
deadline,
{value, gasPrice: gas}
);
console.log(tx);
}
init();
Functioning Token Address: 0x6b175474e89094c44da98b954eedeac495271d0f
Non-Functioning Address: 0x094F00Cb5e31Ab6164E3CAcb654e8D6c2b3b471C
The issue seems to be when defining const trade since the script doesn't run beyond that. I have looked through and don't know of any reason that most tokens seem to work but a few don't (even if they work on the uniswap website). I am pretty new to JS and working with ethers/uniswap so any insight would be greatly appreciated.
You have to make a pool for that token on uniswap. I was also facing the same issue for Eth to usdc swap on the Goerli network. First, add the token into the pool and then make a pool with ether.

Web3 not treating web3.eth.Contract as a contructor

I'm writing a JS file to provide functionality to a smart contract. From what I can tell, MetaMask is injecting web3 into the webpage, but when I attempt to create a contract object, my browsers console (brave browser) is stating that web3.eth.Contract is not a constructor.
I've looked in the object provided by my browsers console, and I don't see the Contract constructor. Is this normal? Or do you think web3 may be incorrectly installed? I've hit a wal at this point.
var blockContractJSON = $.getJSON("../build/contracts/Blocks.json", function(data) {
return data;
});
console.log(blockContractJSON)
// console.log(blocksContract)
var blocksContract;
var currentUser;
var web3js;
console.log(web3js);
// console.log(blockContractJSON);
// defines contract address and initializes contract functions
var startApp = function() {
var contractAddress = "0x2520127E14E8A14C67Ee2B561714ADae53D48110";
console.log('got the contract'); <- web3 not passing to this line?
blocksContract = new web3js.eth.Contract(blockContractJSON, contractAddress);
// console.log(blocksContract);
var checkAccounts = setInterval(function() {
if (web3js.eth.accounts[0] !== currentUser) {
currentUser = web3js.eth.accounts[0];
}
}, 100)();
};
// adds in web3
window.addEventListener('load', function() {
console.log('item loaded from page is')
console.log()
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
console.log('using metamask');
console.log(web3)
// Use Mist/MetaMask's provider
web3js = new Web3(web3.currentProvider);
console.log(web3js)
} else {
alert('install metamask')
}
startApp();
});
Works for me
const Web3 = require('web3')
var web3 = new Web3(new Web3.providers.HttpProvider("infuralink"));
const ABI=[];
const Contract = new web3.eth.Contract(ABI,"contractaddress");
Try using Ethereum lib instead (web3-eth)
[https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html][1]
var eth = new Eth('http://localhost:8545');
check first parameter is the abi node of the JSON not the abi metadata
new eth.Contract(contractAbi.abi, CONTRACT_ADDRESS);

JS SDK, Thrift error code 12 when getting SharedNotebooksList

It's the first time that I work with evernote,
Like the example given in the JS SDK, I create my client with the token that I get from the OAuth and I get all the notebooks of my current user so it was good for me.
But I'm facing a problem that I can't understand, when I use any method of my shared store it throw an Thrift exception with error code 12 and giving the shard id in the message.
I know that 12 error code is that the shard is temporary unavailable..
But I know that it's another thing because it's not temporary...
I have a full access api key, it work with the note store, did I miss something ?
// This is the example in the JS SDK
var linkedNotebook = noteStore.listLinkedNotebooks()
.then(function(linkedNotebooks) {
// just pick the first LinkedNotebook for this example
return client.getSharedNoteStore(linkedNotebooks[0]);
}).then(function(sharedNoteStore) {
// /!\ There is the problem, throw Thrift exception !
return sharedNoteStore.listNotebooks().then(function(notebooks) {
return sharedNoteStore.listTagsByNotebook(notebooks[0].guid);
}).then(function(tags) {
// tags here is a list of Tag objects
});
});
this seems to be an error with the SDK. I created a PR (https://github.com/evernote/evernote-sdk-js/pull/90).
You can work around this by using authenticateToSharedNotebook yourself.
const client = new Evernote.Client({ token, sandbox });
const noteStore = client.getNoteStore();
const notebooks = await noteStore
.listLinkedNotebooks()
.catch(err => console.error(err));
const notebook = notebooks.find(x => x.guid === guid);
const { authenticationToken } = await client
.getNoteStore(notebook.noteStoreUrl)
.authenticateToSharedNotebook(notebook.sharedNotebookGlobalId);
const client2 = new Evernote.Client({
token: authenticationToken,
sandbox
});
const noteStore2 = client2.getNoteStore();
const [notebook2] = await noteStore2.listNotebooks();
noteStore2.listTagsByNotebook(notebook2.guid)

Categories

Resources