So I have this code:
import { ThirdwebSDK } from "#thirdweb-dev/sdk";
import { ConnectWallet, useAddress } from "#thirdweb-dev/react";
export default function DonationPage() {
let address = useAddress()
async function sendCoins() {
try {
let random = ethers.Wallet.createRandom();
// get a signer from somewhere (createRandom is being used purely for example purposes)
// get an instance of the SDK with the signer already setup
const sdk = ThirdwebSDK.fromSigner(signer || random, "mainnet");
try {
if (selectedCoin == 'eth') {
await sdk.wallet.transfer(CORPORATE_WALLET || "0x", donationAmount);
} else {
// const decimals = await contract.erc20..call()
// const amount = new BigNumber(donationAmount * (10 ** decimals))
const contract = await sdk.getContract(crypto.find((coin) => coin.id == selectedCoin)?.contract_address || '0x');
let balance = await contract.erc20.balance()
let allowance = await contract.erc20.allowance(address || '0x')
// console.log('balance', balance.value)
// console.log('allowance', allowance.value)
if(donationAmount + Number(balance.displayValue) > Number(allowance.displayValue)) {
await contract.erc20.setAllowance(address || '0x', donationAmount + Number(balance.displayValue))
}
await contract.erc20.transferFrom(address || '0x',CORPORATE_WALLET || '0x', donationAmount);
}
} catch (error: any) {
alert(error.message)
}
}
return (<>...</>)
}
So i'm using ConnectWallet button to get address and using TrustWallet for this, and trying to transfer tokens from 'address' to a corporate wallet, with a specified donation amount.
However, I receive this error "Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined".
There seems to be no documentation on this online, and ChatGPT won't help either. Does someone know how to fix this?
You can pull up the transaction by its hash on EtherScan and check what the estimation time is for the transaction to be included in a block by a block producer
Because there are no details on the transaction on the question itself, it is not possible to give more specific answer
For transaction troubleshooting, please refer to ethereum.stackexchange.com as diagnosing transaction failures is not really related to programming
Related
I need to implement in the code below "value" the cost in ETH because in Solidity I require msg.value and in order to be able to lie I have to put a parameter "value" in the code in js, but I don't know how, you can it helps? I also attached the Smart Contract part with mint.
React JS file
async function handleMint() {
if (mintFinish === true) {
setMintFinish(false);
} else {
setMintFinish(true);
}
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(
mintExampleAddress,
mintExampleABI.abi,
signer
);
console.log(signer)
try {
// console.log(contract)
const response = await contract.mint(mint);
console.log(response);
} catch (err) {
console.log(err);
}
}
}
Solidity file
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
how you are using etherjs and seeing the smart contract code inside the mint function, i suppose that cost is a public variable and can be read from outside the contract, you get the cost and multiply the value by the mint amount parameter, something like this
const cost = await contract.cost();
const response = await contract.mint(mint,{value:cost.mul(mint)});
you have to remember to use bignumbers and that all return values that are numbers will be returned as one, what i'm doing here is getting the cost from the contract and multiply that for mint and pass that to value as the last parameter in the function call
I am developing a flutter application in which I am implementing hive database for caching data.
I have added both hive and hive_flutter packages.
I am getting data from APIs and store that to hive to update data, It works fine when I used app connected to internet but didn't works when I try to read while being offline. Here is the code of my API method I am calling to get data:
static Future<List<UserPost>> getPosts() async {
//I call my API in try block, if its successful, I update the data in hive
List<UserPost> posts = [];
Hive.openBox(Constants.APIDATA_BOX);
try {
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'),);
if (response.statusCode == 200) {
//Clear hive box from old data
Hive.box(Constants.APIDATA_BOX).clear();
Hive.box(Constants.APIDATA_BOX).put(Constants.API_DATA,jsonDecode(response.body));
}
} catch (e) {
print('You are not connected to internet');
}
//I am getting data here from hive database and it works fine while connected to internet
var listMaps =await Hive.box(Constants.APIDATA_BOX).get(Constants.API_DATA, defaultValue: []);
posts = listMaps.map<UserPost>((map) {
//Here flow stucked whenever working offline,
//Data is also available but here conversion cause error, I have tried many way but fails.
return UserPost.fromMap(map);
}).toList();
return posts;
}
I don't why I am getting error, I have tried many conversion ways here but all works while being online. Any help will be highly apprerciated.
I think I've understood the error but you should explain better which type of error you're having.
Anyway pay attention to the operations on Hive, which are often async, for example Hive.openBox(Constants.APIDATA_BOX);.
So when you have internet connection, you have to await for the response and Hive has time to open the box, otherwise it will throw an error so, considering the futures, you should do this:
static Future<List<UserPost>> getPosts() async {
List<UserPost> posts = [];
await Hive.openBox(Constants.APIDATA_BOX);
try {
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'),);
if (response.statusCode == 200) {
//Clear hive box from old data
await Hive.box(Constants.APIDATA_BOX).clear();
await Hive.box(Constants.APIDATA_BOX).put(Constants.API_DATA,jsonDecode(response.body));
}
} catch (e) {
print('You are not connected to internet');
}
var listMaps = await Hive.box(Constants.APIDATA_BOX).get(Constants.API_DATA, defaultValue: []);
posts = listMaps.map<UserPost>((map) {
return UserPost.fromMap(map);
}).toList();
return posts;
}
Note that await Hive.put() in a normal box is not strictly necessary, as explained in the docs
I am trying to access an api and I will have to run the api calls several times based on the page numbers I need to iterate, the following is the code which I am using and how can I get the all the response pushed into an array.
as nodeJs is single threaded It is not waiting for the responses from the api.
How can I can tackle this and ensure all the response values are being pushed into an array
Inside the for loop I want the final array which has all the values of the api response. So, I check the total page value and response page Number if that matches which means that will be the last page and I push the array to another function but when I do that it does not have all the values because nodejs does not wait for the api response.
const fs = require('fs');
var pepKey = 'asdfasdfasd';
var pepResponse;
var pepTimecards = [];
pep();
function pep(){
var options = {
headers: {
"content-type": "application/json",
},
agentOptions: {
pfx: fs.readFileSync('./certificate/asdfsdaf.p12'),
passphrase: 'asdasdsda'
}
};
request.get('https://source.asdfasdf.io/api/organisations/asdfasdf/timecard_keys?timecard_type=Flex',options, (err, res, body) => {
if (err) { return console.log(err); }
pepResponse = JSON.parse(body)
pepTimecards = pepResponse.data;
if(pepResponse.pages > 1){
for(let i=2;i<=pepResponse.pages;i++){
var url = 'https://source.`pepme`.io/api/organisations/sdfsadf/timecard_keys?timecard_type=Flex&page='+pageNo;
request.get(url,options, (err, res, body) => {
if (err) { return console.log(err); }
body = JSON.parse(body)
pepTimecards = pepTimecards.concat(body.data)
if(pepResponse.pages == body.page){
console.log(pepResponse.pages)
console.log(body.page +"body page")
console.log(pepTimecards)
}
});
}
}else{
}
});
}
Use the request-promise library which supplies promisified versions of the request library. Then, you can use async/await in your for loop to serialize your operations:
Newer answer to go with the edited code in the OP's question
const fs = require('fs');
const rp = require('request-promise');
const pepKey = 'asdfasdfasd';
pep().then(pepTimecards => {
// the timecard data is valid in here
console.log(pepTimecards);
}).catch(err => {
console.log(err);
});
async function pep() {
let timecards = [];
const options = {
headers: {
"content-type": "application/json",
},
agentOptions: {
pfx: fs.readFileSync('./certificate/asdfsdaf.p12'),
passphrase: 'asdasdsda'
},
json: true,
uri: 'https://source.asdfasdf.io/api/organisations/asdfasdf/timecard_keys?timecard_type=Flex'
};
let pepResponse = await rp(options);
timecards = pepResponse.data;
if (pepResponse.pages > 1) {
for (let i = 2; i <= pepResponse.pages; i++) {
options.uri = 'https://source.`pepme`.io/api/organisations/sdfsadf/timecard_keys?timecard_type=Flex&page='+pageNo;
let body = await rp(url, options);
// add body.data onto the existing array
timecards.push(...body.data);
}
} else {
}
console.log(pepResponse.pages)
console.log(timecards)
return timecards;
}
Prior Answer before OP edited the code in their question:
const rp = require('request-promise');
// I'm assuming this is some sort of method definition on a class, otherwise it needs the function keyword
async pageno(pageNo) {
for (let i=2;i<=pepResponse.pages;i++){
try {
options.uri = 'https://test/timecard_keys?timecard_type=asdas&page='+pageNo;
// let request-promise parse the json for you automatically
options.json = true;
let body = await rp(options);
pepTimecards = pepTimecards.concat(body.data)
if (pepResponse.pages == body.page){
console.log(pepResponse.pages)
console.log(body.page +"body page")
console.log(pepTimecards)
}
} catch(e) {
// decide what to do for error handling
// this will log and rethrow so the caller will get a rejected promise
console.log(e);
throw e;
}
}
// return some value here to be the resolved value of the returned promise
return pepTimecards;
}
In your code, it is not clear where the options, pepTimecards, pepResponse variables are declared. They should probably be declared as local variables here or passed in to the function and/or returned from your function.
Summary of modifications:
Add async to method declaration so we can use await.
Load request-promise library into rp variable
Add options.json = true to the let the request-promise library parse the JSON result for us automatically
Change rp() to just use the options structure (add URL to that)
Add try/catch to catch any errors from the await, log them, then rethrow so pageno() will return a promise that rejects if there is an error (you can customize the behavior when there's an error if desired)
Add a return value so there is meaningful resolved value to the promise (you should not be using side-effect programming as it is now (modifying variables that are not passed in, declared locally or returned).
Things for you still to fix:
Stop using side-effect programming where you modify free variables that aren't passed in, aren't declared locally and aren't returned. This is a bad way to design code. You don't show enough overall context from the calling code or where these other variables are defined to make a concrete recommendation on how it should be done.
Decide what your error handling strategy is if there's an error on one of the requests and implement that strategy and proper handling.
The title is my problem. Here is the code I'm using:
const voiceChannel = message.guild.channels.find(channel => channel.name === args[0]);
if (!voiceChannel || voiceChannel.type !== 'voice') {
return message.reply(`I couldn't find the voice channel ${args[0]}.`);
}
await voiceChannel.join();
let connection = message.guild.voiceConnection;
connection.on('speaking', (user, speaking) => {
if(speaking) {
const receiver = connection.createReceiver();
const stream = receiver.createPCMStream(user);
receiver.on('opus', (user, buffer) => {
console.log('got some data');
});
stream.on('data', chunk => {
console.log(chunk.length);
});
}
});
Nothing prints in the console, so I guess the stream and voice receiver just aren't receiving any data. Also, I've looked at lots of posts and lots of people use this code and it works for them. If anybody knows why this is happening please help!!
Thanks in advance.
It's a bit late to answer but might help someone else.
You must send a silent frame first.
const { Readable } = require('stream');
class Silence extends Readable {
_read() {
this.push(Buffer.from([0xF8, 0xFF, 0xFE]));
}
}
Once the connection is established with the voice channel you can do something like this:
connection.on('ready', ()=>{
connection.play(new Silence(), { type: 'opus' });
})
For more details, you can visit this page
Anyone knows what could be the issue that .kick() .setMute(true/false) or even setDeaf(true/false) in discord.js libary don't seem to work. Here is also a part of the code that doesn't do anything when it should but also doesn't throw any errors. Bot was invited with maximum privileges and also code block executes the command to steMute / setDeaf / kick. Any ideas of what might cause this or what should i try logging to find the issue? THANKS!
ar msgUserId = msg.author.id
var allUsers = []
var reset = true
bot.channels.forEach((channel, id) => {
if (reset){
channel.members.forEach((user, id) => {
allUsers.push(user)
if (id == msgUserId){
reset = false
}
})
if (reset){
allUsers = []
}
}
})
if (allUsers){
var number = Math.floor((Math.random() * allUsers.length))
allUsers[number].setDeaf(true)
allUsers[number].setMute(true)
} else {
var channel = msg.channel
channel.send("You must be in a voice channel with others for this to work!")
}
Channels in bot.channels are cached for the sole purpose of metadata which are instances of Channel, you need a guild context (aka. server ID) in order to acquire a TextChannel with which the operations you say can be done.