Getting ERC1155 Wallet Balance Using Java Web3J - java

Since Web3J doesn't currently support ERC1155, is there a way to get the balance for a wallet? My guess is to use a function for this, but I can't seem to figure out how to get it to work.
Function function = new Function(
"balancedOf",
Arrays.asList(new Address(ethAddress), new Uint256(1)),
Arrays.asList(new org.web3j.abi.TypeReference<Bool>() {}));
String data = FunctionEncoder.encode(function);
Do I then create a transaction? Or do I use ethSendRawTransaction? balanceOf only has 2 input so I would expect to have to invoke it from a smartcontract, but I don't see a way to do it.

From reading the web3j docs, It seems that you can do the following:
Function function = new Function<>(
"functionName",
Arrays.asList(new Type(value)), // Solidity Types in smart contract functions
Arrays.asList(new TypeReference<Type>() {}, ...));
String encodedFunction = FunctionEncoder.encode(function)
org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
Transaction.createEthCallTransaction(<from>, contractAddress, encodedFunction),
DefaultBlockParameterName.LATEST)
.sendAsync().get();
List<Type> someTypes = FunctionReturnDecoder.decode(
response.getValue(), function.getOutputParameters());
The response object, from org.web3j.protocol.core.methods.response.EthCall does the JSON-RPC call "eth_call" which only retrieves data form the blockchain.
I believe this is the equivalent of doing in web3js the following:
let contract = new web3.eth.Contract(<ABI>, <Contract Address>);
const res = await contract.functionName(<params>);

Related

Web3j - How to read the contract without credentials?

I'm using Web3j to interact with my deployed smart contract.
I've deployed my contract onto the testnet and can interact with it, however using the generated wrapper code, it requires my wallet.
Web3j web3 = Web3j.build(new HttpService("https://testnet-endpoint-rpc.com"));
Credentials credentials = WalletUtils.loadCredentials(
"coolpassword1", "src\\main\\resources\\path-to-key-store.keystore"
);
FastRawTransactionManager txMananger = new FastRawTransactionManager(web3, credentials, 365);
MySmartContract contract = MySmartContract.load(
"0x73292b80f99ffdc4e9a908865ce1d35fde7b736f", //Address for smartcontract
web3,
txMananger,
new DefaultGasProvider()
);
//Reading from the contract
String contractName = contract.contractName(BigInteger.valueOf(0)).send();
How can I read from the contract without credentials?
I believe you can use the encodedFunctions to read without credentials but for write, you need the credentials.
Ex: balances is one of the methods in the contract with a single input of an address
Function function =
new Function("balances",
Arrays.asList(new org.web3j.abi.datatypes.Address(walletAddress)),
new ArrayList());
String encodedFunction = FunctionEncoder.encode(function);
org.web3j.protocol.core.methods.response.EthCall response = this.web3.ethCall(
Transaction.createEthCallTransaction(walletAddress, ContractAddress, encodedFunction),
DefaultBlockParameterName.LATEST)
.sendAsync().get();

How to map Json (from procedure) to Java object

I have the following SP (SQL server) that return a Json output.
BEGIN
SET #jsonOutput = (
SELECT
Program.Name AS ProgramName,
ProgramOwner.FirstName AS OwnerFirstName,
FROM ProgramOwner, Program
WHERE Program.Id = ProgramOwner.ProgramOwner2Program
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)
I would like to map the return Json output to a List of ProgramDto via modelMapper. Not sure hot to do that since the return values from call.execute is an Object.
Something like this:
SimpleJdbcCall call = new
SimpleJdbcCall(jdbcTemplate).withProcedureName(programProc).declareParameters(
new SqlOutParameter("jsonOutput", Types.VARCHAR));
Map<String,Object>out = call.execute(new MapSqlParameterSource());
if(out.size()>0) {
// Only to show what I am trying to do
Type rootType = new TypeToken<List<ProgramDto>>() {}.getType();
modelMapper.map(out.get("jsonOutput"),rootType );
}
Thank you
As I understood you are trying to get a list of object from
You can use Jackson api
Like this
say for example your json is in variable named jsonData, then you can get the object you need like below.
ObjectMapper mapper = new ObjectMapper();
List<Type> myList = Arrays.asList(mapper.readValue(jsonData, Type[].class));
You can also find more examples here

How to convert java object correctly for jsonPath matcher?

I'm writing mockMvc tests for my controller, and need to validate jsonPath return value.
Have tried differently with .is() and .value(), mapping, in any way i can imagine with no success
Loan loan = new Loan(
"0000-0000",
"OPEN",
LocalDate.now(),
LocalDate.now().plusDays(30),
new BigDecimal("500.0"),
new BigDecimal("50.0"),
new BigDecimal("550.0"),
new ArrayList<>()
);
Mockito.lenient()
.when(loanService.loans())
.thenReturn(Collections.singletonList(loan));
String json = MAPPER.writeValueAsString(loan);
mockMvc.perform(get("/api/loans"))
.andExpect(jsonPath("$.*").value(json));
Expected :{"id":"0000-0000","status":"OPEN","created":"2019-05-09","dueDate":"2019-06-08","principal":500.0,"interest":50.0,"total":550.0,"extensions":[]}
Actual :{id=0000-0000, status=OPEN, created=2019-05-09, dueDate=2019-06-08, principal=500.0, interest=50.0, total=550.0, extensions=[]}
So this is the closes i got, just dont get the types here.
In case you want to assert the complete responseBody as a json, you may use MockMvcResultMatchers's content method.
Just replace jsonPath("$.*").value(json) with content().json(json) as below
mockMvc.perform(get("/api/loans"))
.andExpect(content().json(json));

