How to understand the initialization of a contract as an interface in Solidity - interface

I am learning SmartContract development on Ethereum with Solidity and I would highly appreciate your help to understand this one basic thing:
KittyInterface as a contract has no parameters, just one function:
contract KittyInterface {
function getKitty(uint256 _id) external view returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
);
}
But then it gets initialized like this, giving one parameter (ckAddress).
address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
KittyInterface kittyContract = KittyInterface(ckAddress);
So my question is:
What happens when we call KittyInterface(ckAddress); when the contract has no parameters to take, but only a function? Where does the "ckAddress" go?
Is the address taken to write/connect to the blockchain?
Or is it given to the first function of the contract?
It works, there are no errors, but I struggle to understand it.
It is part of the Cryptozombie-Course, so I cannot debug it.
Can anybody please help me understand?

Sometimes the contract code is not available to us. The contract is
already deployed on a network and only its address is available to us. The only way to use such a contract is through low-level address-provided functions ( send, transfer,
staticcall , call , and delegatecall ). This is because we do not have the
definition of that contract and we cannot use the new keyword for it. If such a contract
implements an interface and that interface definition is available to us, we will be able to use it to reference the target contract through its address itself. with this
KittyInterface(ckAddress)
you are telling the compiler which functions are available in this deployed contract ckAddress so you can call those functions.
Interface might not contain all the functions defined in the contract. Note that only functions defined within the interface are callable using this method: KittyInterface(ckAddress)

The following part is not actual initiating, nor function calling.
KittyInterface kittyContract = KittyInterface(ckAddress);
It is just converting ckAddress to callable smart contract, when you know the type-signature of the function you want to call.
This is called dependency-injection mechanism.
More info can be found in the link.

Related

How to make a function can be called only by specific class in swift?

I have two frameworks A and B. I have a public function inside B called getMap() which returns a copy of a map(which is a private variable in B). So I call getMap() in A to get this value. This is fine because it's a copy so whatever I do to the returned value it doesn't affect the actual variable inside B.
Now I did some processing to this value, I need to pass it back to B. Here is the problem: In order to pass it back, it has to be a public function, but I don't want other frameworks or application to call this function because only A should be making changes to this map value.
Is there any way to specify in B that only if A is calling the function then the value should be set, otherwise ignoring anyone else who is using this function? I've heard you can use delegate/protocol to achieve this but I don't understand.
Yes you should be able to achieve this using delegate/protocols. The protocol will still have to be public which means any class could implement the protocol but the simple solution to this would be to just not implement it any other class.
You would create the the protocol in framework B like this:
protocol FrameworkBDelegate {
func sendMapChanges(map: Map)
}
Then call the delegate method when you're ready send it back to the other framework:
func changeMap() {
var map = frameworkA.getMap()
// Do stuff to map...
delegate.sendMapChanges(map: map)
}
I don't want to write a whole tutorial on how implement delegation so here's a good one from Swift by Sundell: here
Let me know if you need any help.
This is not possible out of the box.
If you create a Framework than you have to decide if a method/class needs to be public or not. If a method is public than there isn't an out of the box solution which delivers a bullet proof solution which solves your requirement. In the end the method is public to ALL consumers of Framework B.
So, you will end up implementing some kind of access control mechanisms within Framework B. This means that Framework A needs to authenticate itself in some way (access code etc.).
The delegate pattern will not solve your issue as well, hence it also has to be public, so that Framework A can use it. However, if it's public than all consumers of Framework B can use it.

Interfaces and contracts in ethereum

