Why Uniswap V2's function getPair() is returning a null address - blockchain

I'm trying to get the pair address if the USDC / USDT pair on uniswap using the v2 core. The pair address exists on uniswap but when i run the code it returns me a null address (0x0000000000000000000000000000000000000000). Im using the goerli testnet
The main file
const IUniswapV2Pair = require("#uniswap/v2-core/build/IUniswapV2Pair.json");
const IERC20 = require("#openzeppelin/contracts/build/contracts/ERC20.json");
const { provider, uFactory } = require("./config");
const ethers = require("ethers");
let tokenA, tokenB;
const getTokenAndContract = async (
_tokenAAddress,
_tokenBAddress,
_provider
) => {
const tokenAcontract = new ethers.Contract(
_tokenAAddress,
IERC20.abi,
_provider
);
const tokenBcontract = new ethers.Contract(
_tokenBAddress,
IERC20.abi,
_provider
);
tokenA = {
address: _tokenAAddress,
decimals: 18,
};
tokenB = {
address: _tokenBAddress,
decimals: 18,
};
};
const tokensAndContract = getTokenAndContract(
process.env.TOKEN_A,
process.env.TOKEN_B,
provider
);
const main = async () => {
const pairAddress = await uFactory.getPair(tokenA.address, tokenB.address);
console.log(pairAddress); // output = 0x0000000000000000000000000000000000000000
};
main();
the config file
const IUniswapV2Factory = require("#uniswap/v2-core/build/IUniswapV2Factory.json");
const hre = require("hardhat");
let provider;
provider = new hre.ethers.providers.WebSocketProvider(
`wss://eth-goerli.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`
);
console.log("uFactory");
const uFactory = new hre.ethers.Contract(
// the address is 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
process.env.UNISWAP_FACTORY_ADDRESS,
IUniswapV2Factory.abi,
provider
);
module.exports = { provider, uFactory };
Is my code wrong?
I looked up the uniswap docs and i followed it and checked that the pair with the 2 addresses existed but it kept returning me 0x0000000000000000000000000000000000000000.

Related

Solidity - ecrecover function is returning an incorrect address than the expected one

