How to properly use the call (or delegatecall) in solidity - call

I'm trying to use this method:
function test(uint amount) public {
address(0xf5eA38B6b9644224dA1aECbC1219e8543c0689b2).call(abi.encodeWithSignature("deposit(uint)",amount));
}
but the transaction gets reverted, this is because the amount is not hashed in some way, and I don't really know to do it, what should I do on the amount? these are transactions:
-the failed one using the method: https://bscscan.com/tx/0x7fdd50cee23295ea866baa8961a2105c58162e77125df852a4fc5bf0fad2f507
and this was the input data:
Function: test(uint256 tAmount) ***
MethodID: 0x29e99f07
[0]: 0000000000000000000000000000000000000000000000000000000000000001
-the successfull one directly calling the contract from the site instead of using call inside another smart contract: https://bscscan.com/tx/0xfd4158766f25761fa5dddb0683c677085a04ea6db05e03794be375a8243d7128
and this was the input data:
Function: deposit(uint256 _amount) ***
MethodID: 0xb6b55f25
[0]: 000000000000000000000000000000000000000000000000005427aedb41a400
do I need to hash amount in someway?

The target contract defines uint as the argument type, but it's just an alias uint256. ABI encode methods don't automatically convert the aliases, so you need to change it in your code.
// `uint256` instead of `uint`
abi.encodeWithSignature("deposit(uint256)",amount)

Related

Storing hash on blockchain (hash of image stored on ipfs)

I am creating a dapp using react to store images on ipfs and the corresponding hash on the blockchain. The purpose of storing hash on the blockchain is timestamping, proof of ownership etc. and I wish to retrieve the hash also at a later stage. I need to know how can we store and retrieve hash on the blockchain.
If you just need to store and retrieve the IPFS hash of an image you can simply use Solidity's events. It may be a bit more complicated but it is a lot cheaper to deploy and use the contract.
Here is a basic approach:
event Store(string indexed id, string ipfsHash); //declare event
function setEvent(string memory _id, string memory _ipfsHash)public{
emit Store(_id, _ipfsHash);
}
When you emit the event in your smart contract, the parameters passed to it are stored in the transaction's logs, a special data structure of the blockchain.
Note that logs and their event data are not accessible within smart contracts. However, you can use libraries such as web3.js inside you app to retrieve them. The use of indexed keyword before the id parameter let's you effectively search for a particular log, containing a desired value. Without it, you would have to retrieve all logs produced by a particular event and search through them manually.
There are a few ways to retrieve past logs, but i will paste an example using getPastEvents :
var contract = new web3.eth.Contract(ABI_of_contract, address_of_contract);
contract.getPastEvents('Store', {
filter : { id : '...id corresponding to the ipfsHash'},
fromBlock : 0,
toBlock: 'latest'},
function(error, result){
console.log(result)
});
If you choose the Ethereum blockchain, the easiest way is to create a smart contract, the simplest example of which is given below.
By calling the Put method, you save the data associated with an identifier. The Get method allows you to retrieve data by identifier without any cost.
pragma solidity >=0.5.8 <0.6.0;
contract Storage
{
address Owner ;
mapping (string => string) Collection ;
//
constructor() public
{
Owner = tx.origin ;
}
//
function Put(string memory id_, string memory data_) public
{
if(msg.sender!=Owner) return ;
Collection[id_]=data_ ;
}
//
function Get(string memory id_) public view returns (string memory retVal)
{
return(Collection[id_]) ;
}
}

Is there any way to use flow to restrict specific string patterns?

I'm using Flow on a React webapp and I'm currently facing a use-case where I'm asking for the user to input certain time values in a "HH:mm" format. Is there any way to describe what pattern is being followed by the strings?
I've been looking around for a solution but the general consensus which I agree to to a certain point seems to be that you don't need to handle this kind of thing using Flow, favouring using validating functions and relying on the UI code to supply the code following the correct pattern. Still, I was wondering if there is any way to achieve this in order to make the code as descriptive as possible.
You want to create a validator function, but enhanced using Opaque Type Aliases: https://flow.org/en/docs/types/opaque-types/
Or, more specifically, Opaque Type Aliases with Subtyping Constraints: https://flow.org/en/docs/types/opaque-types/#toc-subtyping-constraints
You should write a validator function in the same file where you define the opaque type. It will accept the primitive type as an argument and return a value typed as the opaque type with subtyping constraint.
Now, in a different file, you can type some variables as the opaque type, for example in function arguments. Flow will enforce that you only pass values that go through your validator function, but these could be used just as if they were the primitive type.
Example:
exports.js:
export opaque type ID: string = string;
function validateID(x: string): ID | void {
if ( /* some validity check passes */ ) {
return x;
}
return undefined;
}
import.js:
import type {ID} from './exports';
function formatID(x: ID): string {
return "ID: " + x; // Ok! IDs are strings.
}
function toID(x: string): ID {
return x; // Error: strings are not IDs.
}

Swift can't call self from c callback in linphone sdk

