Given an ERC20 token address, how do you get the current price of a single token of the ERC20? - erc20

I'm trying to solve this problem where if I'm given an ERC20 token address such as 0xff75ced57419bcaebe5f05254983b013b0646ef5. And I do not know the name of the token. How can I get the current price for a single token of the ERC20 given the ERC20 token address?
I'm trying to do this in python and I can't seem to find an API that does this. I was searching through Coingecko but it requires the name of the token. Is there any way to go straight to the current price with the address instead of having to know the name of the token?
Thank you so much,
Tony

You can this on-chain with using chainlink oracle. You need to import this first
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
Then write a function inside the contract
function getTokenValue(address _token)public view returns(uint256,uint256){
// price feed address
address priceFeedAddress=tokenPriceFeedMapping[_token];
AggregatorV3Interface priceFeed=AggregatorV3Interface(priceFeedAddress);
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
// decimals returns uint8
uint256 decimals=uint256(priceFeed.decimals());
return (uint256(price),decimals);
}
chainlink documentation

Related

Paginating data from Smart contract in Solidity

I have a smart contract that uses mapping to store data in it. I want to paginate the data mapping.
I have the following Smart contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract Pagination {
uint public stringCount;
mapping (uint => string) public strings;
function add(string memory item) public {
stringCount++;
strings[stringCount]=item;
}
}
I also want to know the best practice out there.
The two approaches in my mind are:
Get the total count of items in the mapping in the front-end application and implement the pagination logic there and load only specific items from the mapping.
Implement the pagination logic in the smart contract (something like what we have been doing in Web2)
Note: I have gone through some questions about paginations on StackOverflow but they all are regarding the arrays.
Approach 1 - Analysis
You can get the total count via
const stringCount = await contractInstance.methods.stringCount().call(); and then implement pagination on frontend.
If you go via this approach, you'll have to call smart contract to fetch string one by one.
Approach 2 - Analysis
Let's say you have a function like:
function getStrings(uint startIndex, uint endIndex) view public returns (string[] memory)
{
// logic goes in here
}
Here you will be making only one 2 calls for fetching whole page. First request for getting stringCount and then only 1 request again for next strings.
So, the second approach is better.

Matching entire line of code (string format) with Python regex

Using Python and Regex, I have a string variable strSourceCode with the following
'\n function balanceOf(address account) external view returns (uint256);\r\n function transfer(address recipient, uint256 amount) external returns (bool);\r\n function allowance(address owner, address spender) external view returns (uint256);\r\n function approve(address spender, uint256 amount) external returns (bool);\r\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\r'
I would like to use re.findall and for example match the word 'allowance' and it should return back the entire line of code starting with \n and ending with \r, shown below
'\n function allowance(address owner, address spender) external view returns (uint256);\r'
I've been struggling for couple of hours now and have decided to post. Any help would be great! Thank you.
I have tried re.M flag as well but it does not seem to work, I'm definitely doing something wrong.
The following regex will find any matches which start with '\n ', have anything before and after your keyword/key phrase, and end in '\r'.
import re
strSourceCode = '\n function balanceOf(address account) external view returns (uint256);\r\n function transfer(address recipient, uint256 amount) external returns (bool);\r\n function allowance(address owner, address spender) external view returns (uint256);\r\n function approve(address spender, uint256 amount) external returns (bool);\r\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\r'
what_to_match = 'allowance'
pattern = f'\n .*{what_to_match}.*\r'
matches = re.findall(pattern, strSourceCode)

How do I get the user's neighborhood or city from $user.currentLocation?

I'm wondering if maybe some one can help me figure this out. How do I get the user's neighborhood (or city) from $user.currentLocation?
I've been trying various things, and looked at the docs, especially here:
https://bixbydevelopers.com/dev/docs/dev-guide/developers/library.geo#searchregion-and-currentlocation
But it's not quite what I'm looking for.
If the user says, "What's the weather?" without specifying the place, my getWeather action looks like this:
input (where) {
min (Optional) max(One)
type (viv.geo.NamedPoint)
default-select {
with-rule {
select-first
}
}
default-init {
if ($user.currentLocation.$exists) {
intent {
goal: geo.GeoPoint
value-set: geo.CurrentLocation { $expr ($user.currentLocation) }
}
}
}
This will give me the long/lat that I use for the weather API query. But I'd like to display (though not say) the neighborhood (or city) of the users current location in a view.
(I believe if I change the goal/value-set to SearchRegion, then I can get the city, but not the long/lat of $user.currentLocation. Instead, I get a generic long/lat of the city, which isn't specific enough.)
So, I want 1) The long/lat of $user.currentLocation for the API and 2) the neighborhood (or city) of that long/lat for a view. I can't figure out how to get both.
The input you've defined is a NamedPoint and NamedPoint.point is a GeoPoint so it should have the lat/longs you need.
To get the city, the NamedPoint.address should contain an Address structure to access the Street address, city, state, country, etc.
Another option might be the reverseGeo property of a GeoPoint to get the Address. This property is a lazy-source so the data will not be available until this property is called.

Get Receipt number on Stripe C#

Please how can I get the receipt number on Stripe with c#
My image :
https://www.casimages.com/i/191231053006538388.png.html
Maybe with a Session ID ?
You'd access the Charge object and it's a field on that resource.
You say you're using Checkout. So the Charge is under session.payment_intent.charges.data[0]. It requires a little digging to get it but it's all there. I'd suggest that when you receive the event as part of fulfilling the order etc, retrieve the Session(stripe.com/docs/api/checkout/sessions/retrieve) and expand "payment_intent". Then session.PaymentIntent.Charges.Data[0].ReceiptNumber is the value you're looking for.
static void CheckoutSessionReceiptEmail()
{
var service = new Stripe.Checkout.SessionService();
var session = service.Get(
"cs_test_nHUZtpUvaI80YAKGgCMGyeHfjQ6nMtUhVLeVpowWsgpfyGujccGxnAuJ",
new Stripe.Checkout.SessionGetOptions
{
Expand = new List<string> { "payment_intent" }
}
);
Console.WriteLine(session.PaymentIntent.Charges.Data[0].ReceiptNumber);
}

How to call a contract function from a specific address

I want to use web3 to call a contract function(sendTransaction not call) from a specific address that I hold the private key to. I also have the contract instance connected. I know I have to dio something like web3.personal.unlockAccount(address,password,duration)
And then specify the from address.
So my question is, is "password" where I enter my private key? And how do I pass that address into fromAddress once I unlock it.
Or is there a more streamlined way to go about it?
is "password" where I enter my private key?
No, it's not. Actually it is a password, which you entered when you were creating account and which was used to generate your keystore file.
If you use web3.personal.unlockAccount(address,password,duration) you need to have your keystore file in the keystore folder near chaindata of geth.
Another way will be to use web3.eth.sendRawTransaction from web3.py, but it will be a little bit clunky to call contract method from it.
key = '0x' + 'YOUR-PRIVATE-KEY
transaction = {
'to': _to,
'value': 0,
'gas': 300000,
'gasPrice': 23000000000,
'nonce': web3.eth.getTransactionCount(_from),
'chainId': int(web3.admin.nodeInfo['protocols']['eth']['network']),
'data': b''
}
signed = web3.eth.account.signTransaction(transaction, key)
print("Transaction Hash: " + web3.toHex(web3.eth.sendRawTransaction(signed.rawTransaction)))
My suggestion will be to create keyfile recognisable by Ethereum clients by using web3.eth.account.encrypt (web3.py because web3.js yet lack this functionality) and after you generate it put it in the right folder and try simply to unlock account.

Resources