What's the difference between createPair and addLiquidity? - ethereum

createPair declare in Uniswap Factory contract, addLiquidity declared in Uniswap Router contract, both can create liquidity pair and swap avaliable in app.uniswap.org.
But most developers use addLiquidity instead of createPair. What's the difference between createPair and addLiquidity?

As the function naming suggests, both functions have a different purpose.
createPair() is meant to be used mainly for creating a pair
addLiquidity() is for adding liquidity to a pair
Having said that, addLiquidity() is more robust and performs a call to createPair() if the pair doesn't exist yet. So by calling addLiquidity() you can "create a pair and add liquidity" in one transaction, instead of splitting the action into 2 separate transactions, saving transaction fees.

Related

Advantage/Disadvantage between Chainlink VRF and an off-chain random number transaction performed by your server?

As I understand it Chainlink VRF uses the request-response approach for providing contracts with a "trusted random number". You (the developer) create a smart contract and inherit the Chainlink VRFConsumerBase contract, declare a storage variable that will hold your random number result, then initialize some keyhash & chainlink oracle address, and implement a function ( lets say abc() ) that calls Chainlinks "requestRandomness()" function. You then override the internal "fulfillRandomness()" function and set the returned random number on your storage variable.
Short flow:
Fund your smart contract with LINK, make a transaction call to abc()
Wait for Chainlinks Oracle to make a transaction call to your contract "fulfillRandomness()" and set the random number result on your storage variable.
Rather than using this approach wouldn’t it be sufficient to just write a smart contract that emits a "RequestRandom" Event and have a personal server running that listens for the RequestRandom event of your contract and have that server then generate a random number and make an authorized transaction to my contract to set that generated random number on it.
contract MyRandom {
event RequestRandom(uint seed);
address public myServerWallet;
uint public myRandomNumber;
constructor(address a) {
myServerWallet = a;
}
function makeRandomRequest(uint seed) external {
emit RequestRandom(seed);
}
function setRandomResult(uint result) external {
require(msg.sender == myServerWallet, "Only server may call");
myRandomNumber = result;
}
}
What would be the difference between this approach vs Chainlink VRF? Am I sacrificing some type of security by using this approach?
Tried the server approach above. It does work but still curious on advantage/disadvantage.

What information are visible in transaction after a call to a payable function?

