Can't invoke method with phantom provider - javascript

I'm trying to create a transaction then use phantom provider to let the user sign and send the transaction.
this is how my transaction is constructed:
if (method === 'sol'){
const amount = sol_dict[req.body.rank];
const lamports = amount * (1000000000);
const transaction_inst = SystemProgram.transfer({
fromPubkey: from_pk,
toPubkey: to_pk,
lamports: lamports,
});
const transaction = new Transaction().add(transaction_inst);
const hash = await connection.getLatestBlockhashAndContext()
transaction.recentBlockhash = hash.value.blockhash;
transaction.lastValidBlockHeight = hash.value.lastValidBlockHeight;
transaction.feePayer = from_pk;
const fee = await transaction.getEstimatedFee(connection);
//console.log(transaction.serialize());
res.json(transaction);
}
I'm getting this error:
when I try to use window.solana.signAndSendTransaction(data); from the response.json() .
adding and removing parameters
serializing data

Related

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

How to send solana via my app in vanilla js?

Trying to do a simple send and receive function in Solana with vanilla JS.
Below is my send function that works fine, and now I want a receive function.
Where the provider would get Solana transferred from my treasury wallet.
I'm not sure what approach I should have, just starting out. Is there a way to just move things around in this function? Or do I have to have a totally different approach?
Thanks!
async function transferSOL() {
// Detecing and storing the phantom wallet of the user (creator in this case)
var provider = phantom;
// Establishing connection
var connection = new web3.Connection(
web3.clusterApiUrl('devnet'),
);
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: treasuryWallet.publicKey,
lamports: 0.1 * web3.LAMPORTS_PER_SOL - 100
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
let signature = await connection.sendRawTransaction(signed.serialize());
await connection.confirmTransaction(signature);
}
If you want to transfer from your treasury to the user, then you must sign for treasuryWallet somehow. In your case, it looks like you already have the keypair available to you in your app, so you can simply do:
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
toPubkey: provider.publicKey,
fromPubkey: treasuryWallet.publicKey,
lamports: 0.1 * web3.LAMPORTS_PER_SOL - 100
}),
);
// Setting the variables for the transaction
transaction.feePayer = treasuryWallet.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Request creator to sign the transaction (allow the transaction)
transaction.sign(treasuryWallet);
let signature = await connection.sendRawTransaction(transaction.serialize());
await connection.confirmTransaction(signature);
Note that this is very unsafe! Everyone who uses your web app has full access to the treasury funds if the keypair is exposed, since they can just sign all the transactions that they want with it.

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.

FETCH API - Cannot access property from JSON response in api Request - Array is Empty

I've been trying to run a script that basically:
Loops thru a list of SellerIDs and identify how many records (which are product offers) each one has. Then, it creates an object with the Seller ID, Total Number of Pages and Total Number of Records.
Loop thru each ID in this newly created object and fetches all offers from each sellers. It fetches in batches of 50, because the API limit = 50.
Later on, I want to save these records to a database. But, to do that, Im going to save specific properties from each offer.
As I fetched them in batches, I need to access the single offers that are laying in the results property, inside each object. response.results.
For some reason, the results field always return as an empty array and Im unable to reach any of its properties.
If anyone has any idea what could be causing this issue, it's be a great help!
I've been trying to figure out and reading a lot, but still couldn`t find out.
Im a noob newly starting coding enthusiast, so sometimes I make dumb mistakes :X
Here's the code:
// node --max-old-space-size=8192 '.\2. CheckNeededPagination.js'
const express = require('express');
const mysql = require('mysql');
let listOfSellerIds = require('./1. list_of_seller_ids');
const request = require('request-promise');
const fetch = require('node-fetch');
const Request = require('request');
// IDs do app no Mercado Livre
var meli = require('mercadolibre-nodejs-sdk');
const mlToken = "hidden for security purposese";
const mlAppID = 'hidden for security purposese';
const mlSecretKey = 'hidden for security purposese';
const mlRedirectURI = 'https://localhost:3001/index'
const authURL = `http://auth.mercadolivre.com.br/authorization?response_type=code&client_id=${mlAppID}&redirect_uri=${mlRedirectURI}`
const endpoint = 'https://api.mercadolibre.com/sites/MLB/search?seller_id='
const reqHeaders = {method: "GET", headers: {'Authorization': mlToken}};
// -----------------------------------------------------------------------------------------------------
const myCode = (()=>{
const myPaginationNeeds = [];
// MODULE 1: Get Pagination Need from All sellers and return them as an object
async function makeRequest(){
for (s=0; listOfSellerIds[s]; s++){
const res = await fetch(`https://api.mercadolibre.com/sites/MLB/search?seller_id=${listOfSellerIds[s]}&offset=0&limit=1`, {method: "GET", headers: {'Authorization': mlToken}});
const data = await res.json();
myPaginationNeeds.push({'SellerID': listOfSellerIds[s],'RecordsNum': await data.paging.total, 'NumOfPages': await Math.ceil(data.paging.total/50)});
// myPaginationNeeds.push(await data);
}
console.log(myPaginationNeeds); // Uncomment to test object with seller pagination needs
}; // End of MODULE 1
//MODULE 2 -> Get All Offers From Sellers
async function getOffers (){
allOffers = [];
for (s=0; listOfSellerIds.length > s; s++){ //Loop thru sellers
curSellerID = listOfSellerIds[s];
console.log(`We're on seller ${listOfSellerIds[s]}! There are ${listOfSellerIds.length - s} sellers left to go...` )
for (i =0; 2 > i; i++){ //myPaginationNeeds[s].NumOfPages
console.log(`We're on page number ${i} of ${myPaginationNeeds[s].NumOfPages}! There are ${myPaginationNeeds[s].NumOfPages - i} pages left to go...` )
const response = await fetch(`https://api.mercadolibre.com/sites/MLB/search?seller_id=${listOfSellerIds[s]}&offset=${myPaginationNeeds[s].NumOfPages*50}&limit=50`, {method: "GET", headers: {'Authorization': mlToken}})
const resData = await response.json();
allOffers.push({'SellerInfo': await resData.seller,'SellerPaging': await resData.paging,'SellerResults': await resData.results});
const myResults = await resData.results[0];
console.log(await myResults);
}; // End of loop thru offset
} // End of loop thru sellers
// console.log(await allOffers);
//console.log(allOffers);
} // end of GetOffers
async function fetchIt () {
await makeRequest();
await getOffers();
console.log(allOffers.length);
//console.log(allOffers[0].SellerResults[0]);
};
fetchIt();
}); // End of myCode
myCode();

