Ethereum Donation Function defining by tiers of NFT's (Reactjs, Web3) - reactjs

Hope you all having a great week!
I'm having a few issues with NFT's and already deployed a smart contract. Here's the problems I have at the moment and where I need some clarification because I was not able to find any info about it.
I'm doing the NFT's mint function, where the contact and ABI I'm taking from already deployed smart contract. The whole NFT function's purpose is for donation. There are only 5 NFT's released and depending on NFT's trier (index) the price will differ. Because we have an index from 1 to 5.
The question is, how I can access those tiers from Smart contact and assign different prices on them when the buyer chooses from 5 different NFT's.
Here's my code where I was able to access the Metamask and make the first mint, but It does not directly target the specific tiers (index).
As well, the connection with Metamask is already handled and working.
Any help will be appreciated, or any info where I can understand how I could go around making this Minting depending on tiers function. Thanks in advance!!!
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, ContractAbi, signer);
const mintToken = async () => {
const connection = contract.connect(signer);
const addr = connection.address;
const result = await contract.donate(addr, {
value: ethers.utils.parseEther('0.05'),
});
await result.wait();
};

Related

How can we find the total number of tokens available in a wallet ? (withOut initialising Moralis) -As it is time taking

const Moralis = require('moralis').default
const {EvmChain} = require('#moralisweb3/evm-utils')
const runApp = async () => {
// WithOut Moralis initialising - I want to skip these ------(https://i.stack.imgur.com/u4cGM.jpg)
await Moralis.start({
apiKey: 'api_key_secret'
})
// ------------------
const address = '0xbf820316675F3F96beb7a47Cec34c5aEdf07BD0e'
const chain = EvmChain.GOERLI
const response = await Moralis.EvmApi.token.getWalletTokenBalances({
address,
chain
})
console.log(response.toJSON())
}
runApp()
As every detail of a smartContract is public. I don't want to use the API of a third party like Moralis as it slows the app.
Yes, you are right all the smartContract data on the blockchain is public. But it is not always easy to read this data. To read data from the blockchain you would need to run your own local rpc node or you may have to rely on another 3rd node provider or API provider to read the blockchain data.
Moralis provides the data to users through the API and it is one of the fastest ways to read real-time blockchain data.
If you don't want to use any third-party providers for reading blockchain data, one option is to run your own full RPC node. This requires setting up a server and syncing the entire blockchain to your machine. It gives you the ability to read the data directly from the blockchain. This can be a good option if you have the technical expertise and the resources to set up and maintain a full node.
But this is not an easy option nor the fastest option to choose if you are only looking to get the ERC20 token wallet balances.

How to call Solidity Function to return Ether from Smart Contract?

I have deployed a smart contract on a local truffle project and I am trying to interact with it in a React project using web3. The following solidity function should send Ether what was previously deposited in the contract to a user address on a boolean condition:
function Payout() public{
require( voteEndTime< block.timestamp, "Voting Time is not up. Please come back later" );
Voter storage sender = voters[msg.sender];
if (negativeVotes > positiveVotes){
require(!sender.option, "Wrong Vote. Stake is distributed among winners");
payable(address(msg.sender)).transfer((stakes*sender.amount) / negativeStakes);
}
else if (positiveVotes > negativeVotes){
require(sender.option, "Wrong Vote. Stake is distributed among winners");
payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);
}
else{
payable(address(msg.sender)).transfer((stakes*sender.amount) / stakes);
}
}
The contract is definitely able to read the user's address using msg.sender because it has worked in the other functions I have. Every other function in the contract is also working fine. I can interact with it and I am able to send Ether to it. The problem occurs when I am trying to return the Ether stored in the contract to an account. I am trying to call my Payout() function using the following web3 call in React on button click:
var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })
I have specified a higher gas limit, because the contract runs out of gas if I try to use the gas estimation seen below. The function this call is present in looks like this:
const giveMeMoney = async (e) => {
const web3 = await new Web3(window.ethereum);
await window.ethereum.enable();
var Accounts = await web3.eth.getAccounts()
account = Accounts[0]
console.log(account)
const gas = await BallotContract.methods.Payout().estimateGas();
console.log(gas)
var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })
}
I am able to access the function from the frontend and it is returning the correct string if a "require" condition is not met. My problem is that the contract does not return any Ether if the conditions are met and this line:
payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);
...is accessed. I am getting the following error:
Uncaught (in promise) Error: Returned error: VM Exception while processing transaction: revert
at Object.ErrorResponse (errors.js:30)
at onJsonrpcResult (index.js:162)
at XMLHttpRequest.request.onreadystatechange (index.js:123)
ErrorResponse # errors.js:30
Now I am unsure what could be the problem, because the contract is running perfectly fine if I test it in Remix. Does anybody see the problem or have a workaround for this kind of problem?
The "out of gas" error is caused by the transfer function. This function has a gas limit of 2100; I recommend you use call, you can check how here.
Also the boolean value of the Voter struct defaults to false. So if the negative votes win, but the user didn't vote, they still can try to claim the reward, even if the amount is 0. I recommend you check how to use an enum, it can be very useful.