I am trying to sign a message and verify it later. But while verifying,
the returned address from the ecrecover is very odd and not matching with any of the accounts I am using.
Solidity Code:-
library CryptoSuite { function splitSignature(bytes memory sig) internal pure returns(uint8 v, bytes32 r, bytes32 s) {
require(sig.length == 65);
assembly{
// first 32bytes
r := mload(add(sig, 32))
// next 32bytes
s := mload(add(sig, 64))
// last 32bytes
v := byte(0, mload(add(sig,96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) {
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s); //recovers the value of the person who signed this
}
}
function isMatchingSignature(bytes32 message, uint id, address issuer) public view returns (address) {
Certificate memory cert = certificates[id];
require(cert.issuer.id == issuer);
address recoveredSigner = CryptoSuite.recoverSigner(message, cert.signature);
return recoveredSigner == cert.issuer.id;
}
Java Script Code
it('should verify that the certificate signature matches the issuer', async () => {
const {inspector, manufacturerA} = this.defaultEntities;
const vaccineBatchId = 0;
const message = `Inspector(${inspector.id}) has certified vaccine batch #${vaccineBatchId} for Manufacturer (${manufacturerA.id}).`;
//const message = `Inspector has certified vaccine batch for Manufacturer (${manufacturerA.id}).`;
const certificate = await this.coldChainInstance.certificates.call(0);
console.log(certificate);
const signerMatches = await this.coldChainInstance.isMatchingSignature(
this.web3.utils.keccak256(message),
certificate.id,
inspector.id,
{ from : this.owner }
);
console.log(signerMatches);
assert.equal(signerMatches, true, "can't verify");
});

CryptoJS Progressive Ciphering

Is there any other tutorial or documentation on how to do Progressive Ciphering with CryptoJS?
Their own Documentation about it is kinda lacking of Information's
These are the Information's I found:
https://cryptojs.gitbook.io/docs/#progressive-ciphering
https://github.com/brix/crypto-js/blob/develop/docs/QuickStartGuide.wiki
Here's my solution:
export function calcSha1 (file: File): Promise<string> {
const reader = new FileReader()
const promise = new Promise<string>(
(resolve) => {
reader.onloadend = (evt: ProgressEvent<FileReader>) => {
const sha1Hash = CryptoJS.algo.SHA1.create()
let currentPosition = 0
const chunkSize = 10 * 1024 * 1024 // 10MB
while (currentPosition < file.size) {
let endPosition = currentPosition + chunkSize
if (endPosition > file.size) {
endPosition = file.size
}
const blob = evt.target?.result?.slice(currentPosition, endPosition)
const wordArray = CryptoJS.lib.WordArray.create(blob)
sha1Hash.update(wordArray)
currentPosition += chunkSize
}
const result = sha1Hash.finalize()
resolve(result.toString())
}
}
)
reader.readAsArrayBuffer(file)
return promise
}

How to send byte data over gRPC with C/C++?

So I'm using gRPC to store data in a key-value store.
The protos look like this:
syntax = "proto3";
package keyvaluestore;
service KeyValueStore {
rpc AddUser(Credentials) returns (Response) {}
rpc Get(Request) returns (Response) {}
rpc Put(Request) returns (Response) {}
rpc Cput(Request) returns (Response) {}
rpc Delete(Request) returns (Response) {}
}
message Credentials {
string user = 1;
string passwd = 2;
}
message Request {
string user = 1;
string key = 2;
bytes val = 3;
bytes val2 = 4;
string addr = 5;
string command = 6;
}
message Response {
bytes val = 1;
uint32 nbytes = 2;
string message = 3;
}
Right now, the issue is that if we send over say, an image as byte data which can include the null byte, then when the server receives it in the Request object, it treats it as a string; when it does this it only reads it up the the first null byte.
How we pack the Request object on the client side:
bool KeyValueStoreClient::Put(const string& user, const string& key, const char* val) {
Request req;
req.set_user(user);
req.set_key(key);
req.set_val(val);
ClientContext ctx;
Response res;
Status status = stub_->Put(&ctx, req, &res);
}
Server receives req->val() as a string instead of char*:
Status KeyValueStoreServiceImpl::Put(ServerContext* ctx, const Request* req, Response* res) {
// req->val() is a string
}
In your method Put the val argument is a const char*, not a std::string.
Protobuf documentation for C++ generated code (i.e., the interface to your messages) says that when setting a value using a const char* (the void set_foo(const char* value) overload) it uses the first \0 as a terminator.
Tell it the size explicitly by using the void set_foo(const char* value, int size) overload.

How to convert TRON address to different format

I have an issue while deploying contract in TRON network, where I am required to specify address in format that starts with 4.. or when I receive transactions history (here the api respond with 4.. addresses as well).
Therefore I have a question:
How to convert TRON address started with TLAXtqju7GKyqoP... to 419b6e043089843624c36f1e3b1e8572d189cbe170 and vice versa?
How to convert TRON address started with TLAXtqju7GKyqoP... to 419b6e043089843624c36f1e3b1e8572d189cbe170 and vice versa?
const TronWeb = require('tronweb');
const tronWeb = new TronWeb(
'http://127.0.0.1:9090',
'http://127.0.0.1:9090',
'http://127.0.0.1:9090',
'd6fbbf6eecffdb32172e391363a401f89617acb9dd01897b9fa180830a8a46b2',
);
Once you have the tronWeb object, then you can convert the addresses vice-versa by using tronWeb's address utility
For Example:
const addressInHexFormat = '414450cf8c8b6a8229b7f628e36b3a658e84441b6f';
const addressInBase58 = tronWeb.address.fromHex(addressInHexFormat);
> addressInBase58 = 'TGCRkw1Vq759FBCrwxkZGgqZbRX1WkBHSu'
const addressInHex = tronWeb.address.toHex(addressInBase58);
> addressInHex = '414450cf8c8b6a8229b7f628e36b3a658e84441b6f'
Note
The above tronWeb object is created by using Tron's Quickstart Docker container. In this way the addresses can be converted vice-versa.
You just should decode your base58Address from Base58. In result you will obtain addresschecksum, so you should remove last 4 bytes from result and obtain desired address.
address = 41||sha3[12,32): 415a523b449890854c8fc460ab602df9f31fe4293f
sha256_0 = sha256(address): 06672d677b33045c16d53dbfb1abda1902125cb3a7519dc2a6c202e3d38d3322
sha256_1 = sha256(sha256_0): 9b07d5619882ac91dbe59910499b6948eb3019fafc4f5d05d9ed589bb932a1b4
checkSum = sha256_1[0, 4): 9b07d561
addchecksum = address || checkSum: 415a523b449890854c8fc460ab602df9f31fe4293f9b07d561
base58Address = Base58(addchecksum): TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW
The address format is well explained in the relevant TRON documentation.
In Java code (based on wallet-cli):
public String tronHex(String base58) {
byte[] decoded = decode58(base58);
String hexString = decoded == null ? "" : org.spongycastle.util.encoders.Hex.toHexString(decoded);
return hexString;
}
private byte[] decode58(String input) {
byte[] decodeCheck = Base58.decode(input);
if (decodeCheck.length <= 4) {
return null;
}
byte[] decodeData = new byte[decodeCheck.length - 4];
System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length);
byte[] hash0 = Sha256Hash.hash(decodeData);
byte[] hash1 = Sha256Hash.hash(hash0);
if (hash1[0] == decodeCheck[decodeData.length] &&
hash1[1] == decodeCheck[decodeData.length + 1] &&
hash1[2] == decodeCheck[decodeData.length + 2] &&
hash1[3] == decodeCheck[decodeData.length + 3]) {
return decodeData;
}
return null;
}
And the other way around:
public String hexStringTobBase58(String hexString) {
hexString = adjustHex(hexString);
byte[] decodedHex = hexString == null? new byte[0] : org.spongycastle.util.encoders.Hex.decode(hexString);
String base58 = encode58(decodedHex);
return base58;
}
private String adjustHex(String hexString) {
if (hexString.startsWith("0x")) {
hexString = "41" + hexString.substring(2);
}
if (hexString.length() % 2 == 1) {
hexString = "0" + hexString;
}
return hexString;
}
private String encode58(byte[] input) {
byte[] hash0 = Sha256Hash.hash(input);
byte[] hash1 = Sha256Hash.hash(hash0);
byte[] inputCheck = new byte[input.length + 4];
System.arraycopy(input, 0, inputCheck, 0, input.length);
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
return Base58.encode(inputCheck);
}
Find class Base58 here, class Sha256Hash here and the required dependency to Spongy Castle here.
C# example:
public static string GetHex(this String str)
{
var sb = new StringBuilder();
var bytes = Base58.Bitcoin.Decode(str); // nuget https://www.nuget.org/packages/SimpleBase/
for (int i = 0; i < bytes.Length - 4; i++)
{
var t = bytes[i];
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}

Asmx Web Service Basic Authentication in Asp.net Core Web Application

I created a Asmx Web service and host it in IIS, in MVC, I could call it from below code:
BasicWebService.WebService1 client = new BasicWebService.WebService1();
client.Credentials = new System.Net.NetworkCredential("user", "pwd","domain");
string result = client.HelloWorld();
But, I failed to mark it work under Asp.net Core.
Here is the code what I have tried.
ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient(ServiceReference1.WebService1SoapClient.EndpointConfiguration.WebService1Soap);
client.ClientCredentials.UserName.UserName = "xx";
client.ClientCredentials.UserName.Password = "xx";
//string USER = "xx";
//string PASSWORD = "xx";
//string Domain = "xx";
//NetworkCredential netCredential = new NetworkCredential(USER, PASSWORD,Domain);
////client.Credentials = new System.Net.NetworkCredential("xx", "xx", "xx");
//client.ClientCredentials.Windows.ClientCredential = netCredential;// netCredential.GetCredential(new Uri("http://localhost/WCFBasicSecurity/WebService1.asmx"), "Basic");
ServiceReference1.HelloWorldResponse result =client.HelloWorldAsync().Result;
Got solution from GitHub, thanks for the suggestion from hongdai. Modify the generated reference.cs with below:
public WebService1SoapClient(EndpointConfiguration endpointConfiguration) :
base(WebService1SoapClient.GetBindingForEndpoint(endpointConfiguration), WebService1SoapClient.GetEndpointAddress(endpointConfiguration))
{
this.Endpoint.Name = endpointConfiguration.ToString();
this.ChannelFactory.Credentials.UserName.UserName = "xx\xx";
this.ChannelFactory.Credentials.UserName.Password = "xxxx";
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
//Transport Security
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport);
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
return result;
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
System.ServiceModel.Channels.CustomBinding result = new System.ServiceModel.Channels.CustomBinding();
System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement();
textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None);
result.Elements.Add(textBindingElement);
System.ServiceModel.Channels.HttpTransportBindingElement httpBindingElement = new System.ServiceModel.Channels.HttpTransportBindingElement();
httpBindingElement.AllowCookies = true;
httpBindingElement.MaxBufferSize = int.MaxValue;
httpBindingElement.MaxReceivedMessageSize = int.MaxValue;
result.Elements.Add(httpBindingElement);
return result;
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
return new System.ServiceModel.EndpointAddress("https://localhost/WCFBasicSecurity/WebService1.asmx");
//return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
Reference:https://github.com/dotnet/wcf/issues/1812