How to build a DApp on Nebulas (Part3)

In this article, we are going to present a new feature — the “accept” function— which will be released in Nebulas version 1.0.2.

What is “accept” for?

Prior to version 1.0.2, transfers to a contract could inconveniently only be done by calling a contract function. To make things easier, we provide a new default function, accept, which will be called when sending a binary transfer to the contract account. If there is no explicitly declared accept in the contract or another error occurs during execution, the transfer will fail.

How to use this function

By default, accept is not implemented. That is to say, you can not initiate any binary transfer to the contract account unless you explicitly implement it.

The simplest way to use this function is like this:

"use strict";
var AcceptableContract = function() {};
AcceptableContract.prototype = {
init: function(){},

// declares an empty accept
accept: function(){ // do nothing }
};
module.exports = AcceptableContract;

Assume the address of contract above is n1qsgj2C5zmYzS9TSkPTnp15bhCCocRPwno

Try to send a binary transfer transaction to the contract, then you would see a 1000000 WEI increase in the contract account.

// Request
curl -i -H 'Accept: application/json' -X POST http://localhost:8685/v1/admin/transaction -H 'Content-Type: application/json' -d '{
"from":"n1NZttPdrJCwHgFN3V6YnSDaD5g8UbVppoC",
"to":"n1qsgj2C5zmYzS9TSkPTnp15bhCCocRPwno", "value":"1000000",
"nonce":8,
"gasPrice":"1000000",
"gasLimit":"2000000"}'
// Result
{
"result": {"txhash":"412b7ec144a6d06f395c75296e808c51d0122cb27b4cfd386e31dafaf475bf6a","contract_address":""}
}

Surely, accept's implementation could be very complex, even with any number of arguments. Note that, no arguments would be passed to accept when initiating a binary transfer to the contract account, so if you defined a accept with some parameters, errors may occur during execution.

"use strict";
var AcceptableContract = function() {};
AcceptableContract.prototype = {
init: function(){},

accept: function(fruit, price){
if (fruit === 'robin') {
return parseInt(price) * 100;
} else {
return 1000;
}
}
};
module.exports = AcceptableContract;

In the end, unlike the init function, accept could be called as a common user function, and in this usage, it has no extra semantic effect.

What comes next?

In the upcoming fourth part of this series, we will introduce two new features of smart contract, i.e. Date and Math.random.