How to perform Amazon Cloud Search with .net code?

I am learning Amazon Cloud Search but I couldn't find any code in either C# or Java (though I am creating in C# but if I can get code in Java then I can try converting in C#).
This is just 1 code I found in C#: https://github.com/Sitefinity-SDK/amazon-cloud-search-sample/tree/master/SitefinityWebApp.
This is 1 method i found in this code:
public IResultSet Search(ISearchQuery query)
{
AmazonCloudSearchDomainConfig config = new AmazonCloudSearchDomainConfig();
config.ServiceURL = "http://search-index2-cdduimbipgk3rpnfgny6posyzy.eu-west-1.cloudsearch.amazonaws.com/";
AmazonCloudSearchDomainClient domainClient = new AmazonCloudSearchDomainClient("AKIAJ6MPIX37TLIXW7HQ", "DnrFrw9ZEr7g4Svh0rh6z+s3PxMaypl607eEUehQ", config);
SearchRequest searchRequest = new SearchRequest();
List<string> suggestions = new List<string>();
StringBuilder highlights = new StringBuilder();
highlights.Append("{\'");
if (query == null)
throw new ArgumentNullException("query");
foreach (var field in query.HighlightedFields)
{
if (highlights.Length > 2)
{
highlights.Append(", \'");
}
highlights.Append(field.ToUpperInvariant());
highlights.Append("\':{} ");
SuggestRequest suggestRequest = new SuggestRequest();
Suggester suggester = new Suggester();
suggester.SuggesterName = field.ToUpperInvariant() + "_suggester";
suggestRequest.Suggester = suggester.SuggesterName;
suggestRequest.Size = query.Take;
suggestRequest.Query = query.Text;
SuggestResponse suggestion = domainClient.Suggest(suggestRequest);
foreach (var suggest in suggestion.Suggest.Suggestions)
{
suggestions.Add(suggest.Suggestion);
}
}
highlights.Append("}");
if (query.Filter != null)
{
searchRequest.FilterQuery = this.BuildQueryFilter(query.Filter);
}
if (query.OrderBy != null)
{
searchRequest.Sort = string.Join(",", query.OrderBy);
}
if (query.Take > 0)
{
searchRequest.Size = query.Take;
}
if (query.Skip > 0)
{
searchRequest.Start = query.Skip;
}
searchRequest.Highlight = highlights.ToString();
searchRequest.Query = query.Text;
searchRequest.QueryParser = QueryParser.Simple;
var result = domainClient.Search(searchRequest).SearchResult;
//var result = domainClient.Search(searchRequest).SearchResult;
return new AmazonResultSet(result, suggestions);
}
I have already created domain in Amazon Cloud Search using AWS console and uploaded document using Amazon predefine configuration option that is movie Imdb json file provided by Amazon for demo.
But in this method I am not getting how to use this method, like if I want to search Director name then how do I pass in this method as because this method parameter is of type ISearchQuery?
I'd suggest using the official AWS CloudSearch .NET SDK. The library you were looking at seems fine (although I haven't look at it any detail) but the official version is more likely to expose new CloudSearch features as soon as they're released, will be supported if you need to talk to AWS support, etc, etc.
Specifically, take a look at the SearchRequest class -- all its params are strings so I think that obviates your question about ISearchQuery.
I wasn't able to find an example of a query in .NET but this shows someone uploading docs using the AWS .NET SDK. It's essentially the same procedure as querying: creating and configuring a Request object and passing it to the client.
EDIT:
Since you're still having a hard time, here's an example. Bear in mind that I am unfamiliar with C# and have not attempted to run or even compile this but I think it should at least be close to working. It's based off looking at the docs at http://docs.aws.amazon.com/sdkfornet/v3/apidocs/
// Configure the Client that you'll use to make search requests
string queryUrl = #"http://search-<domainname>-xxxxxxxxxxxxxxxxxxxxxxxxxx.us-east-1.cloudsearch.amazonaws.com";
AmazonCloudSearchDomainClient searchClient = new AmazonCloudSearchDomainClient(queryUrl);
// Configure a search request with your query
SearchRequest searchRequest = new SearchRequest();
searchRequest.Query = "potato";
// TODO Set your other params like parser, suggester, etc
// Submit your request via the client and get back a response containing search results
SearchResponse searchResponse = searchClient.Search(searchRequest);

Pass an array collection in JSON

I am trying to pass an array collection from flex page to my backend java.Here is the code,
private function getItems():void{
myObj = new Object();
myObj['dId']= dId.value.toString();
myObj['itmList']=JSON.encode(itmList);// trying to pass like this..
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"&parameter="+ escape(JSON.encode(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");
}
My itmList is an array collection, how can I pass it from JSon to Java controller? And how to get that in Java?
JSON.encode the itmList source array instead. (i.e. itmList.source is an array)
Then use HTTPService instead:
HTTPService AsyncToken and AsyncResponder example
Another option is to use JSON.stringify instead (Flash has had native JSON support since FP 11). Just make sure you remove the import com.adobe.serialization.json.JSON; from the top of your file.
myObj['itmList']=JSON.stringify(itmList);
Or, since you're encoding your whole data object,
myObj['itmList']=itmList.source;
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"&parameter="+ escape(JSON.stringify(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");

Categories