I am going to send tezos from contract to an address using jsLigo
if (amount > (0 as tez)) {
let receiver: contract<unit> =
match ((Tezos.get_contract_opt(sender) as option<contract<unit>>), {
Some: (contract) => contract,
None: () => failwith("Contract not found.")
});
Tezos.transaction(unit, (amount as tez), receiver);
}
I am getting this error while building.
Invalid type(s)
Cannot unify operation with unit.
And I am not sure it is correct method to send tezos.
Related
I'm testing this function:
function Deposit(uint256 StopLoss) public payable {//Deposita quantity i es registre
//Pay subscription
if (msg.value == 0){
revert Quantity_zero();
}
//Add wallet to the s_Wallets
s_Wallets.push(payable(msg.sender));
//Start subscription time
Dades storage dades = s_Registre[msg.sender];
dades.Quantity += msg.value;
dades.Stop = StopLoss;
}
When sending value and StopLoss argument it allways send me some error.
This is the js testing code being 1850 the argument StopLoss value and sending a 5 ETH value.
describe("Subscription", async function () {//PriceConversion
it("Subscribes the deployer", async function () {
await MarketOrder.Deposit(1850, {value: ethers.utils.parseEther("5")})
const Quantity = await MarketOrder.CallQuantity()
console.log(`Q: ${Quantity}`)
const Stop = await MarketOrder.CallStop()
console.log(`S: ${Stop}`)
assert.equal(Quantity.toString(), 1850)
assert.equal(Stop.toString(), 5)
}
})
This is the error:
1) MarketOrder Unit Tests
Subscription
Subscribes the deployer:
Error: invalid BigNumber value (argument="value", value=[1850], code=INVALID_ARGUMENT, version=bignumber/5.6.2)
at Logger.makeError (node_modules/#ethersproject/logger/src.ts/index.ts:261:28)
at Logger.throwError (node_modules/#ethersproject/logger/src.ts/index.ts:273:20)
at Logger.throwArgumentError (node_modules/#ethersproject/logger/src.ts/index.ts:277:21)
at Function.BigNumber.from (node_modules/#ethersproject/bignumber/src.ts/bignumber.ts:289:23)
at NumberCoder.encode (node_modules/#ethersproject/abi/src.ts/coders/number.ts:25:27)
at /home/oriok/hh-ff/1.uniswapV3/node_modules/#ethersproject/abi/src.ts/coders/array.ts:71:19
at Array.forEach (<anonymous>)
at pack (node_modules/#ethersproject/abi/src.ts/coders/array.ts:54:12)
at TupleCoder.encode (node_modules/#ethersproject/abi/src.ts/coders/tuple.ts:54:20)
at AbiCoder.encode (node_modules/#ethersproject/abi/src.ts/abi-coder.ts:111:15)
error Command failed with exit code 1.
Does anyone know how to send argument + value properly?? I have tryed many codes but not working.
Ty guys!
ethers.utils.parseEther returns object with BigNumber in it..
you have to convert it into string before using it in the test..
Eg:
ethers.utils.parseEther("5").toString()
Refer.. https://docs.ethers.io/v5/api/utils/display-logic/#utils-parseEther
I am currently working on a crowd sale contract, But I am having an issue with a function as the list of the error and the code of the function is attached, I need someone to tell me that what is happening in the code and how can i resolve the error that I'm facing in the code. Solidity version ^0.5.0
Code:
function _finalization() internal {
if (goalReached()) {
ERC20Mintable erc20Mintable = ERC20Mintable(token);
//getting the total tokens that are been minted yet
uint256 alreadyMintedToken = erc20Mintable.totalSupply();
//tokens of the final total supply
uint256 finalTotalTokenSupply = alreadyMintedToken
.div(tokenSalePercentage)
.mul(100);
foundersTimelock = new TokenTimelock(
token,
foundersFund,
releaseTime
);
partnersTimelock = new TokenTimelock(
token,
foundersFund,
releaseTime
);
foundationTimelock = new TokenTimelock(
token,
foundersFund,
releaseTime
);
//we will have the tokens that the founder will get
erc20Mintable.mint(
address(foundersTimelock),
finalTotalTokenSupply.mul(foundersPercentage).div(100)
);
erc20Mintable.mint(
address(partnersTimelock),
finalTotalTokenSupply.mul(partnersPercentage).div(100)
);
erc20Mintable.mint(
address(foundationTimelock),
finalTotalTokenSupply.mul(foundationPercentage).div(100)
);
erc20Mintable.renounceMinter();
// Unpause the token
ERC20Pausable erc20Pausable = new ERC20Pausable(token);
erc20Pausable.unpause();
erc20Pausable.renounceOwnership(wallet);
}
super._finalization();
}
Error 1:
Explicit type conversion not allowed from "function () view returns
(contract IERC20)" to "contract ERC20Mintable". ERC20Mintable
erc20Mintable = ERC20Mintable(token);
Error 2:
Crowdsale.sol:179:46: TypeError: Invalid type for argument in function call. Invalid implicit conversion from function () view returns (contract IERC20) to contract IERC20 requested.
foundersTimelock = new TokenTimelock(token,foundersFund,releaseTime);
^---^
Error 3:
Crowdsale.sol:179:28: TypeError: Type contract TokenTimelock is not
implicitly convertible to expected type address. foundersTimelock =
new TokenTimelock(token,foundersFund,releaseTime);
am manually setting up a model class with json (de)serialization. By now I have implemented some testcases. In particular one where I check if toJson -> fromJson is the identity for my model type called Session.
Here is the relevant part of my model type:
class Session extends Equatable {
final List<User> audience;
/* ... */
Session.fromJson(Map<String, dynamic> json) :
/* ... */
audience = (json['audience'] as List).map(((it) =>
User.fromMap(it))).toList();
Map<String, dynamic> toJson() => {
/* ... */
'audience': audience.map((it) => it.toJson()).toList()
};
}
These are the types in the audience field:
class User extends Equatable {
factory User.fromJson(Map<String, dynamic> json) {
if (_isRegisteredUserJson(json)) {
return RegisteredUser.fromMap(json);
} else {
return User(id: json['id']);
}
}
/* ... */
}
class RegisteredUser extends User {/* ... */}
In my test I set up the audience field (using the faker library) like so:
User _user() => User(id: faker.guid.guid());
RegisteredUser _registeredUser() => RegisteredUser(
id: faker.guid.guid(),
alias: faker.person.name(),
email: faker.internet.email());
Session _session => Session(
audience: faker.randomGenerator
.amount((n) => n % 3 == 0 ? _registeredUser() : _user, 100)
.cast<User>()
/* ... */
);
I expect the audience List to contain only elements of type User or RegisteredUser after toJson() returns. Instead I get A List containing either RegisteredUsers or _Closure: () => 'User from Function' which I am not exactly sure about what that is.
As a result I get the following Error Message for my test:
00:00 +4 -1: toJson -> fromJson is identity for Session [E]
type '() => User' is not a subtype of type 'User' in type cast
dart:_internal/cast.dart 99:46 _CastListBase.[]
dart:collection/list.dart 60:33 __CastListBase&_CastIterableBase&ListMixin.elementAt
dart:_internal/iterable.dart 414:40 MappedListIterable.elementAt
dart:_internal/iterable.dart 219:19 ListIterable.toList
package:feedback/model/base_module.dart 42:54 BaseModule.toJson
package:feedback/model/session.dart 51:23 Session.toJson
test/json_test.dart 34:47 main.<fn>.<fn>
package:test_api/src/backend/declarer.dart 168:27 Declarer.test.<fn>.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/future_impl.dart 22:43 _Completer.completeError
dart:async/runtime/libasync_patch.dart 40:18 _AsyncAwaitCompleter.completeError
package:test_api/src/backend/declarer.dart Declarer.test.<fn>.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1053:19 _CustomZone.registerUnaryCallback
dart:async/runtime/libasync_patch.dart 77:23 _asyncThenWrapperHelper
package:test_api/src/backend/declarer.dart Declarer.test.<fn>.<fn>.<fn>
package:test_api/src/backend/invoker.dart 250:15 Invoker.waitForOutstandingCallbacks.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1045:19 _CustomZone.registerCallback
dart:async/zone.dart 962:22 _CustomZone.bindCallbackGuarded
dart:async/timer.dart 52:45 new Timer
dart:async/timer.dart 87:9 Timer.run
dart:async/future.dart 174:11 new Future
package:test_api/src/backend/invoker.dart 399:21 Invoker._onRun.<fn>.<fn>.<fn>
00:00 +4 -1: Some tests failed.
Unhandled exception:
Dummy exception to set exit code.
#0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1112:29)
#1 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#3 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:391:30)
#4 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
#5 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
Thanks to Jordan Davies, here is the answer:
In the method call _user I accidentally omitted the brackets and therefore passed a function as parameter where I wanted the result of that function.
I am trying the following API using Alamofire, but this API has multiple "to" fields. I tried to pass an array of "to" emails as parameters. It shows no error but did not send to all emails. API is correct, I tested that from terminal. Any suggestions will be cordially welcomed.
http -a email:pass -f POST 'sampleUrl' from="email#email.com" to="ongkur.cse#gmail.com" to="emailgmail#email.com" subject="test_sub" bodyText="testing hello"
I am giving my code:
class func sendMessage(message:MessageModel, delegate:RestAPIManagerDelegate?) {
let urlString = "http://localhost:8080/app/user/messages"
var parameters = [String:AnyObject]()
parameters = [
"from": message.messageFrom.emailAddress
]
var array = [String]()
for to in message.messageTO {
array.append(to)
}
parameters["to"] = array
for cc in message.messageCC {
parameters["cc"] = cc.emailAddress;
}
for bcc in message.messageBCC {
parameters["bcc"] = bcc.emailAddress;
}
parameters["subject"] = message.messageSubject;
parameters["bodyText"] = message.bodyText;
Alamofire.request(.POST, urlString, parameters: parameters)
.authenticate(user: MessageManager.sharedInstance().primaryUserName, password: MessageManager.sharedInstance().primaryPassword)
.validate(statusCode: 200..<201)
.validate(contentType: ["application/json"])
.responseJSON {
(_, _, jsonData, error) in
if(error != nil) {
println("\n sendMessage attempt json response:")
println(error!)
delegate?.messageSent?(false)
return
}
println("Server response during message sending:\n")
let swiftyJSONData = JSON(jsonData!)
println(swiftyJSONData)
delegate?.messageSent?(true)
}
}
First of all if you created the API yourself you should consider changing the API to expect an array of 'to' receivers instead of multiple times the same parameter name.
As back2dos states it in this answer: https://stackoverflow.com/a/1898078/672989
Although POST may be having multiple values for the same key, I'd be cautious using it, since some servers can't even properly handle that, which is probably why this isn't supported ... if you convert "duplicate" parameters to a list, the whole thing might start to choke, if a parameter comes in only once, and suddendly you wind up having a string or something ...
And I think he's right.
In this case I guess this is not possible with Alamofire, just as it is not possible with AFNetworking: https://github.com/AFNetworking/AFNetworking/issues/21
Alamofire probably store's its POST parameter in a Dictionary which doesn't allow duplicate keys.
Hi I am using Lift for my api and need some help generating a jSONP response. I have a working version of the JSON response and need to add to it so that I can use my api for cross-domain calls. Here is a code snippet of my api currently:
/Request/
case "api" :: "events" :: "person" :: _ Get req => JsonResponse(json_person(personEvents(req, req.request.queryString.mkString("")),person_details(req)))
/response/
def json_person(in : List[Events], person1 : List[Person]) : JValue = {
("person" ->
person1.map(people =>
("name" -> people.main_person_name.is) ~
("alternate_name" -> people.aka.is)
))}
The way I've done this in the past is to check for whether or not a "callback" query parameter was provided in the URL, and if so, use the function name provided to perform the callback. If not provided, send back the object itself.
case "api" :: "events" :: "person" :: _ Get req => {
val jsonObj = json_person(...)
S.param("callback") match {
case Full(callbackName) => JSFunc(callbackName, jsonObj).cmd
case _ => JsonResponse(jsonObj)
}
}