I've seen this asked before but I still need some clarification on where exactly the functions declared in an interface are fully defined? I understand the interface lays out and explains functions that another contract (contractB) can use but is the interface just a convenience and not a necessity for contractB to use those functions? In my mind I'm confusing delegateCall with interfaces. If we want to call functions from other contracts, why use interfaces rather than delegateCall? If the contract address pointed to by the interface has a function defined but I do not outline it in the interface, can I still use it in contractB?
For example, below I know I can use transfer function in crowdsale but where is transfer? Let's say contract A has function makepovertyhistory() defined but I do not mention it in the interface token...can I still use it in the crowdsale contract?
If I redefine the transfer function inside the interface, does it overwrite the transfer function defined at the address instantiated within crowd sale contract? I'm not sure if I'm thinking about this all correctly so thought I would ask more detailed questions in case anyone else found the generic answers still to general to build a visual of what's going on.
It might be helpful to also distinguish why we would use an interface instead of inheriting a contract directly into my currently being created contract
interface token {
function transfer(address receiver, uint amount);
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
....
....
..
Interfaces in Solidity are really no different than interfaces in any OOP. They allow you to code towards a stub without knowing the underlying implementation. If a new version of a contract that implements the interface is needed, your contract that uses it doesn't need to change.
This allows you to address one of the common problems in smart contracts: upgradable contracts. By using an interface, you can deploy a new version of a contract, then update any existing contracts with the new address.
Simplified example (obviously, this would not pass basic security checks, but you get the idea).
interface I {
someMethod();
}
contract C {
I i;
C(address _addr) {
i = I(_addr);
}
doSomething() {
i.someMethod();
}
upgrade(address _newAddr) {
i = _newAddr;
}
}
Providing this type of separation (and using libraries) makes upgrading contracts much easier and cheaper.
For example, below I know I can use transfer function in crowdsale but
where is transfer? Let's say contract A has function
makepovertyhistory() defined but I do not mention it in the interface
token...can I still use it in the crowdsale contract?
No, it needs to be imported or defined somewhere.
If I redefine the transfer function inside the interface, does it
overwrite the transfer function defined at the address instantiated
within crowd sale contract?
It depends on how you're calling the transfer function. If you're executing it on the address of a deployed contract, then you are using that deployed contract's implementation.
A more in-depth example can be found in this blog post.

Preconditions and postconditions in interfaces and abstract methods

I'm trying to implement my own programming language, and i'm currently doing lexing and parsing. I'm nearly done and want to add native support for class invariants, preconditions and postconditions.
public withdraw (d64 amount) : this {
require amount > 0;
require this.balance - amount > this.overdraft;
# method code
d64 newBalance = this.balance - amount;
ensure this.balance == newBalance;
}
You would also be able to define class invariance at the top of the class.
class BankAccount {
invariant this.balance > this.overdraft;
# class body
}
These are my questions:
Would it make sense to include class invariance in abstract classes, or interfaces.
Would it make sense to include preconditions in abstract methods and interface methods.
Would it make sense to include postconditions in abstract methods, or interface methods.
Thinking about it myself, i don't think it makes sense to include invariance or postconditions in interfaces, but i don't really see a problem with preconditions.
It would be possible to include pre- and postconditions in abstract and interface methods like below.
public interface BankAccount {
public withdraw (d64 amount) : this {
require amount > 0;
require this.balance - amount > this.overdraft;
# no other statements (implementation)
d64 newBalance = this.balance - amount;
ensure this.balance == newBalance;
}
}
It really depends on whether your interface is stateful or stateless. It can be perfectly fine to include pre and/or post conditions for interface methods. In fact, we do this all the time. Any time you create a piece of javadoc (or any other tool), you are creating a contract. Otherwise, how could you test anything? It's important to realize that test-driven-development and design-by-contract have much in common. Defining a contract is essential to proper tdd - you first design an interface and create an informal contract for it (using human-readable language). Then, you write a test to ensure contract is satisfied. If we follow tdd classicists (https://www.thoughtworks.com/insights/blog/mockists-are-dead-long-live-classicists), we always write tests against contracts.
Now, to be more specific. If interface is stateful, we can easily express its invariants according to other methods. Let's take a java List interface as an example:
If you read the javadoc carefully, you will see there are a lot of invariants. For instance, the add method has the following contract:
Preconditions: element cannot be null (if list doesn't support it -
it's a design smell btw in my opinion, but let's set it aside for
now)
Postconditions: ordering is preserved, i.e. the ordering of other
elements cannot be changed
Since List interface is definitely stateful, we can reason about the state of the list using query method, like get, sublist etc. Therefore, you can express all the invariants based on interface's methods.
In case of an interface which is stateless, such as Calculator, we also define a contract, but its invariants do not include any state. So, for example, the sum method can have the following contract:
int sum(int a, int b)
Preconditions: a and b are integers (which is automatically guaranteed by static type checking in Java)
Postconditions: the result is an integer (again - type safety) which is equal to a + b
Our Calculator is a stateless interface, therefore we don't include any state in our invariants.
Now, let's get back to your BankAccount example:
The way you describe it, BankAccount is definitely a stateful interface. In fact, it's a model example of what we call an Entity (in terms of domain-driven-design). Therefore, BankAccount has it's lifecycle, it's state and can (and will) change during its lifetime. Therefore, it's perfectly fine to express your contracts based on the state methods of your class. All you need to do, is to move your amount, balance and overdraft to the top of the interface, either as properties (if your language supports it) or methods - it doesn't really matter. What's important is that amount, balance and overdraft are now part of your interface, and form the ubiquitous language of your interface. These methods/properties are integral part of your entire BankAccount interface - which means, they can be used as part of your interface's contract.
Some time ago I've implemented a very simple prototype of Java contracts, implemented as set of annotations supported by Aspect Oriented Programming. I tried to achieve similar goal to yours - to integrate contracts with language and make them more formal. It was just a very simple prototype, but I think it expressed the idea quite well. If you are interested - I should probably upload it to the github soon (I've been using bitbucket for most of the time so far).

