Check if a contract implements IERC165 - interface

I have a list of contracts, some may or may not implement IERC165. How can I check if a contract implements ERC165?
IERC165(proposal.targets[i]).supportsInterface(typeof(IMultiProposalDependent).interfaceId

as of 0.6 try catch exists, so I just try to call the function I'm expecting.
try IMultiProposalDependent(proposal.targets[i]).updateResults(proposal.voteInfo) {
} catch {
}
Probably wastes a ton of gas but I don't have a better solution atm

Related

Refactor catch statements

We have many try-catch blocks in our code handling the exceptions of the api calls. Since most of the catch blocks are identical we want to refactor them and only them (because the try blocks should stay in the place they are). How is this possible in Flutter?
Example code:
try {
_userData = apiService.call("user_data");
} on ResourceNotFoundException {
handleResourceNotFoundException();
} on NetworkException {
handleNetworkException();
}
The best solution I found is using a general catch, fit everything into a handleException function, and in there rethrow the exception again.
try {
_userData = apiService.call("user_data");
} on catch (e) {
handleException(e);
}
void handleException(e) {
try {
throw e;
} on ResourceNotFoundException {
handleResourceNotFoundException();
} on NetworkException {
handleNetworkException();
}
}
This way it is possible to reuse the exception handling logic and also extend it.
You should add some abstraction to your API call, meaning you should add a function that takes in the API call you are trying to call as a parameter and surround it with a try-catch block and handle all your exceptions there.
This way you have separated your API calls logic from handling exceptions.

Flutter & Dart: How to check/know which class has called a function?

I am trying to know which class has called a specific function. I've been looking through the docs for this, but without success. I already know how to get the name of a class, but that is something different of what I'm looking for. I found already something related for java but for dart I haven't. Maybe I'm missing something.
Let's say for example that I have a print function like so:
class A {
void printSomethingAndTellWhereYouDidIt() {
// Here I would also include the class where this function is
// being called. For instance:
print('you called the function at: ...');
//This dot-dot-dot is where maybe should go what I'm looking for.
}
}
class B {
A a = A();
void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}
The output should be something like:
you called the function at: B
Please let me know if there are ways to achieve this. The idea behind is to then use this with a logger, for instance the logging package. Thank you in advance.
You can use StackTrace.current to obtain a stack trace at any time, which is the object that's printed when an exception occurs. This contains the line numbers of the chain of invocations leading up to the call, which should provide the information you need.
class A {
void printSomethingAndTellWhereYouDidIt() {
print(StackTrace.current);
}
}
class B {
A a = A();
void test() {
a.printSomethingAndTellWhereYouDidIt();
}
}
If you are doing this for debugging purposes, you can also set a breakpoint in printSomethingAndTellWhereYouDidIt to check where it was called from.

PromiseKit, how to await a finalized promise?

coming from the JS world I'm having a bit of problem wrapping my head around promise kit flavor of promises, I need a bit of help with the following.
Assume I have a function that returns a promise, say an api call, on some super class I await for that promise, then do some other action (potentially another network call), on that parent call I also have a catch block in order to set some error flags for example, so in the end I have something close to this:
func apiCall() -> Promise<Void> {
return Promise { seal in
// some network code at some point:
seal.fulfill(())
}
}
// in another class/object
func doApiCall() -> ? { // catch forces to return PMKFinalizer
return apiCall()
.done {
// do something funky here
}
.catch {
print("Could not do first request"
}
}
now I'm trying to write some unit tests for this functionality, so the response is mocked and I know it will not fail, I just need to await so I can verify the internal state of my class:
// on my test file
doApiCall().done {
// test my code, but I get an error because I cannot pipe a promise that already has a `.catch`
}
How would one go about solving this problem? I could use finally to chain the PMKFinalizer but that feels wrong
Another tangential question would be, is it possible to re catch the error on a higher level, let's say a UI component so it can hold some temporary error state? as far as I see I did not see a way to achieve this.
Many thanks 🙏

How to get a CycAccess object?

There's a lisp function in ResearchCyc called random-assertion. I want to call that from some Java code. I'm using the Cyc Core API Suite v1.0.0-rc5 (from http://dev.cyc.com), but I don't see any way to call underlying Lisp code.
In the old OpenCyc API there was an object called CycAccess that you could use for this, but I can't figure out how to get one. If I could find it, I'd call this
access.converseObject("(random-assertion)");
At least in ResearchCyc, this would retrieve a pseudo-random assertion from the Cyc knowledge base. Not sure if it would work in OpenCyc, but it might also work there.
Can someone explain how to call lisp-code like this through Cyc's java API?
(Disclaimer: I am one of the developers of the Cyc APIs...)
The reference implementation of the Core API Suite is the Core Client, which is based on the Base Client... which, in turn, is derived from the old OpenCyc API. So, it's absolutely possible to call arbitrary lisp (SubL) code on ResearchCyc, in several different ways...
First of all, there already is a method which wraps random-assertion:
try {
CycAccess access = CycAccessManager.getCurrentAccess();
CycAssertion cycAssertion = access.getLookupTool().getRandomAssertion();
} catch (SessionException ex) {
// Do something with the exception...
} catch (CycConnectionException connEx) {
// Do something else...
}
Speaking to the general case, though, you'll find that the syntax is fairly similar to the OpenCyc API:
try {
CycAccess access = CycAccessManager.getCurrentAccess();
Object cycAssertion = access.converse().converseObject("(random-assertion)");
} catch (SessionException ex) {
// Do something with the exception...
} catch (CycConnectionException connEx) {
// Do something else...
}
Or, if it's safe to assume that the result will be a CycObject:
...
CycAccess access = CycAccessManager.getCurrentAccess();
CycObject cycAssertion = access.converse().converseCycObject("(random-assertion)");
...
However, the Base Client adds a new way of encapsulating SubL functions, via the com.cyc.baseclient.subl.SublFunction interface. The SublFunction interface itself is pretty minimal, but there are a number of classes under com.cyc.baseclient.subl.subtypes which provide implementations for you to extend. For example, if you're calling a no-arg function and expect back a CycObject, you could extend SublCycObjectNoArgFunction like so:
public static final SublCycObjectNoArgFunction RANDOM_ASSERTION_FUNCTION =
new SublCycObjectNoArgFunction("random-assertion");
...
try {
CycAccess access = CycAccessManager.getCurrentAccess();
CycObject cycAssertion = RANDOM_ASSERTION_FUNCTION.eval(access);
} catch (SessionException ex) {
// Do something with the exception...
} catch (CycConnectionException connEx) {
// Do something else...
}
(For other examples of this, see com.cyc.baseclient.subl.functions.* in the Base Client.)
This approach makes it fairly simple to define SubL functions as static fields without writing (or re-writing) much code. We expect the Core Client to gradually migrate towards this approach.
Lastly, you can use the implementation classes in the KB Client to convert your results to KBObjects. For example:
try {
CycAccess access = CycAccessManager.getCurrentAccess();
CycObject cycAssertion = RANDOM_ASSERTION_FUNCTION.eval(access);
// To convert to a com.cyc.kb.Assertion:
Assertion assertion = AssertionImpl.get(cycAssertion);
// Or, to convert to a more general KBObject:
KbObject kbObj = KbObjectImpl.get(cycAssertion);
} catch (SessionException ex) {
// Do something with the exception...
} catch (CycConnectionException connEx) {
// Do something else...
} catch (KbTypeException ex) {
// Potentially thrown by AssertionImpl#get() & KbObjectImpl#get()
} catch (CreateException ex) {
// Also potentially thrown by AssertionImpl#get() & KbObjectImpl#get()
}

Good way to repeat a test, inserting an extra action?

I like the way Catch has nested hierarchies of tests, and it works through the combinations. It feels more natural than the setup/teardown of xUnit frameworks.
I now have a set of tests. What I want to do, about halfway down is insert a load/save serialization test, and then repeat all the tests below that point, first without the load/save, then again using the data it loaded from the serialization process. I.e. to prove that the load/save was correct.
I cannot get my head around if Catch has anything that can help with this? If it was phpUnit, I would be thinking about a string of #depends tests, and use a #dataProvider with a boolean input. A bit ugly.
(If that does not make sense, let me know, and I'll try to work out a minimal example)
The issue here is that Catch is designed to descend a tree-like organisation of tests and it automatically discovers all of the leaf-nodes of the structure and calls back into the test cases with untested code paths until they're all tested. The leaf nodes (tests, sections) are meant to be independent.
It sounds like you want to test a repository - something that can persist some data and then load it back in.
To repeat the exact same tests in two different scenarios (before serialisation, after serialisation) you'd need to put the same tests into some common place and call into that place. You can still use the same Catch macros in a non-test-case function, as long as you call it from a test case.
One possible way to do this is:
struct TestFixture {
Data data;
Repository repository;
TestFixture() : data(), instance() { }
};
void fillUpData(Data& data) {
// ...
}
void isDataAsExpected(Data& data) {
// Verify that 'data' is what we expect it to be, whether we
// loaded it or filled it up manually
SECTION("Data has ...) {
REQUIRE(data...);
}
}
TEST_CASE_METHOD(TestFixture, "Test with raw data") {
fillUpData(data);
isDataAsExpected(data);
REQUIRE(repository.save(data));
}
TEST_CASE_METHOD(TestFixture, "Operate on serialised data") {
REQUIRE(repository.load(data));
isDataAsExpected(_data);
}
One possible alternative is to supply your own main and then use command-line arguments to control whether/not the data is first serialised.
There's a third way I can think of that uses a non-quite-ready-yet feature of Catch - Generators:
TEST_CASE("...") {
using Catch::Generators;
int iteration(GENERATE(values(0, 1)));
const bool doSave(iteration == 0);
const bool doLoad(iteration == 1);
Repository repository;
Data data;
if (doLoad) {
REQUIRE(repository.load(data));
} else {
// fill up data
}
REQUIRE(..data..test..);
if (doSave) {
REQUIRE(repository.save(data));
}
}
The advantage of this method is you can see the flow and the test runs twice (for the two values) but the major disadvantage is that Generators are incompatible with SECTIONs and BDD-style features.