How get USDT balance BEP-20? web3.eth.getBalance - binance-smart-chain

Good day! Can you please tell me how you can get the balance of the USDT address? I found a way to get BNB balance (https://docs.binance.org/smart-chain/developer/BEP20.html), but there is no example for USDT

Token balance of an address is not a property of the address. It is stored in each of the token's contract. So you need to call the balanceOf() function of the token contract, passing it the holder address as a parameter.
For example the BUSD token:
const busdAddress = "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56";
const holderAddress = "0x8894e0a0c962cb723c1976a4421c95949be2d4e3";
// just the `balanceOf()` is sufficient in this case
const abiJson = [
{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},
];
const contract = new web3.eth.Contract(abiJson, busdAddress);
const balance = await contract.methods.balanceOf(holderAddress).call();
// note that this number includes the decimal places (in case of BUSD, that's 18 decimal places)
console.log(balance);

Related

Cypress: Get JQuery value without needing `then` or `each`

I'm hoping someone can help, but I've posted this as a Cypress discussion as well, although it might just be my understanding that's wrong
I need to get the Cypress.Chainable<JQuery<HTMLElement>> of the cell of a table using the column header and another cell's value in the same row.
Here's a working example JQuery TS Fiddle: https://jsfiddle.net/6w1r7ha9/
My current implementation looks as follows:
static findCellByRowTextColumnHeaderText(
rowText: string,
columnName: string,
) {
const row = cy.get(`tr:contains(${rowText})`);
const column = cy.get(`th:contains(${columnName})`)
const columnIndex = ???
return row.find(`td:eq(${columnIndex})`)
}
This function is required because I want to write DRY code to find cells easily for content verification, clicking elements inside of it etc.
The only example I've seen is this https://stackoverflow.com/a/70686525/1321908, but the following doesn't work:
const columns = cy.get('th')
let columnIndex = -1
columns.each((el, index) => {
if (el.text().includes(columnName) {
columnIndex = index
}
cy.log('columnIndex', columnIndex) // Outputs 2 as expected
})
cy.log('finalColumnIndex', columnIndex) // Outputs -1
My current thinking is something like:
const columnIndex: number = column.then((el) => el.index())
This however returns a Chainable<number> How to turn it into number, I have no idea. I'm using this answer to guide my thinking in this regard.
Using .then() in a Cypress test is almost mandatory to avoid flaky tests.
To avoid problems with test code getting ahead of web page updating, Cypress uses Chainable to retry the DOM query until success, or time out.
But the Chainable interface isn't a promise, so you can't await it. You can only then() it.
It would be nice if you could substitute another keyword like unchain
const column = unchain cy.get(`th:contains(${columnName})`)
but unfortunately Javascript can't be extended with new keywords. You can only add methods like .then() onto objects like Chainable.
Having said that, there are code patterns that allow extracting a Chainable value and using it like a plain Javascript variable.
But they are limited to specific scenarios, for example assigning to a global in a before() and using it in an it().
If you give up the core feature of Cypress, the automatic retry feature, then it's just jQuery exactly as you have in the fiddle (but using Cypress.$() instead of $()).
But even Mikhail's thenify relys on the structure of the test when you add a small amount of asynchronicity
Example app
<foo>abc</foo>
<script>
setTimeout(() => {
const foo = document.querySelector('foo')
foo.innerText = 'def'
}, 1000)
</script>
Test
let a = cy.get("foo").thenify()
// expect(a.text()).to.eq('def') // fails
// cy.wrap(a.text()).should('eq', 'def') // fails
cy.wrap(a).should('have.text', 'def') // passes
let b = cy.get("foo") // no thenify
b.should('have.text', 'def') // passes
Based on your working example, you will need to get the headers first, map out the text, then find the index of the column (I've chosen 'Col B'). Afterwards you will find the row containing the other cell value, then get all the cells in row and use .eq() with the column index found earlier.
// get headers, map text, filter to Col B index
cy.get("th")
.then(($headers) => Cypress._.map($headers, "innerText"))
.then(cy.log)
.invoke("indexOf", "Col B")
.then((headerIndex) => {
// find row containing Val A
cy.contains("tbody tr", "Val A")
.find("td")
// get cell containing Val B
.eq(headerIndex)
.should("have.text", "Val B");
});
Here is the example.

How to mapping the price of an asset with chain links and solidity?

I have a contract that has to save the time and price of eth via chainlink. The time works and has no problems. The price, on the other hand, fails to be recorded either with an array or with a mapping. I have tried several solutions, which include push().
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
interface EACAggregatorProxy {
function latestAnswer() external view returns (int256);
}
contract oracleLink {
uint256 deadline;
uint256 startTime = startTimes[block.timestamp];
mapping(uint => uint) startTimes;
address public chainLinkETHUSDAddress = 0x9326BFA02ADD2366b30bacB125260Af641031331;
uint public ethPrice = 0;
uint256 price = ethPrice;
mapping(uint => uint) ethPrice;
function priceOnTime() public payable {
deadline = block.timestamp + (numberOfSeconds * 1 seconds);
int256 chainLinkEthPrice = EACAggregatorProxy(chainLinkETHUSDAddress).latestAnswer();
ethPrice = uint(chainLinkEthPrice / 100000000);
return ethPrice;
}
}
The chainLinkETHUSDAddress address hardcoded in your source contains a contract only on the Kovan testnet. Meaning, this code works only on this testnet or its forks, and fails on other networks.
If you want to use the returned value in Remix, you need to create a local fork of the Kovan testnet and then connect to this local network using the Environment selectbox in Remix.
Your code is not using the mapping correctly. I mapping is like an array, just more efficient in some ways, but also has some limitations.
so to use your mapping you need to use it as
ethPrice[x] = y;
Where both x and y are an uint (as you specified the mapping uint => uint). So each unique uint maps (refers) to another uint.
ethPrice[x] = uint(chainLinkEthPrice / 100000000);
Where x is an uint you use to lookup the value later on with.
You're incorrectly storing the mapping. Mapping has to be stored as variable[key]=value.
https://www.tutorialspoint.com/solidity/solidity_mappings.htm

#SNMP - GetBulk V2 request is limited to 100 results?

I'm trying to perform the below request and the results should be around 900 variables, not 100.
it doesn't matter how many oids I send 1 or 10, I always get no more than 100 variables.
what I'm doing wrong?
var readCommunity = new OctetString("XXXXX");
var oidsList = new List<string>
{
"1.3.6.1.2.1.2.2.1.3",
"1.3.6.1.2.1.2.2.1.5",
"1.3.6.1.2.1.2.2.1.6",
"1.3.6.1.2.1.2.2.1.7",
"1.3.6.1.2.1.2.2.1.8",
"1.3.6.1.2.1.2.2.1.2",
"1.3.6.1.2.1.2.2.1.10",
"1.3.6.1.2.1.2.2.1.16",
"1.3.6.1.2.1.2.2.1.14",
"1.3.6.1.2.1.31.1.1.1.6"
};
var oids = oidsList.Select(oid => new Variable(new ObjectIdentifier(oid))).ToArray();
ISnmpMessage request= new GetBulkRequestMessage(
0,
VersionCode.V2,
readCommunity,
0,
1000,
oids);
var response = request.GetResponse(60000, new IPEndPoint(IPAddress.Parse("1.1.1.1"), 161));
You can send a request asking for as many items as you wished, but it is the agent who decides how many to return to you. That's how the standard defines,
The receiving SNMP entity produces a Response-PDU with up to the
total number of requested variable bindings communicated by the
request.
While the maximum number of variable bindings in the Response-PDU is
bounded by N + (M * R), the response may be generated with a lesser
number of variable bindings (possibly zero) for either of three
reasons.
Reference

Power Query delayed recursion

I'm very new to Power Query and trying to piece a little demo together in Excel.
I have two web endpoints: I have to post some content to the first endpoint, this gives me the url of the second endpoint and then I have to query this second endpoint for the actual results. The second endpoint gives back a json response and in it, there is a field that represents if the results are ready or not. If the results are ready, they can be processed, if not, the endpoint should be queried again at a later date.
Here's the code I have so far:
let
apikey = "MYAPIKEY",
proxyendpoint = "URL OF THE FIRST ENDPOINT",
bytesbody = File.Contents("FILE TO POST"),
headers = [#"Ocp-Apim-Subscription-Key" = apikey],
bytesresp = Web.Contents(proxyendpoint, [Headers=headers, Content=bytesbody]),
jsonresp = Json.Document(bytesresp),
opLoc = jsonresp[OperationLocation],
getResult = (url) =>
let
linesBody = Web.Contents(url, [Headers=headers]),
linesJson = Json.Document(linesBody),
resultStatus = linesJson[status],
linesData = if (resultStatus = "Succeeded") then
linesJson[recognitionResult][lines]
else
Function.InvokeAfter(()=>#getResult(url),#duration(0,0,0,5))
in
linesData,
linesText = List.Transform(getResult(opLoc), each _[text]),
table = Table.FromList(linesText)
in
table
My problem is that when I check with Fiddler, I see the second endpoint queried once, I can check there in the response that the results are not ready, the data loading "hangs", but I cannot see any additional calls to the second endpoint, so basically my recursive calls are not being evaluated.
What am I doing wrong?
With the ()=> in the first argument of Function.InvokeAfter, the result of Function.InvokeAfter will be the function getResult, rather than the result from getResult. So it should be left out:
Function.InvokeAfter(#getResult(url),#duration(0,0,0,5))
Turns out my code was basically right. The issue was that Web.Contents() does some internal caching, that's why I couldn't see any more calls in Fiddler and that's why my data loading "hang" (since the first time the recursion exit criterion was false and the result got cached, every subsequent recursion just used the same data).
I created some POCs for the delayed recursion scenario and strangely, everything worked. I changed things around until I reached a version of the POC where the only difference was the Web.Contents() call. So I did a search for this specific issue and found a post here.
So as suggested in this post, I added a new header value to every Web.Contents() call to avoid the response being cached (also cleaned up the code a bit):
let
apikey = "MYAPIKEY",
proxyendpoint = "URL OF THE FIRST ENDPOINT",
bytesbody = File.Contents("FILE PATH TO BE POSTED"),
headers = [#"Ocp-Apim-Subscription-Key" = apikey],
bytesresp = Web.Contents(proxyendpoint, [Headers=headers, Content=bytesbody]),
jsonresp = Json.Document(bytesresp),
opLoc = jsonresp[OperationLocation],
getResult = (url, apiKeyParam) =>
let
// note the extra header here, which is different in every call
currentHeaders = [#"Ocp-Apim-Subscription-Key" = apiKeyParam, #"CacheHack" = Number.ToText(Number.Random())],
linesBody = Web.Contents(url, [Headers=currentHeaders]),
linesJson = Json.Document(linesBody),
resultStatus = linesJson[status],
result = if (resultStatus = "Succeeded") then linesJson[recognitionResult][lines]
else Function.InvokeAfter(()=>#getResult(url, apiKeyParam), #duration(0,0,0,5))
in result,
linesText = List.Transform(getResult(opLoc, apikey), each _[text]),
table = Table.FromList(linesText)
in table

IBeacon. Custom filter regions

Good day. Sorry my English is bad. Whether prompt there is an opportunity to define region of bicons not on UUID and on it is one part. For example, we have 2 regions:
1 - UUID = 57547265-7261-772e-636f-6c0054000000
2- there is only the full part (most likely this is the fourth last group) -
6c001137e000
Can I just specify in my method a filter only for the last group of UUID?
For example:
List<string> listUuids =new List<string>()
{ "57547265-7261-772e-636f-6c0054000000" , "6c001137e000" };
for (int i = 0; i <listUuids.Count; i ++)
{
var uuid = Identifier.Parse (listUuids [i]);
var region = new Region ("R" + i, uuid, null, null);
beaconManager.StartRangingBeaconsInRegion (region);
}
I would really appreciate any answers!
Best Regards!
You can do this with a custom beacon parser. Like this:
BeaconManager.GetBeaconParsers().clear();
BeaconMannager.GetBeaconParsers().add(new Beacon parser().setBeaconLayout("m:2-3=0215,i:14-19,i:4-13,i:20-21,i:22-23,p:24-24");
var region = new Region("partial UUID region", Identifier.parse("0x6c001137e000"), null, null)
The above custom parser defines four identifiers for a iBeacon packet. The first identifier is the last 6 bytes of the UUID. The second identifier is the first 10 bytes of the UUID. The third and fourth identifiers are the major and minor, respectively.
Using the region defined above will match any beacon matching the specified last 6 bytes of the UUID.

Resources