What is a pointer language?

I am in the process of trying to gain a clear understanding of what a callback is. I came across this post: what-is-a-callback-function. The user 8bitjunkie who answered the question mentioned callbacks are named such because of how they are used in pointer languages. My initial assumption based on the name led me to think that a pointer language is a language where pointers can be directly manipulated. So I would like to know if c++ is a pointer language, and if my initial assumption was incorrect; what a pointer language is. As far as I can tell it does not seem to be a typical language agnostic term. If it is, it is covered by results relating to the usage of pointers.
Callbacks are not unique to languages that allow direct manipulation of pointers - but that is what a "Pointer Language" is. I will focus my answer on what callbacks are because that seems to be your main confusion.
Callbacks are available in Java, Python, JavaScript, and many other languages that hide pointers from you.
A callback is just a function that will be executed at the end of another function. Generally this is useful for asynchronous tasks, because it allows you to respond to the task in a specific way without blocking.
For an example I will use Java - a language with managed memory no direct access to pointers. The more native way to implement callbacks is with function pointers, and I think that is what your article meant about "Pointer Languages." But I'd rather show you what a callback is and how to use them without pointers in one fell swoop, so Java it is.
In this example we will have an interface defined like this.
public interface CallBack {
public void onFinished(boolean success);
}
This callback interface allows us to declare an object with a predefined method that will respond to either success or failure. We can then define a Runnable class like this.
public class CBObject implements Runnable {
private CallBack myCallback;
public CBObject(CallBack myCallback) {
this.myCallback = myCallback;
}
public void run() {
boolean success = false;
// do some stuff, set success = true if it works
myCallback.onFinished(success); // this calls the callback
}
}
Then if we want to use this callback we will do something like this.
public void doSomethingAsynchronous(CallBack callback) {
CBObject cb = new CBObject(callback);
Thread task = new Thread(cb);
task.start();
}
This will run this task asynchronously but allow the user to react to its success or failure.
I hope this helps!

GWT / JSNI - "DataCloneError - An object could not be cloned" - how do I debug?