I was wondering what information are publicly visible and intelligible when an EOA (external ownable address) calls a payable function on a smart contract, with some parameters and a return value.
Let us say I have the smart contract function below, the question is: 'is the return value visible somewhere on the blockchain?'. I am using Solidity 0.8.12.
function askForSecretCode(uint time) external payable returns (bytes32) {
require(msg.value == 42, 'Need to pay 42 wei.');
secretCodes[secretCodesNum] = keccak256(abi.encodePacked(msg.sender, time);
return keccak256(abi.encodePacked(msg.sender, time);
}
Anyone can see the input time param value as a part of a transaction invoking the askForSecretCode function.
Even though if you don't publish the contract source code, the bytecode is public, and there are decompilers that can (with some error rate) help generate source code back from the bytecode. So let's assume that the source code is available as well.
From the source code (or usually even from the pseudocode generated by the decompiler), anyone can determine the storage slot of secretCodesNum (which from the context seems to be a property of the contract) and retrieve its value using the eth_getStorageAt RPC method, including historical values.
Using these secretCodesNum values, they can use the same method to determine storage slots of any secretCodes[secretCodesNum] and their values.
TLDR: Never ever store private data on the blockchain.

Solidity tx.destination.call.value(tx.value)(tx.data)

I came across this Solidity code:
tx.destination.call.value(tx.value)(tx.data)
but don't understand how it works... especially the tx.data at the end.
This statement is calling a function represented by tx.data on the address at tx.destination passing in wei (tx.value).
To break it down further:
tx.destination is an address. An address has built in members and functions, including call which allows you to execute functions on a contract without the ABI (see Address type definition). For example, you can call a method foobar on a contract without a defined interface like this:
contractAddress.call(bytes4(keccak256("foobar(uint256,uint256)")), val1, val2); // where val1 and val2 are the uint256 parameters to pass in
Using call alone will use some default values when calling the other contract's method. For example, all of the remaining gas will be forwarded. If you want to change those values, you can adjust it by supplying your own gas and/or wei values, which looks like a function call itself:
contractAddress.call.value(9999999)();
This will send 9999999 wei to contractAddress. You can override both the gas and ether sent by chaining multiple function calls:
contractAddress.call.value(99999999).gas(77777)();
The last set of parens in both examples indicate to use the fallback function when sending the wei. You can see a similar example in the Solidity docs FAQ.
If you wanted to call something other than the fallback function, you would combine the 2 examples above, which is what the code you posted is doing. The fact that they are using tx is a bit confusing since that is normally a built-in reference, but they are likely shadowing that and it's referencing a struct with destination, value, and data members.

Read-only Functions Iteration Cost

I am developing smart contracts for some use-cases and currently I'm working on optimization of smart contracts. I am confused with something that I found interesting on Hitchiker's Guide. In the section 4- Iterating the contract code
// returns true if proof is stored
// *read-only function*
function hasProof(bytes32 proof) constant returns (bool) {
for (uint256 i = 0; i < proofs.length; i++) {
if (proofs[i] == proof) {
return true;
}
}
return false;
}
For this code above, He states that "Note that every time we want to check if a document was notarized, we need to iterate through all existing proofs. This makes the contract spend more and more gas on each check as more documents are added. "
There is no doubt that the proper way of implementing it is to use mapping instead of array structure. Here is the point that makes me confused. It's read-only function and it is not a transaction that affects blockchain. When I observed my netstats, it does not show any transaction when this function is called(Actually, it is what I expected before calling this function).
I don't think that he misunderstood the mechanism, could someone clean my mind about this comment?
Roman’s answer is not correct. Constant functions still consume gas. However, you don’t pay for the gas usage when it runs in the local EVM. If a constant function is called from a transaction, it is not free. Either way, you are still consuming gas and loops are a good way to consume a lot.
EDIT - Here is an example to illustrate the point
pragma solidity ^0.4.19;
contract LoopExample {
bytes32[] proofs;
function addProof(bytes32 proof) public {
if (!hasProof(proof))
proofs.push(proof);
}
function hasProof(bytes32 proof) public constant returns (bool) {
for (uint256 i = 0; i < proofs.length; i++) {
if (proofs[i] == proof) {
return true;
}
}
return false;
}
}
And here are the gas consumption results for calling addProof 4 times:
addProof("a"): 41226
addProof("b"): 27023
addProof("c"): 27820
addProof("d"): 28617
You kind of have to ignore the very first call. The reason that one is more expense than the rest is because the very first push to proofs will cost more (no storage slot is used before the 1st call, so the push will cost 20000 gas). So, the relevant part for this question is to look at the cost of addProof("b") and then the increase with each call afterwards. The more items you add, the more gas the loop will use and eventually you will hit an out of gas exception.
Here is another example where you are only calling a constant function from the client:
pragma solidity ^0.4.19;
contract LoopExample {
function constantLoop(uint256 iterations) public constant {
uint256 someVal;
for (uint256 i = 0; i < iterations; i++) {
someVal = uint256(keccak256(now, i));
}
}
}
Here, if you call this through Remix, you'll see something like this in the output (Notice the comment on gas usage):
Finally, if you try to run this constant method from a client using too many iterations, you will get an error:
$ truffle console
truffle(development)> let contract;
undefined
truffle(development)> LoopExample.deployed().then(function(i) { contract = i; });
undefined
truffle(development)> contract.constantLoop.call(999);
[]
truffle(development)> contract.constantLoop.call(9999);
[]
truffle(development)> contract.constantLoop.call(99999);
Error: VM Exception while processing transaction: out of gas
at Object.InvalidResponse (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\errors.js:38:1)
at C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\requestmanager.js:86:1
at C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\truffle-provider\wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3\lib\web3\httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:64:1)
at XMLHttpRequest._setReadyState (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:509:1)
at IncomingMessage.<anonymous> (C:\Users\adamk\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:469:1)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
Most of the people will say constant functions will not consume gas. That will not correct because, constant functions execute on the local node's hardware using it's own copy of the blockchain. This makes the actions inherently read-only because they are never actually broadcast to the network.
Lets assume I've contract having isEmp constant function, when I call estimateGas() it should return 0 if constant method's are not consuming gas. But its returning 23301.
truffle> contractObj.isEmp.estimateGas(web3.eth.accounts[0])
23301
Here is my solidity code
function isEmp(address employee) public constant returns(bool) {
return emps[employee];
}
Hence above experiment is proved that it will consume gas.
The thing is that constant (now it's called view) functions are getting the information from previously executed normal functions. Why? Because view functions are accessing the storage of the contract that created in creation of the contract and changed with functions that changes it if you write the function that way. For example:
contract calculateTotal{
uint256 balance;
constructor(uint256 _initialBalance){
balance=_initialBalance;
}
function purchaseSmth(uint256 _cost) external {
balance=balance-_cost;
}
function getBalance() external view returns(uint256){
return balance;
}
}
Now when you create this contract you set the balance, that way balance already calculated and you don't need to be recalculated because it will be the same. When you change that balance value with purchaseSmth the balance will be recalculated and storage value of balance is going to change. That means that function will change the blockchain's storage. But again you are paying for these executions because the blockchain must be changed. But view functions are not changing any storage value. They are just getting the previously calculated value that standing in blockchain already. When you make some calculations in the view functions like: return balance*10; the execution does not affects blockchain. The calculation of it will be done by your device. Not by any miner.
If we look at the answer of #AdamKipnis we see that constant/view function is not consuming any gas by itself if you call it rightaway. Because it will be always calculated before. First the constructor will create it as empty array. Then when you call the hasProof you will see an empty array. Then when you use addProof it will change the proofArray. But the price is going bigger because it uses the hasProof function in it. If it wasn't there then the price would not go up forever. However If you call the hasProof function manually then your computer(if it is a node) will execute that loop locally eitherway if that function has it or not. But any storage, status changing execution will be directed to miners because of the blockchain logic. Someone else should execute that code and verify it If that change is possible in that transaction and If there is no error in the code.
When you use a wallet like metamask wallet in some cases you can see the errors before making any transactions(executions). But that is not a verified error until you make the transaction and a miner executes that code then finds that this code has some errors or it is doing, changing something in a way that it shouldnt be possible. Like trying to transferring to yourself some bnb from another person's wallet. That execution can't happen because It is not your wallet to transfer the bnb from. It sounds obvious but random miners should validate that execution to making a block that includes your transaction in it with other executions in per block transaction limit boundary in that time.
EDIT: The device, computer, hardware is the node. Node can be you or if you use a remote node for your executions than the node will do everything your device will not. Like cloud computing. Because you would'nt have a ledger if you were not a node.
It will only cost gas if the constant (view or pure) function is executed or called by another external smart contract, that is not the owner of that function. But if it is called from within the smart contract that declared the constant (view or pure) function, then no gas will be used.
Just like when you use a class member function in another class in other programming languages by creating an object of that class. But in solidity this will cost you regardless of the fact that it's a constant function or not.
So when Jitendra Kumar. Balla did an experiment that showed it will cost gas, the gas shown there is the estimated gas cost if it is called by another smart contract but not from within the smart contract.

Prototype for array locator functions

I am thinking of creating a generic task/function which will read a transaction from any given ovm analysis port and if the transaction matches some constraint provided by user then i will fire an event that matching transaction found.
I want the user to pass the constraint like we pass it with array locator functions using the with clause like
out = arr.find_first with (item == 10);
The with clause in many of SystemVerilog's constructs is not very OOP friendly. There is no way to pass the with expression as an argument.
Two software design patterns you may want to try is
the factory - where you allow the user to extend these functions with a difference compare function
a policy class - you can make class whose sole purpose is to provide a compare function.