How to do something as soon as Skill is created?

In my Alexa Skill i set dynamic entities in 'addRequestInterceptors' as the entities must be available as soon as possible, the issue is that if the user says 'Alexa, open SKILLNAME' the entities are initialized correctly, but if the user instead says 'Alexa, ask SKILLNAME where is DYNAMICENTITY' at this point the skill fails as the DYNAMICENTITY is not yet set.
So my question is, how can i set my dynamic entities as soon as possible like when the skill is created? I've tryed the LaunchIntent but as in the case above it's avoided if the user make the question inside the invocation..
So LaunchIntent and addRequestInterceptors aren't good to do it..
Here is my code which i should run as soon as possible:
const LoadListaPuntiVendita = {
async process(handlerInput) {
const {attributesManager, requestEnvelope} = handlerInput;
const sessionAttributes = attributesManager.getSessionAttributes();
const attributes = await attributesManager.getPersistentAttributes() || {};
const piva = attributes.hasOwnProperty('piva') ? attributes.piva : null;
sessionAttributes["piva"] = piva;
if (!piva || piva === null) {
return;
}
let negozi = sessionAttributes['negozi']
if (!negozi) {
const response = await logic.fetchNegozi(piva);
sessionAttributes['negozi'] = response;
addDynamicEntities(handlerInput.responseBuilder, 'PuntoVenditaType', response);
}
}
};
Here's one possible bug on first glance. This will only run as expected after you've had at least one exchange in which "piva" had been saved and set as a persistent value for the customer.
If you're running this the moment the skill is initialized, it still must be run after the persistence adapter has been initialized and retrieved the value of "piva" from your store AND there must be have been a value stored for "piva" or the code returns early without setting the entity.

Stripe Create Payment Intents Promise Never Resolves

I signed up for a Stripe account and followed some simple steps to get up and running with Node. I just installed the package and tested a payment Intents with my test key:
const Stripe = require('stripe');
const handleStripe = async () => {
const stripe = Stripe(testKeyString);
console.log(“we make it here”);
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
payment_method_types: ['card'],
receipt_email: 'jenny.rosen#example.com',
});
//we never make it here
console.log(paymentIntent);
}
catch(err){
//we never make it here either
console.log(err);
}
}
The console logs “we make it here”, but nothing else. The promise is never resolved.
I suspect that this might be a bug with the stripe npm package. Anybody have any thoughts on why the promise is never returned?
EDIT: sorry, I wasted everyone’s time here. I was following the docs QuickStart where it said “install a client library” and I assumed it was for the front end. So a very silly mistake on my part thinking that it was a good idea to make a payment intent from the front end with a secret key. Just getting going with the Stripe API and I’m off to a bad start. Thanks for your comments and answer
Thanks
What happens if you run it without the try/catch? Also what do you get if you try https://status.stripe.com/reachability from that server - are you sure you can reach Stripe's servers?

Let users create elements that only they can see in Firebase (in React)

I recently started learning firebase and i find it great. I was able to let users register/login with email and password and once they are on the app they can create "Cards" with some data. However any user that creates an account on my app can then view and delete, edit, etc. any Card created by any user.
My question is simply how can i only display Cards strictly to the users who created them only?
Here is my code up to now:
useEffect(() => {
const cardRef = firebase.database().ref('Cards')
cardRef.on('value', (snapshot) => {
const cards = snapshot.val()
const cardslist = []
for (let id in cards) {
cardslist.push({id, ...cards[id] })
}
setCardslist(cardslist)
})
},[])
//in my jsx i then have cardslist which displays the cards
<div>{cardslist}</div>
Here is what you need to do:
1 - Make sure every "card" document has a "creator" field, so you can filter the query with something like...
your_query().where("creator", "==", current_viewer_id)
2 - Make sure you use Firestore Rules, to limit read/write operations on a card to only the creator of the card. Your use case is one of the first examples you'll see in Firestore Rules documentation and explainer videos.
Good luck! You're almost there.

Resources