I am attempting to call out to parallels.js via JSNI. Parallels provides a nice API around web workers, and I wrote some lightweight wrapper code which provides a more convenient interface to workers from GWT than Elemental. However I'm getting an error which has me stumped:
com.google.gwt.core.client.JavaScriptException: (DataCloneError) #io.mywrapper.workers.Parallel::runParallel([Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;Lcom/google/gwt/core/client/JavaScriptObject;)([Java object: [Ljava.lang.String;#1922352522, JavaScript object(3006), JavaScript object(3008)]): An object could not be cloned.
This comes from, in hosted mode:
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:299) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107) at io.mywrapper.workers.Parallel.runParallel(Parallel.java)
Here's my code:
Example client call to create a worker:
Workers.spawnWorker(new String[]{"hello"}, new Worker() {
#Override
public String[] work(String[] data) {
return data;
}
#Override
public void done(String[] data) {
int i = data.length;
}
});
The API that provides a general interface:
public class Workers {
public static void spawnWorker(String[] data, Worker worker) {
Parallel.runParallel(data, workFunction(worker), callbackFunction(worker));
}
/**
* Create a reference to the work function.
*/
public static native JavaScriptObject workFunction(Worker worker) /*-{
return worker == null ? null : $entry(function(x) {
worker.#io.mywrapper.workers.Worker::work([Ljava/lang/String;)(x);
});
}-*/;
/**
* Create a reference to the done function.
*/
public static native JavaScriptObject callbackFunction(Worker worker) /*-{
return worker == null ? null : $entry(function(x) {
worker.#io.mywrapper.workers.Worker::done([Ljava/lang/String;)(x);
});
}-*/;
}
Worker:
public interface Worker extends Serializable {
/**
* Called to perform the work.
* #param data
* #return
*/
public String[] work(String[] data);
/**
* Called with the result of the work.
* #param data
*/
public void done(String[] data);
}
And finally the Parallels wrapper:
public class Parallel {
/**
* #param data Data to be passed to the function
* #param work Function to perform the work, given the data
* #param callback Function to be called with result
* #return
*/
public static native void runParallel(String[] data, JavaScriptObject work, JavaScriptObject callback) /*-{
var p = new $wnd.Parallel(data);
p.spawn(work).then(callback);
}-*/;
}
What's causing this?
The JSNI docs say, regarding arrays:
opaque value that can only be passed back into Java code
This is quite terse, but ultimately my arrays are passed back into Java code, so I assume these are OK.
EDIT - ok, bad assumption. The arrays, despite only ostensibly being passed back to Java code, are causing the error (which is strange, because there's very little googleability on DataCloneError.) Changing them to String works; however, String isn't sufficient for my needs here. Looks like objects face the same kinds of issues as arrays do; I saw Thomas' reference to JSArrayUtils in another StackOverflow thread, but I can't figure out how to call it with an array of strings (it wants an array of JavaScriptObjects as input for non-primitive types, which does me no good.) Is there a neat way out of this?
EDIT 2 - Changed to use JSArrayString wherever I was using String[]. New issue; no stacktrace this time, but in the console I get the error: Uncaught ReferenceError: __gwt_makeJavaInvoke is not defined. When I click on the url to the generated script in developer tools, I get this snippet:
self.onmessage = function(e) {self.postMessage((function (){
try {
return __gwt_makeJavaInvoke(3)(null, 65626, jsFunction, this, arguments);
}
catch (e) {
throw e;
}
})(e.data))}
I see that _gwt_makeJavaInvoke is part of the JSNI class; so why would it not be found?
You can find working example of GWT and WebWorkers here: https://github.com/tomekziel/gwtwwlinker/
This is a preliminary work, but using this pattern I was able to pass GWT objects to and from webworker using serialization provided by AutoBeanFactory.
If you never use dev mode it is currently safe to pretend that a Java String[] is a JS array with strings in it. This will break in dev mode since arrays have to be usable in Java and Strings are treated specially, and may break in the future if the compiler optimizes arrays differently.
Cases where this could go wrong in the future:
The semantics of Java arrays and JavaScript arrays are different - Java arrays cannot be resized, and are initialized with specific values based on the component type (the data in the array). Since you are writing Java code, the compiler could conceivable make assumptions based on details about how you create and use that array that could be broken by JS code that doesn't know to never modify the array.
Some arrays of primitive types could be optimized into TypedArrays in JavaScript, more closely following Java semantics in terms of resizing and Java behavior in terms of allocation. This would be a performance boost as well, but could break any use of int[], double[], etc.
Instead, you should copy your data into a JsArrayString, or just use the js array to hold the data rather than going back and forth, depending on your use case. The various JsArray types can be resized and already exist as JavaScript objects that outside JS can understand and work with.
Reply to EDIT 2:
At a guess, the parallel.js script is trying to run your code from another scope such a in the webworker (that's the point of the code, right) where your GWT code isn't present. As such, it can't call the makeJavaInvoke which is the bridge back into dev mode (would be a different failure with compiled JS). According to http://adambom.github.io/parallel.js/ there are specific requirements that a passed callback must meet to be passed in to spawn and perhaps then - your anonymous functions definitely do not meet them, and it may not be possible to maintain java semantics.
Before I get much deeper, check out this answer I did a while ago addressing the basic issues with webworkers and gwt/java: https://stackoverflow.com/a/11376059/860630
As noted there, WebWorkers are effectively new processes, with no shared code or shared state with the original process. The Parallel.js code attempts to paper over this with a little bit of trickery - shared state is only available in the form of the contents passed in to the original Parallel constructor, but you are attempting to pass in instances of 'java' objects and calling methods on them. Those Java instances come with their own state, and potentially can link back to the rest of the Java app by fields in the Worker instance. If I were implementing Worker and doing something that referenced other data than what was passed in, then I would be seeing further bizarre failures.
So the functions you pass in must be completely standalone - they must not refer to external code in any way, since then the function can't be passed off to the webworker, or to several webworkers, each unaware of each other's existence. See https://github.com/adambom/parallel.js/issues/32 for example:
That's not possible since it would
require a shared state across workers
require us to transmit all scope variables (I don't think there's even a possibility to read the available scopes)
The only thing which might be possible would be cache variables, but these can already be defined in the function itself with spawn() and don't make any sense in map (because there's no shared state).
Without being actually familiar with how parallel.js is implemented (all of this answer so far is reading the docs and a quick google search for "parallel.js shared state", plus having experiemented with WebWorkers for a day or so and deciding that my present problem wasn't yet worth the bother), I would guess that then is unrestricted, and you can you pass it whatever you like, but spawn, map, and reduce must be written in such a way that their JS can be passed off to the new JS process and completely stand alone there.
This may be possible from your normal Java code when compiled, provided you have just one implementation of Worker and that impl never uses state other than what is directly passed in. In that case the compiler should rewrite your methods to be static so that they are safe to use in this context. However, that doesn't make for a very useful library, as it seems you are trying to achieve. With that in mind, you could keep your worker code in JSNI to ensure that you follow the parallel.js rules.
Finally, and against the normal GWT rules, avoid $entry for calls you expect to happen in other contexts, since those workers have no access to the normal exception handling and scheduling that $entry enables.
(and finally finally, this is probably still possible if you are very careful at writing Worker implementations and write a Generator that invokes each worker implementation in very specific ways to make sure that com.google.gwt.dev.jjs.impl.MakeCallsStatic and com.google.gwt.dev.jjs.impl.Pruner can correctly act to knock out the this in those instance methods once they've been rewritten as JS functions. I think the cleanest way to do this is to emit the JSNI in the generator itself, call a static method written in real Java, and from that static method call the specific instance method that does the heavy lifting for spawn, etc.)