Caching custom emojis from another shard

im trying to get a larger discord bot of mine to save all custom emojis it grabs from another shard to a cache so I can serve better response times for each shard. To give a theoretical example, my bot spawns 4 shards and only one shard serves the guild that contains all the custom emojis that I want to use across all shards. I am using this function to grab the emojis, but I need to await each one, and it can make my response times up to 15 seconds as there are many emojis I need to grab:
function findEmoji(id) {
const temp = this.emojis.get(id);
if (!temp) return null;
const emoji = Object.assign({}, temp);
if (emoji.guild) emoji.guild = emoji.guild.id;
emoji.require_colons = emoji.requiresColons;
return emoji;
}
async function grabEmoji(emojiID) {
const emojiArray = await client.shard.broadcastEval(`(${findEmoji}).call(this, '${emojiID}')`);
const foundEmoji = emojiArray.find(emoji => emoji);
if (!foundEmoji) return;
const raw = await client.rest.makeRequest('get', Discord.Constants.Endpoints.Guild(foundEmoji.guild).toString(), true);
const guild = new Discord.Guild(client, raw);
const emoji = new Discord.Emoji(guild, foundEmoji);
return await emoji;
}
// then when I send the message, I call the function with the said ID of the emoji I want:
await grabEmoji("530800350656200705");
On the other hand, when I remove await, it will give me listener errors (maxListeners reached) or whatever, and then display "null".
Here is what I have tried, but I havent been able to get it to work.
const emojiMap = new Map();
createMap();
async function createMap() {
let woodenPick = await grabEmoji("601256699629797379"),
stonePick = await grabEmoji("601256431076769803"),
ironPick= await grabEmoji("601257055285673987"),
goldPick = await grabEmoji("601256566670491658"),
diamondPick= await grabEmoji("601256973798998016"),
emeraldPick = await grabEmoji("601256896577404938"),
rubyPick = await grabEmoji("601256312696733696"),
ultimatePick= await grabEmoji("629817042954092545"),
sandstonePick = await grabEmoji("629817043142705152"),
aquaPick = await grabEmoji("629817733902761985"),
techPick = await grabEmoji("502940161085014046"),
stone = await grabEmoji("502940717883064321"),
coal = await grabEmoji("502940528149659649"),
iron =await grabEmoji("502940160942669824"),
gold = await grabEmoji("493801062856392705"),
diamond= await grabEmoji("493805522466766849"),
obsidian =await grabEmoji("493801062671581184"),
emerald = await grabEmoji("630846535025819649"),
ruby =await grabEmoji("502940161001259018"),
lapis = await grabEmoji("502940160988807188"),
redstone= await grabEmoji("632411168601931822"),
silver = await grabEmoji("632413243503149087"),
neonite = await grabEmoji("632413243708801024"),
pulsatingStar= await grabEmoji("632404511759138816"),
sapphire = await grabEmoji("642799734192341013"),
developerBadge = await grabEmoji("642799734209118221"),
staffBadge = await grabEmoji("642799734209118221"),
donatorBadge = await grabEmoji("642799734247129089"),
contributorBadge = await grabEmoji("642799734247129089");
emojiMap.set(['woodenPick', woodenPick])
emojiMap.set(['stonePick', stonePick])
emojiMap.set(['ironPick', ironPick])
emojiMap.set(['goldPick', goldPick])
emojiMap.set(['diamondPick', diamondPick])
emojiMap.set(['emeraldPick', emeraldPick])
emojiMap.set(['rubyPick', rubyPick])
emojiMap.set(['ultimatePick', ultimatePick])
emojiMap.set(['sandstonePick', sandstonePick])
emojiMap.set(['aquaPick', aquaPick])
emojiMap.set(['techPick', techPick])
emojiMap.set(['stone', stone])
emojiMap.set(['coal', coal])
emojiMap.set(['iron', iron])
emojiMap.set(['gold', gold])
emojiMap.set(['diamond', diamond])
emojiMap.set(['obsidian', obsidian])
emojiMap.set(['emerald', emerald])
emojiMap.set(['ruby', ruby])
emojiMap.set(['lapis', lapis])
emojiMap.set(['redstone', redstone])
emojiMap.set(['silver', silver])
emojiMap.set(['neonite', neonite])
emojiMap.set(['pulsatingStar', pulsatingStar])
emojiMap.set(['sapphire', sapphire])
emojiMap.set(['developerBadge', developerBadge])
emojiMap.set(['staffBadge', staffBadge])
emojiMap.set(['donatorBadge', donatorBadge])
emojiMap.set(['contributorBadge', contributorBadge])
}
client.on('message', ... //rest of the code continues for my command handler.
//grab emojis
let woodenPick = emojiMap.get('woodenPick')
let stonePick = emojiMap.get('stonePick')
let ironPick = emojiMap.get('ironPick')
let goldPick = emojiMap.get('goldPick')
let diamondPick = emojiMap.get('diamondPick')
let emeraldPick = emojiMap.get('emeraldPick')
let rubyPick = emojiMap.get('rubyPick')
let ultimatePick = emojiMap.get('ultimatePick')
let sandstonePick = emojiMap.get('sandstonePick')
let aquaPick = emojiMap.get('aquaPick')
let techPick = emojiMap.get('techPick')
let stone = emojiMap.get('stone')
let coal = emojiMap.get('coal')
let iron = emojiMap.get('iron')
let gold = emojiMap.get('gold')
let diamond = emojiMap.get('diamond')
let obsidian = emojiMap.get('obsidian')
let emerald = emojiMap.get('emerald')
let ruby = emojiMap.get('ruby')
let lapis = emojiMap.get('lapis')
let redstone = emojiMap.get('redstone')
let silver = emojiMap.get('silver')
let neonite = emojiMap.get('neonite')
let pulsatingStar = emojiMap.get('pulsatingStar')
let sapphire = emojiMap.get('sapphire')
let developerBadge= emojiMap.get('developerBadge')
let staffBadge = emojiMap.get('staffBadge')
let donatorBadge = emojiMap.get('donatorBadge')
let contributorBadge = emojiMap.get('contributorBadge')
Doing that returns undefined as seen here:
Does anyone have any ideas? I'm directly saving the emoji object to the map thinking I can just use it later.
Getting discord.js's abstraction of an Emoji object in order to display it in a message is extremely unnecessary, but I can't blame you as discord.js tends to nudge its users towards these kinds of practices.
You already know the emoji names and IDs. There is no other information that you need to get from your other shards that your bot doesn't already have. In Discord messages, custom emoji are represented like this:
Custom Emoji - <:NAME:ID> -> <:mmLol:216154654256398347>
Custom Emoji (Animated) - <a:NAME:ID> -> <a:b1nzy:392938283556143104>
source: discord api docs reference
Hence, you don't need to make any requests, any broadcast evals, or anything of the sort: you only need static data. Like this:
let emojiMap = {
woodenPick: "601256699629797379",
stonePick: "601256431076769803",
//etc
};
I recommend a util function for putting the emoji in a message:
function getEmoji(name) {
return `<:${name}:${emojiMap[name]}>`;
}
Use it like this:
await msg.react(emojiMap.woodenPick); //might need to be :name:id
//etc, probably use an array for that (or Object.keys(emojiMap))
//make embed
let description = `${getEmoji("woodenPick")} --> Wooden Pickaxe\netc...`;

Categories

Resources