I have problem when try to call Swift instance method from c callback.
Error: "A C function pointer cannot be formed from a closure that captures context."
linphone_core_cbs_set_registration_state_changed(cbs) { (lc, cfg, state, message) in
switch state{
case LinphoneRegistrationOk:
print("LinphoneRegistrationOk")
self.call()
}
func call() {
let account = "test"
let domain = "sip.linphone.org"
let identity = "sip:" + account + "#" + domain
linphone_core_invite(lc, identity)
}
If you have the ability to pass an arbitrary void* as a context then using Unmanaged<SelfType>.passUnretained(self).toOpaque() and converting it back with Unmanaged<SelfType>.fromOpaque(context).takeUnretainedValue() is the best solution.
But based on your small snippet of (lc, cfg, state, message) none of them seem like a context pointer. So getting self back is still possible but likely more complex. Because you will need to create a global/static piece of data that can be accessed from inside your closure in a safe manner. Some ideas of how you can do this are below:
1) You can do this with just a simple global/static if you know that is safe.
2) You can use thread local storage and store a pointer to self and cast it back and forth in the same way as if you had the void* argument and used Unmanaged. This one of course requires that your C callback be raised on the same thread where you store the value.
3) If you have access to a unique identifier that both Swift and C can access that will continue to be valid and accessible in your callback you can create a map of type [UniqueIdentifierAccessibleBySwiftAndC: TypeOfSelf] and use that to get self back.

When writing a Lua-facing function in C, what's a good way to check if an argument supports table-like lookups?

Here's a potential pattern that can check if an argument is a table:
int my_fn(lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
// .. do stuff with the table ..
}
This works whenever the first argument is a table. However, other Lua types support table lookups, such as a userdata, and in luajit, a cdata.
Is there a nice way to check if a table lookup, such as via lua_getfield, will succeed before I call it? I mean without restricting the type to tables. Relatedly, are tables, userdata, and cdata the only types in luajit that support indexed lookups?
I'm most interested in answers restricted to the Lua 5.1 C API because I'm using LuaJIT which currently works with this version.
Clarification
The advantage of the luaL_checkXXX functions is that, in one line, they:
throw an informative, user-friendly error message if the type is wrong, and
provide a C-friendly return value that can be used immediately.
I'm looking for something similar for tables. I don't expect a C-friendly hash-table return value, but I do want the same quality of error message to the user if the argument in question is not indexable.
I'm embracing the philosophy of duck typing. If I write a function that simply wants to index some keys from an argument, then I don't care if that argument is truly a table, or just a userdata that supports __index lookups. I want to accept either one.
In general, just tables have lookups because it's the only type which defines this property. Userdata are opaque, just the host knows what to do with it or adds a metatable (which can be analyzed) for specific behaviour. CData are part of Lua compiling with LuaJIT, i never used this type with C API (is it even supported?). At the end you have to check the type/metatable for possible lookups and request a field to check for setting, there's no way around lua_getfield (but raw access should be faster, see lua_rawget). The exception would be to check for table array length by lua_objlen.
Furthermore a cheaper solution for type checking would be lua_is*** functions.
Here's one way to do it:
// If the value at index narg is not indexable, this function does not return and
// provides a user-friendly error message; otherwise the stack is unchanged.
static void luaL_checkindexable(lua_State *L, int narg) {
if (lua_istable(L, narg)) return; // tables are indexable.
if (!luaL_getmetafield(L, narg, "__index")) {
// This function will show the user narg and the Lua-visible function name.
luaL_argerror(L, narg, "expected an indexable value such as a table");
}
lua_pop(L, 1); // Pop the value of getmetable(narg).__index.
}
This works for tables and any value with an __index value on its metatable.
It provides a standard-format error given by luaL_argerror. Here's an example error message:
a_file.lua:7: bad argument #1 to 'fn' (expected an indexable value such as a table)
You can use it like this:
// This Lua-facing function expects an indexable 1st argument.
int my_fn(lua_State *L) {
luaL_checkindexable(L, 1);
lua_getfield(L, 1, "key"); // --> arg1.key or nil is now on top of stack.
// .. your fn ..
}

How do I create a Flow with a different input and output types for use inside of a graph?

I am making a custom sink by building a graph on the inside. Here is a broad simplification of my code to demonstrate my question:
def mySink: Sink[Int, Unit] = Sink() { implicit builder =>
val entrance = builder.add(Flow[Int].buffer(500, OverflowStrategy.backpressure))
val toString = builder.add(Flow[Int, String, Unit].map(_.toString))
val printSink = builder.add(Sink.foreach(elem => println(elem)))
builder.addEdge(entrance.out, toString.in)
builder.addEdge(toString.out, printSink.in)
entrance.in
}
The problem I am having is that while it is valid to create a Flow with the same input/output types with only a single type argument and no value argument like: Flow[Int] (which is all over the documentation) it is not valid to only supply two type parameters and zero value parameters.
According to the reference documentation for the Flow object the apply method I am looking for is defined as
def apply[I, O]()(block: (Builder[Unit]) ⇒ (Inlet[I], Outlet[O])): Flow[I, O, Unit]
and says
Creates a Flow by passing a FlowGraph.Builder to the given create function.
The create function is expected to return a pair of Inlet and Outlet which correspond to the created Flows input and output ports.
It seems like I need to deal with another level of graph builders when I am trying to make what I think is a very simple flow. Is there an easier and more concise way to create a Flow that changes the type of it's input and output that doesn't require messing with it's inside ports? If this is the right way to approach this problem, what would a solution look like?
BONUS: Why is it easy to make a Flow that doesn't change the type of its input from it's output?
If you want to specify both the input and the output type of a flow, you indeed need to use the apply method you found in the documentation. Using it, though, is done pretty much exactly the same as you already did.
Flow[String, Message]() { implicit b =>
import FlowGraph.Implicits._
val reverseString = b.add(Flow[String].map[String] { msg => msg.reverse })
val mapStringToMsg = b.add(Flow[String].map[Message]( x => TextMessage.Strict(x)))
// connect the graph
reverseString ~> mapStringToMsg
// expose ports
(reverseString.inlet, mapStringToMsg.outlet)
}
Instead of just returning the inlet, you return a tuple, with the inlet and the outlet. This flow can now we used (for instance inside another builder, or directly with runWith) with a specific Source or Sink.

Resources