How to call a contract's balanceOf function for a specific block using Web3.py - python-3.x

How can I get the balance of a token at a specific time? I'm using Web3.py. Nothing I seem to try works. I can get the latest balance of USDC for a particular wallet like this:
contract = web3.eth.contract('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', abi=self.ABI)
raw_balance = contract.functions.balanceOf('0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B').call()
I try to specify the block number inside of the call() function:
raw_balance = contract.functions.balanceOf(wallet_address).call(block_identifier=13372637)
But I get an error each time:
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://mainnet.infura.io/v3/...

Try doing
contract.functions.<function>.call(block_identifier=web3.eth.get_block('latest')['number'])
If that works using the latest block, then you might need to pay extra to get historical data, unfortunately...
EDIT:
Another possibility is you're using np.int64 or another int variant. Try enforcing int(block_no) and see if that works
EDIT EDIT:
Also, try using https://docs.alchemy.com/alchemy/ instead of Infura. Free account worked for me..

Related

Integrate GeeTestTask(python3_anticaptcha) with selenium in python3

I have a problem about python3_anticaptcha (api provided by anti-captcha.com), search on web, find support and try over a month but no luck.
API doc:
https://anticaptcha.atlassian.net/wiki/spaces/API/pages/416972814/GeeTestTaskProxyless+-+captcha+from+geetest.com+without+proxy
I am doing a auto login on a website, and copy the api on anti-captcha's doc:
def runGee(self, challenge):
print("start gee")
try:
# Enter the key to the AntiCaptcha service from your account. Anticaptcha service key.
ANTICAPTCHA_KEY = "mycode"
# обязательные параметры
websiteURL = "https:\/\/www.nike.com.hk"
gt = "2328764cdf162e8e60cc0b04383fef81"
print("sloving1")
print("challenge:" ,challenge)
# пример работы с GeeTestTask без прокси
result = GeeTestTaskProxyless.GeeTestTaskProxyless(anticaptcha_key=ANTICAPTCHA_KEY,
websiteURL=websiteURL,
gt=gt).captcha_handler(challenge=challenge)
print("sloving2")
print(result)
print("--end gee--")
except Exception as err:
print(err)
print("--end with error--")
However, the geetask start over 3 minute(or more), and got error everytime. usually error code like:
{'errorId': 34, 'errorCode': 'ERROR_TOKEN_EXPIRED', 'errorDescription': 'Captcha provider
reported that additional variable token has expired.', 'taskId': 1204556667}
or
{'errorId': 12, 'errorCode': 'ERROR_CAPTCHA_UNSOLVABLE', 'errorDescription': ' Captcha
could not be solved by 5 different workers.', 'taskId': 1204060350}
..etc
depends on what parameter i passed.
May i know am i passing the right value to geetask? or some wrong on the code?
Moreover, if geetest return the correct value, i need to do any else to pass capcha(or pass code to geetest server) or GeeTestTaskProxyless already done(not to do anything)?
it is extremely hard to me, does anyone had used this api successfully? Thanks
The problem is not in the anticaptcha but in the geetest provider.
The token challenger can only be used once, when your browser loads the geetest captcha it expires the token.
To fix this problem, you only need to block the request that consumes the token in your browser.
go to devtools and add the block for the geestest captcha API in the browser, like this:
You can automatically integrate this into the selenium with the following command:
driver.execute_cdp_cmd('Network.setBlockedURLs', {"urls": ["api.geetest.com/get.php"]})
driver.execute_cdp_cmd('Network.enable', {})
It seems for me that those errors are because of proxy (if you use any) or just bad IP.
Personally, I use another captcha service and I didn't have such problems with it.
I advice you to try it, it's actually much easier: https://2captcha.com/2captcha-api#solving_geetest
You should send a request like this one:
https://2captcha.com/in.php?key=1abc234de56fab7c89012d34e56fa7b8&method=geetest&gt=f1ab2cdefa3456789012345b6c78d90e&challenge=12345678abc90123d45678ef90123a456b&api_server=api-na.geetest.com&pageurl=https://www.example.com/page/
What you need to archieve is to get correct answer from it, like this one:
{
"challenge":"1a2b3456cd67890e12345fab678901c2de",
"validate":"09fe8d7c6ba54f32e1dcb0a9fedc8765",
"seccode":"12fe3d4c56789ba01f2e345d6789c012|jordan" }
Then you just need to implement that answer on a site. Just read the first link I gave you.
Cheers.

How to navigate Edge extension local storage callback requirements

I'm trying to access the local storage data in Edge set by my options page, using my popup script. Is there a current, working example of this available?
I was using localStorage, but it would only update the popup if I reloaded the extension after saving changes in my options page. I want to make it easier on the user by allowing the popup to access it immediately after saving, without reloading. I found the browser.storage.local.get(), but documentation conflicts everywhere I look, and I can't find viable working examples.
I have used, per Edge documentation:
browser.storage.local.get("sample");
But it throws an error requiring a callback function. So then I used:
let sample = browser.storage.local.get("example");
sample.then(ifGood, ifBad);
I get an error regarding property "then".
Then I simply tried adding a callback to the action itself:
sample = browser.storage.local.get("example", callbackFunction);
function callbackFunction(data){
alert(data);
}
The end alert should display a string, but it just displays an empty Object. How do I access the data returned in the callback? I tried callbackFunction(this) as an argument in the get, but it throws an error about the syntax of the get.
I found a work-around using browser.runtime.reload() in the Options page when saving the changes. It still reloads the extension, but it does it without requiring the user to do it manually.
You should use this syntax:
browser.storage.local.get(propertyName | null, callbackFn)
where
callbackFn = function fn(resultObject) {...}
When you pass null you will get whole storage object.
Look for example 1 or example 2 in my Edge extension.

Triggering Google Cloud function using console

I am trying to use the google cloud console to test a cloud function. Below is a snippet.
exports.requestCreated = functions.firestore
.document('users/{userId}/requests/{requestId}')
.onWrite((change, context) => {
// execute operation
});
I have tried all sorts of combination of JSON data. E.g.
{"userId":"Xl86pqOpF9T2MAn12p24OJAfYJW2","requestId":"abc1234"}
But I keep getting the following statement in logs:
Request created by {userId}
The actual userId is not being read from the JSON data in the console. Can you help?
This is not a problem with the execution of the cloud function. It's a problem with hardcoding the string.
'users/{userId}/requests/{requestId}' is a hardcoded string. Node.js will not automatically replace {userId} with the value of the variable userId.
Following this previous SO post, try something like this using template strings:
`users/${userId}/requests/${requestId}`
Please note it is surrounded by backticks (`), not single quotes (').
This assumes you already have a userId and requestId variables defined. You must restructure your cloud function like this to retrieve that data. Notice that the specific variable values must be extracted from the event variable.
Thank you, Nareddyt. The function is for Firestore, and the way it is written right now checks if a new document is created under the collection requests. I tried replacing the string as you suggested, but as you pointed out, it requires these variables to be defined. I do not quite understand how to restructure the cloud function because the syntax I have used is how event detection is suggested in the Firestore documentation. My function currently works in its entirety, but testing it is a major pain. I have to go through my mobile app and do the whole userflow to test this function. I am new to Node.js and any guidance would be appreciated.

Updating a Contentful entry

I've hit a brick wall whilst attempting to update a Contentful entry using a typical http request in Javascript; I receive the error code "VersionMismatch" which, according to the documentation, means:
This error occurs when you're trying to update an existing asset,
entry or content type, and you didn't specify the current version of
the object or specify an outdated version.
However, I have specified the current version of the entry using the 'X-Contentful-Version' header parameter as per the documentation, and have used the dynamic property value from 'entry.sys.revision' as the parameter value (as well as hardcoding the current version, plus a bunch of different numbers, but I always receive the same error). This post reported the exact same issue, but was seemingly resolved by adding this header parameter.
Here's my current code, that is also using the Contentful API to retrieve entries from my Contentful space, but I'm having to use plain Javascript to put the data back due to specific requirements:
var client = contentful.createClient(
{
space: space_id,
accessToken: client_token
}
);
client.getEntry(entry_id).then((entry) => entry).then(function(entry) {
// update values of entry
entry.fields.title = "Testing";
// post data to contentful API
var request = new XMLHttpRequest();
request.open('PUT', 'https://api.contentful.com/spaces/' + space_id + '/entries/' + entry_id);
request.setRequestHeader('Authorization', 'Bearer my_access_token');
request.setRequestHeader('Content-Type', 'application/vnd.contentful.management.v1+json');
request.setRequestHeader('X-Contentful-Content-Type', entry.sys.contentType.sys.id);
// setting the 'X-Contentful-Version' header with current/soon to be old version
request.setRequestHeader('X-Contentful-Version', entry.sys.revision);
// convert entry object to JSON before sending
var body = JSON.stringify({fields: entry.fields});
request.send(body);
});
Contentful developer here.
It looks like you get your content with the Contentful Delivery SDK and then try yo use that data to update content. That will not work. Instead I recommend using the Contentful Management SDK which will take care of all the versioning header for you.
I know its too late to answer here, but I am also facing same issue while doing this process.
So I asked this question and got the answer how we can achieve this without using Contentful-management sdk. My intention is not to suppress this sdk but we should be go to perform operation without it. I am trying to do it via postman but facing issue.
So I just post it and got the answer but understand the problem why I am not able to update the content because of two things
URL (api.contentful.com is the correct url if we are trying to update the content)
access_token (if we are using api.contentful.com which means we have to generate our personal token (management token) in the contentful, we cannot use preview/delivery tokens)
These are the highlighted point which we need to consider while doing update. I posted the link below may be it help someone in future.
Updating entry of Contentful using postman

symfony2 get firewall name on login page

I'd want to use a login page to access different firewalls, so I need to get information about the firewall I'm logging in.
In my controller I'd use
$this->container->get('security.context')->getToken()->getProviderKey()
but as an anonymous user I don't have access to getProviderKey method.
I could also parse
_security.xxx.target_path
to get xxx firewall but I'm looking for a more general solution if it exists at all.
Any idea?
As of symfony 3.2, you can now get the current firewall configuration using the following:
public function indexAction(Request $request)
{
$firewall = $this->container
->get('security.firewall.map')
->getFirewallConfig($request)
->getName();
}
Ref: http://symfony.com/blog/new-in-symfony-3-2-firewall-config-class-and-profiler
For Symfony 3.4 I wrote this to avoid referencing the non-public "security.firewall.map" service:
$firewallName = null;
if (($firewallContext = trim($request->attributes->get("_firewall_context", null))) && (false !== ($firewallContextNameSplit = strrpos($firewallContext, ".")))) {
$firewallName = substr($firewallContext, $firewallContextNameSplit + 1);
}
(Referencing "security.firewall.map" on 3.4 will throw an exception.)
Edit: This will not work in a custom exception controller function.
I was doing a little research on this myself recently so that I could send this information in an XACML request as part of the environment.
As far as I can tell from GitHub issues like this one:
https://github.com/symfony/symfony/issues/14435
There is currently no way to reliably get the information out of Symfony except the dirty compiler pass hack suggested on the linked issue. It does appear from the conversation on these issues, they are working on making this available, however, the status is still open, so we will have to be patient and wait for it to be provided.
#Adambean's answer is pretty elegant, but I'd write it as a one-liner:
$firewallName = array_slice(explode('.', trim($request->attributes->get('_firewall_context'))), -1)[0];
The difference is that $firewallName will always be a string (which may be empty).
Also, please note that this answer (like #Adambean's) doesn't work for a firewall with a dot in its name.

Resources