texts: Solidity. Concatenate and hash two strings

texts:
Hi all I need tho sha256 two strings. I am new to solidity. This is what I've got:

function addressToString(address _addr) public pure returns(string memory)
{
    bytes32 value = bytes32(uint256(_addr));
    bytes memory alphabet = "0123456789abcdef";

    bytes memory str = new bytes(51);
    str[0] = '0';
    str[1] = 'x';
    for (uint256 i = 0; i < 20; i++) {
        str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)];
        str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)];
    }
    return string(str);
}

function addExam(string memory examHash) public onlyOwner returns (string memory examProfessorHash) {
    // Hash the examHash and the professorsAddress together
    examsFinalHash = keccak256(abi.encodePacked(examHash, addressToString(msg.sender)));  // TYPE ERROR

    professorsExam[msg.sender] = examsFinalHash;

    return examsFinalHash;
}

I got the addressToString function from this SO answer: Convert address to string . But I still get this error:

  Type bytes32 is not implicitly convertible to expected type string
  storage ref. examsFinalHash = keccak256(abi.encodePacked(examHash,
  addressToString(msg.sender))); // TYPE ERROR


texts: Dynamically create smart contract structure based on user input

texts: I would like to create a smart contract based on user input. User would provide some information/data from the UI, and based on the information provided my smart contract logic would get defined, and then the smart contract would get deployed. Is it possible to achieve this?


texts: How can we write a contract that relies on hidden information?

texts: Since a smart contract can only access (public) information on the blockchain itself, how can I make a smart contract that relies on hidden / secret information? Are there any workarounds in this situation?


texts: Who mines/confirms blocks on private Ethereum projects?

texts:
this is a pretty simple question - I understand that projects can be built on the Ethereum blockchain. I have tried doing a bunch of Googling, but can't seem to figure out who mines these projects.

For example, if I were to build my own smart contract system using the Ethereum protocol, who would confirm the blocks when transactions take place? Is this shared across the entire Ethereum platform, or would the incentive for miners be a particular token?

Thanks!


texts: What is formal verification, and why is it important for smart contracts?

texts:
"Formal verification" has appeared in various previous questions and answers, and I believe was the topic for one of the talks at DevCon2.

Main question: It's perhaps quite broad, but what is formal verification in the context of Ethereum, and why do we need it for smart contracts?

Sub-questions:

Is it something that's already implemented and part of the ecosystem, or is it something that will be implemented in future?
How is formal verification different to the inherent determinism of the language a smart contract is written in? (See Why do smart contract languages need to be deterministic?)


texts: web3js encodeABI() is there way to call it asynchronously?

texts:
I am working on an ERC827 contract invocation through metamask. For ERC827 transfer method require an additional 'data' argument. Since encodeABI()supports only synchronous invocation, metamask throws error. Is there a way to workaround this problem?

my contract invocation code is something like below.

let erc827_abi = { contract abi}
let service_abi = {contract abi}
var erc827_address = '0x9df5e31a1e5de828254d535d5c9b514d513316e8'
var service_crt_address = '0x1ce94a12f58b0b9b39d0a9f1520878a07d9a72e8'
var user_address = web3.eth.accounts[0]

const erc827contractInstance = web3.eth.contract(erc827_abi).at(erc827_address);
const servicecontractInstance = web3.eth.contract(service_abi).at(service_crt_address);

//encodeABI() is the call which fails.

const sdata = servicecontractInstance.bookService(args.servicename,user_address,args.customername,args.servicetype,args.value,args.transaction_type,args.account_number).encodeABI(function(error, result){
 if(!error)
     console.log(result);
 else
     console.error(error)
 });
console.log("encoded ABI is",sdata)

erc827contractInstance.transferFrom(user_address,testadd_2,tokensToSend,sdata{from: testadd_2,gas:55000},function (error, result){ //get callback from function which is your transaction key
   if(!error){
        console.log(result);
    } else{
        console.log(error);
    }
});

if encodeABI() is invoked like below it works.

const sdata = servicecontractInstance.bookService(args.servicename,user_address,args.customername,args.servicetype,args.value,args.transaction_type,args.account_number).encodeABI();

But unfortunately metamask does not support this.

appreciate any pointers on resolving this.

Thanks James for your response. Please see the error information. not sure this is the one you are looking for.

inpage.js:1 Uncaught Error: The MetaMask Web3 object does not support synchronous methods like eth_sendTransaction without a callback parameter. See https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#dizzy-all-async---think-of-metamask-as-a-light-client for details.
    at MetamaskInpageProvider.send (inpage.js:1)
    at s.send (inpage.js:1)
    at n.e [as sendTransaction] (inpage.js:1)
    at u.sendTransaction (inpage.js:1)
    at u.execute (inpage.js:1)
    at HTMLDivElement.<anonymous> (:formatted:1767)
MetamaskInpageProvider.send @ inpage.js:1
s.send @ inpage.js:1
e @ inpage.js:1
u.sendTransaction @ inpage.js:1
u.execute @ inpage.js:1
(anonymous) @ :formatted:1767


texts:
I would like to create a smart contract that will take care of locking and/or vesting funds to several beneficiaries (inputted by the owner of the smart contract). The funds that it will vest and lock needs to come from another token smart contract. Is that even possible? My question is how do you get funds from a ERC20 token smart contract to my vesting/locking smart contract so that  It can then manipulate the funds according to some set rules.

Thanks a lot <3


texts:
Is there any way to unlock the ethereum account when using the infura api.

Can only metamask do it?

I would not like to use metamask because not every user has it on the browser


texts: Subtraces of delegatecall in Parity trace

texts:
I'm investigating transactions using Parity trace which provides useful data over a transaction flow. Among this data is the Subtraces field which allows me to understand how many sub-calls each action has.

When delegate-call is used it seems that the subtraces are a bit confusing.
For example, looking at this transaction trace I can see a few delegate calls, for example Action [6] which has 1 subtrace, but I can't see any action called by this step (by 0x2157a7894439191e520825fe9399ab8655e0f708 in this case).
Why is that? What is the meaning of the subtraces field in calls of type delegatecall?


texts: OpenZeppelin Pausable Concept, Security Concepts

texts:
Are items like the OpenZeppelin Pausable contracts any different than just having additional checks inline with standard Solidity?  If a coder just placed checks in front of every function call with similar a similar boolean check, would this have any less security effect?  The owner of the contract (or multi-sig option) would be the only one who can change the boolean.

If I am missing something please explain.  I agree that a secure OS that builds all this on top of simple easy to read contracts is a good idea, I just want to be sure that the OpenZeppelin OS is not somehow doing something more than this.


texts: Does test network account reset when I restart the node?

texts:
When I start a test network (using geth --ropsten --syncmode ~~etc command) and enter console (using geth attach <ipc_address> command) to see the balance of my accounts, it's always empty.  Even though I faucet them before. So I need to faucet the accounts again.
Does the balance of accounts always reset after I stop the network?


texts: Exception in Contract Reverts Entire Stack, Uses all Gas

texts:
I added a check to make sure when I send ether that if it fails, I attempt to abort the transaction using a throw.  Per example here:  Solidity Exceptions

When make a call to a function that does this throw from another contract and the throw fails, all gas is used up on that source contract's gas budget.  (gasUsed == gasSent in the transaction receipt).  This happens no matter how much gas I send.

The throw is inside a complicated loop (business logic), but it's just like the example cited above:

// inside complicated business logic I wish to roll back if this fails
if (a.send(remittance) == false) {
    throw;
}

The code that is making the call from another contract looks like this.  I'll note there's only one callback currently installed:

for(uint i = 0;i < callbacks.length; i++) {
    callbacks[i].oracleCallback(_value, _time, _info);
}

I'm using a fairly recent build of the master branch of geth and a fairly recent build (early January) of solidity.

Here's the transaction receipt (private test server):

{"transactionHash":"0x61474d8ecd82d5c95d7c9c548f5a4cd5213b16775809580189860bd69773c07a","transactionIndex":0,"blockNumber":440377,"blockHash":"0xb88779e44dabd14fcc55f7a0cdd31aaeab6417b990ed626748d8726463173bad","cumulativeGasUsed":800000,"gasUsed":800000,"contractAddress":null,"logs":[]}


texts: Why does ethminer only show 3GB on my Sapphire R7 370 4GB?

texts:
Ethminer found my Sapphire R7 370 Nitro 4GB but only shows 3221225472 bytes of memory.

My r7 had 4GB of memory.

I would like to konw why my Sapphire R7 370 4GB only use 3GB of gpu memory.

I am using the last version of ethmine (Ethminer 0.9.41-genoil-1.0.4b3) on operating system is Windows 10 Home.


texts: Node running on testnet doesn't match etherscan explorer

texts:
Two of my nodes running geth version 1.5.3 have been working great on testnet since 24th November 2016 by using this command:

geth --rpc --datadir /mydatadir/.ethereum/testnet --networkid 3

but recently they seem to be working on another chain or fork different from testnet.etherscan.io. Transactions and balances are different on my nodes from the public testnet explorer. Last transactions created by the nodes don't even exist on testnet.etherscan.io so I guess my nodes are working off the main testnet chain.

For example, the address 0xf28dafbfeb41bf32869c9d498da0d651d0206ed4 has 9,041 ethers according to testnet.etherscan.io but it has 10,121 according to my nodes:

https://testnet.etherscan.io/address/0xf28dafbfeb41bf32869c9d498da0d651d0206ed4

Besides, my nodes are reporting last block is #667887 meanwhile testnet.etherscan.io says it is #690562

Has been there any kind of fork on testnet lately? Is parameter networkid = 3 right to work on Ropsten testnet? Do I have to upgrade my node to work on the standard testnet chain again? Thx!

P.S.: After reading the 5 answers at Ropsten testnet is under kind of attack? What can we do? my conclusion is Geth as of now cannot operate on last testnet Kovan. Right? So, only option seems to be to wait for new geth release or migrate my nodes to Parity, is that correct?


texts: Is it possible to download a existing smart contract state from a blockchain and deploying it in a different blockchain?

texts:
Suppose I have independent 2 ethereum blockchain on private net N1 and N2. A smart contract S exists on the blockchain N1. Consider that the smart contract S is self-complete and doesn't depend on any external state of the chain N1.

  Is it possible to download the smart contact from the chain N1 along with all the complete state of the contract S and deploy it in chain N2?

The deployed contract in chain N2 reflect the most recent state of the contract in N1 before the download.

  How to download a smart contract state (code and storage both) from a blockchain?


texts: Getting error while trying to generate genesis block?

texts:
I am trying to generate the genesis block but getting an error:

Please guide me for this issue.


texts: How to print "string" from Solidity in React?

texts:
My smart contract function is :

function sNName(uint z)public view returns(string memory) {
    return abc[xyz[z].name];
}

Where abc represents a mapping (bytes32 => string)

In my .js file, I called the function like this:

for(x=0 ;x < t; x++)
{
  n = await marketplaceContract.methods.sNName(x).call().toString();
  this.setState(prevState => ({
    cart: [...prevState.cart, n]
  }));
}

When I try to output cart, I get :

[object Promise]

I expected a string cos I have used await. Is there any mistake in using it inside a loop?

Please help.


texts: How can I trigger a quorum private smart contract deployment from my js client app?

texts:
My question follows directly this answer to a similar question.

I need for my client app users to be able to trigger private contract deployment. I've tried using privateFor with both the web3 and web3-quorum npm packages, but it doesn't work: contract is deployed but not private.

I understand from the answer above that Quorum only allows creating a private smart contract from the node itself, because the node possess the keys to encrypt and decrypt everything.

So here's my question: Can a smart contract function itself deploy a private smart contract?

I will try but it will take me a while so maybe I can get an answer here before then.

Thank you


texts:
I am following this guide to set up Ethereum Proof of Authority on a VM in Azure.  The guide says this about  deploying a node, after setting up the enode.

  --port 30311 is the enode port for node1 and has to be different from the bootnode port (that is 30310 if you followed my command) because we are on a localhost. On a real network (one node per machine), use the same port.

so in command prompt i did this

  bootnode -nodekey boot.key -verbosity 9 -addr :30310

then i opened another prompt window to launch the node. using my public ip for rpc addr and using 30310 for the --port.

However i am bing given this message:

  Fatal: Error starting protocol stack: listen udp :30310: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

Why am i getting this message if there was written,

  On a real network (one node per machine), use the same port.

n.b. im only deploying the enode and 1 node on this vm


texts: Unable to start parity: database migration fails repeatedly

texts:
I am unable to start Parity, the database migration fails repeatedly. How in Parity on MacOS (1.4.5 already installed) do I eliminate this error so that my Parity will run?

Geth is fine but not running when this occurs.


texts: $200 reward! Sent tron to a contract I created accidentally

texts:
Just curious. I sent a little bit of tron to a contract that I created. I can access the wallet I used to create said contract - but in order to access the tron I sent to the contract I'd need to address it through metamask, or something? I only have the actual wallet orginally used to create the contract.

This is the contract

and this is the wallet that was used to create it

I'll give anyone $200in TRX/ETH if they can figure this out.

Just to note as well - I do not have the original source code saved when I created this contract using http://remix.ethereum.org/ - IS there a way to still salvage the tron, and withdraw it?


texts: Error while migrating contracts to Ropsten using truffle - Error: legacy access request rate exceeded

texts:
I'm deploying some contract to Ropsten ethereum test network using Truffle but it gave me this error:

Error: legacy access request rate exceeded

I have no idea what does it means and what should I do with it. Before I migrated the contract to my local blockchain and it worked.

I migrate 2 contracts and 1 library. 1 contract passes correctly, but library fails and contract using library fails as well.


texts: Not enough components (4) in value to assign all variables (6)

texts:
This is an exception on compilation I am getting with truffle.  The code I am running builds a store from a container contract and then makes a call to get a product from it.

Store s = Store(saddress); // saddress is the address of a store created earlier

var (pid,name,price,description,quantity,enabled) = s.getProduct(store.purchases[id].product_id);

In the Store.sol file getProduct is:

function getProduct(uint id) constant returns (uint , string name, uint price, string description, uint quantity, bool enabled){
    return (
      id,
      products[id].name,
      products[id].price,
      products[id].desc,
      products[id].quantity,
      products[id].enabled
    );
  }

Has anyone encountered a similar problem before?


texts:
my purpose is to generate a random key when the smart contract is created and save that key in a private variable. I don't what to know its value either.
Let's take for example the code below:
pragma solidity >=0.4.22 <0.7.0;

/**
 * @title Storage
 * @dev Store value in a variable
 */
contract Storage {

    uint256 private number;

    constructor () public {
        number = uint(keccak256(abi.encodePacked(now, msg.sender))) % 100;
    }
}

Can someone know what the number is? Could some miner repeat the calculation and get the same number?
I deployed this smart contract on rinkeby and I don't see any getters to read the value of number.


texts:
I have deployed smart contracts to ethereum main net using the ethereum wallet and remix etc in the past, however I am about to deploy my first web3js project.

My project would interact with the smart contract only to get a value and send an eth address to the contract. I can get this working when testing on my local.

For final production version, would I need to deploy the contracts in the usual way then connect to the live smart contract by providing the contract address and ABI to web3 and truffle? Or is there another recommended way of doing it? All tutorials and examples I have found only seem to mention projects running on local.


texts: i´m mining now for about 3 days with 3 rigs each with over 50Mh/s, but my balance is still 0. Does anybody know why ?


texts:
I have issued a contract, but it doesn't contain subtract totalsupply logic, I want to modify the original contract, how can I do that with same contract address?

Does some one know? Please help.
Thanks a lot.


texts: Starting a private geth node on android studio?

texts:
I want to start a private node of go-ethereum on android-studio.
I have tried this to start a private node but I am getting the error geth not running:

https://github.com/karalabe/geth-sandbox/tree/master/android_sync/DroidGeth


texts: I wanted to do it on private blockchain crowdsale, I did everything according to the instructions on the site https://www.ethereum.org/crowdsale#unlimited-crowdsale, but when I copied the last code I got an error when trying to compile it. How can I fix it?


texts:
This SC compiles but fails to produce expected results when deployed and having  a transaction sent to it.

I was expecting the line:
"owner.transfer(tokensIssued/1000 szabo);"
to produce a send of 0.00333 Ethers, but produced nothing.

Other parts of smart contract performing as expected.

When I hard code the line in question as:
"owner.transfer(0.00333 ethers);"
it works as expected.

Any tips/guidance appreciated.


texts: So I'm trying to retrieve my REP tokens, yet the JSON key backup that I pull out of my library/ethereum/keystore folder throws an error in the Javascript console saying "your key is not the proper length". Can anybody help me?


texts: Can contracts be executed on PRIVATE-NET?

texts:
Using geth commands, I've created a private blockchain network and two accounts. Using Ethereum Wallet, I've also successfully mined ether using one of the accounts. However, doing any of the following just hangs or sits idle once I kicked it off:

Create a wallet
Transfer ether to the second account
Deploy a custom contract

The wallet creation just spins, as does the contract execution for the custom contract, and the transfer of ether is waiting for confirmation.

Is the reason for all this that other users need to be processing these tasks? In any case, please advise how I can resolve this. Thanks.


texts:
Suppose that you have a contract like this:
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

contract Foo {
  struct UnusedStruct {
    uint256 unusedProperty;
  }

  function someFunction(uint256 foo) external pure {
    foo;
  }
}

Does the unused struct affect the compiler output in any way? Would the bytecode be an exact match if I remove it?


texts: Do I need to garbage collect unused data?

texts:
I have a bunch of mapping{address => uint256) in my contract. I expect that during normal use, these mappings will be added and removed frequently. When a mapping is no longer needed, is it necessary that I explicitly delete it? Or is it ok if I just leave it there? My understanding is that once a mapping is stored, leaving it there will not cause any problems or consume any gas unless it is accessed. Is this correct?

In any other language I would worry about the collection getting big and cluttering things up. But, since everything stored in the whole history is permanent, "deleting" a mapping is actually performing another write to set the value to 0, and will take more space rather than less.

Note: I am aware that this question sounds almost identical to this one, however they are slightly different. I am asking about storage costs, they are asking about how the delete keyword works. The other question also has an accepted "answer" that doesn't actually answer mine at all - they tested in a debugger, and found that their debugger does not retain data once there are no pointers to it in the current scope. As I am not using their debugger, their results might not apply to me. I am specifically asking in the context of the ethereum blockchain, which I'm 99% sure does not have an automatic garbage collector built in... Does it?


texts: Ethereum-PHP Calling contract function with parameter

texts:
I'm not the author of Ethereum part but have to connect to using php. Choosen Ethereum-PHP package (https://github.com/digitaldonkey/ethereum-php). Have connection to ethereum and smart contract but cannot execute smart contract function with parameter successfuly.
I have Schema contract and function test ():

 function test(uint value) public returns(uint) {
return value*2;
 }

and ABI:

...
{"constant":false,"inputs":[{"name":"value","type":"uint256"}],
"name":"test","outputs":
[{"name":"","type":"uint256"}],
"payable":false,"stateMutability":"nonpayable","type":"function"}
...

Now in php I have:

  $eth = new Ethereum('https://kovan.infura.io/<unique address>');
  $schemaContract = new SmartContract($abi, '<contract address>', $eth);

  // Call a function with result : 2
  $result = $schemaContract->test(1)->Val();

I cannot recieve the result. Don't know exactly how to achieve this. Tried many different options like :

$result = $schemaContract->test(1);
$result = $schemaContract->test('1');
$result = $schemaContract->test(1);
$result = $schemaContract->__call('test',1);

But always recieved some error messages.

What am I doing wrong?

Best regards,
TB


texts: Gas usage for same contract is constantly growing

texts:
Here is the smart contract. The gas usage for this contract is constantly growing. All state variables are initialized at deployment and never changed. Signers array is about 2-3 in size no more. And this contract started from using 150,000 gas to right now 600,000.

Is there any visible issue with code?

Here is few transaction ids:

https://etherscan.io/tx/0x26f13d3b3d0809ffc24f22b5f33966aa0c144e433cbe239649df5f00f3d29740  (used gas: 117,013)

https://etherscan.io/tx/0xfcf395bd21ce4e69857184ee3d7b2164f3d0d8536b666dad46d5be8455aed73c (used gas: 681,795)

Code:

pragma solidity ^0.4.24;

contract MultiSigContract {
    mapping (address => bool) public IsSigner;
    address public Executer;
    address[] public Signers;

    function MultiSigContract(address[] _signers, address _executer) public {
        require(_executer != 0x0);
        Signers = _signers;
        Executer = _executer;
        for (uint i = 0; i < Signers.length; i++) {
            IsSigner[Signers[i]] = true;
        }
    }

    function execute(address destination, uint amount, uint8[] sigV, bytes32[] sigR, bytes32[] sigS) public {
        require(sigR.length == sigS.length && sigR.length == sigV.length);
        require(sigR.length == Signers.length);
        require(msg.sender == Executer);
        require(address(this).balance >= amount);

        address[] recoveredAddresses;
        bytes32 txHash = keccak256("\x19Ethereum Signed Message:\n72", this, destination, amount);

        for(uint8 i = 0; i < Signers.length; i++) {
            address recovered = ecrecover(txHash, sigV[i], sigR[i], sigS[i]);
            require(IsSigner[recovered] == true);
            recoveredAddresses.push(recovered);
        }

        for(uint8 j = 0; j < Signers.length; j++) {
            require(contains(Signers[j], recoveredAddresses));
        }

        destination.transfer(amount);
    }

    function contains(address _address, address[] _addressArray) private pure returns (bool) {
        for(uint8 i = 0; i < _addressArray.length; i++) {
            if (_addressArray[i] == _address) {
                return true;
            }
        }

        return false;
    }

    function () public payable {}
}


texts:
I would like to use a mining-pool like nanopool, but I have a Mac - what alternatives do I have?

Is my understanding right, that whenever I want to be part of a mining-pool I need a miner provided by the 'pool-creators' ?

AlethZero is just for solo-mining, right?


texts: How to manually initialize a truffle project? ("truffle init")

texts:
I cannot run truffle init on my company PC. (see Cannot run truffle behind proxy?).

I used a network sniffer and found that the connection was reset when trying to establish an SSL connection to GitHub. My company firewall seems to try to replace the security certificates and caused the problem.

I guess truffle init is trying to clone the scaffold source code from the GitHub? It seems there are only eight files (four of them are mandatory) in four directories. How to manually download them?

Will truffle compile and migration need to access sites which need SSL?


texts: ethereumj.starter running locally but bestBlock always remains at 0

texts:
I ran the following commands to get ethereumj.starter code and run it.

%> git clone https://github.com/ether-camp/ethereumj.starter
%> cd ethereumj.starter
%> ./gradlew run

From the log file and console output, I could see that the node started up, connected to peers and was also syncing. However, in another terminal window, the output of the following command was always 0, as shown below.

%> curl -w "\n" -X GET http://localhost:8080/bestBlock
0

This was despite the log file showing transactions being received, and also having logged messages like the following, with some high block number listed as best block ....

Peer V63: [ 267c54b3,    NODE_RETRIEVING, ping     95 ms, difficulty 270944163663211043882, best block 3723188 ]: (idle 3s of 20s) Geth/v1.6.0-stable-facc47cb/windows-amd64/go1.8.1    Nodes/sec: 3681.86, miss: 0.00

Am I missing something here? Shouldn't the best block number reported by the curl command be increasing with time as the local node gets sync'ed?


texts:
I am facing problem with bytes32.

Here is my sample contract:

pragma solidity ^0.4.16;

  contract Test {

    bytes32 public input;
    function test(bytes32 _in) public {
    input = _in;
  }
}

The problem is in truffle dev, no matter how I run the test function, the input value is the same. For example, if I run:

  MyContract.deployed().then(inst => { inst.test(12, {from: >web3.eth.accounts[0]}) });

Then I get the result:

  truffle(develop)> MyContract.deployed().then(inst => { return >inst.input.call() });
  '0xc000000000000000000000000000000000000000000000000000000000000000'

Also, if I run:

  MyContract.deployed().then(inst => { inst.test("12", {from:
  web3.eth.accounts[0]}) });

The result is the same:

  MyContract.deployed().then(inst => { return inst.input.call() });
  '0xc000000000000000000000000000000000000000000000000000000000000000'

I don't think it's normal..
Any ideas what I might be doing wrong?

Thanks


texts: Link my backend rpc server with front end web form applications

texts: I am using azure, i have 2 resources - one is the web form app (visual studio)and other one is the ubuntu vm running geth. I tried alot of things to make the front end to connect with the backend. Is there any way that the rpc server can be made accessible by the front end web app on azure. Or is there any way to make the server on the internet so that i can connect to it. Or is there any easily available open node?


texts: Safely checking transaction origin account

texts:
I have the following scenario.

Contract A {
  mapping (address => bool) public allowed;
  mapping (address => uint) public userData;

  function doSomething(address _user) public returns(bool){
    if(allowed[_user]){
      userData[_user]++;
      return true;
    } else
      return false;
  }
}

Contract B {
  function doSomethingWithA(){
     A contractA = A(_Aaddress);
     if(contractA.doSomething(msg.sender))
       // Do something
     else
       // don't
  }
}

Contract A holds a mapping of which users are allowed to interact with it.
Contract A has a function that should only be called by contract B.

ONLY the EOA interacting with B should be able to execute A's doSomething().

In the current scenario, anyone could call doSomething(address _user) and pass an allowed _user to get a valid result.

I could require(msg.sender == _user); in doSomething(address _user)  but that would cause the function to fail as the msg.sender would always be contract B.

I know I could use tx.origin instead of msg.sender, but I was wondering if that would compromise the security of the contract.

So, my questions are:

Is there any other way to solve this without using tx.origin?
If the only way is with tx.origin. What should I have in mind in order to prevent an attack related to the usage of tx.origin?


texts: Getting current user balance of an aToken for a specific asset in AAVE v2 protocol

texts:
As AAVE protocol V2 documentation says:

aTokens are interest-bearing tokens that are minted and burned upon deposit and withdraw. The aTokens' value is pegged to the value of the corresponding deposited asset at a 1:1 ratio, and can be safely stored, transferred or traded. All interest collected by the aTokens reserves are distributed to aTokens holders directly by continuously increasing their wallet balance.

After depositing some amount of an ERC-20 token such as DAI, I need to know the current aToken balance of a user for the same asset (DAI in this case), so that I would be able to calculate user investment's profit.
It is also mentioned in the documents that there is an IProtocolDataProvider interface with a getUserReserveData method which gives asset address as well as the user address as arguments and returns currentATokenBalance as part of the return value. However, I could not find the aforementioned smart contract file in AAVE protocol V2's GitHub. Did it change silently overnight and documents are not getting the new updates yet? Am I doing the right thing for getting a user's current aToken balance? If not, what is the correct way of doing that?


texts: Call a function in meteor wihout confirmation in metamask

texts:
I am working on university project and this is the only and last point i need your help. I want to call automatically a state-changing function in meteor without the submit confirmation in metamask. Therefore i read about using ethereumjs-tx but i don't know how to sign the method call to get this smart contract method automatically running. Pleas i can't find a answer anywhere:
The current code i have in my script:

global.Buffer||require("buffer").Buffer;
const EthereumTx = require('ethereumjs-tx')
const privateKey = Buffer.from('my private key', 'hex')
const txParams = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: contractAdress,
  value: '0x00',
  data: contractdata,
  // EIP 155 chainId - mainnet: 1, ropsten: 3
  chainId: 3
}
const tx = new EthereumTx(txParams)
tx.sign(privateKey)
const serializedTx = tx.serialize()

How has the method call look like, something like this?
myContractInstance.setFinised(true, what to insert here?, function(err, res){});


texts: Storing private data that will be decrypted by a smart contract

texts:
Another private data problem!

I would like to store some data in a Smart Contract, encrypted so nobody can see it upon some specific condition (time, or whatever).

For instance, after one year, this data could be decrypted and revelead, by the contract.
One way to do it is to use an Oracle (I have a functioning version using Oraclize.it) where the data is encrypted using Oraclize.it public key, and decrypted by the contract by a call to the Oracle. The partial security is that only the smart contract call call the Oracle with this data, but the weakness is now Oraclize.it, the service....

There is one discussion here: Is there a strategy for keeping data "private" and then releasing it programmatically but as I said, the issue is that Oraclize.it might not be secure enough (it's a single point of failure)

What are alternative to achieve the same goal?
Is there a way to store encrypted data somewhere that can be only decrypted by a smart contract? It seems that IPFS can not restrict the access of file to a single smart contract


texts: Getting this error when I run a test on truffle : sets the total supply upon deployment

texts:
When I try to run a test from truffle, I got this problem, here my test js code:
var YarockToken=artifacts.require("./YarockToken.sol");
contract('YarockToken',function(accounts){

var tokenInstance;

it('set the total supply upon deployment', function(){
    return YarockToken.deployed().then(function(instance){
        tokenInstance=instance;
        return tokenInstance.totalSupply();
    }).then(function(totalSupply){
        assert.equal(totalSupply.toNumber(),1000000,'sets the total supply to 1,000,000');
        return tokenInstance.balanceOf(accounts[0]);

    }).then(function(adminBalance){
        assert.equal(adminBalance.toNumber(),1000000,'it allocates the initial supply to the admin account');
    });
});
});

and here my contract code:
pragma solidity ^0.5.16;

contract YarockToken{
//Constructor
//Set total number of tokens
//Read the total number of tokens
uint public totalSupply;

mapping(address=> uint256) public balanceOf;

constructor(uint256 _initialSupply) public{
    balanceOf[msg.sender]=_initialSupply;
    totalSupply=_initialSupply;
}

}

and here is the result of the test
❰C❙~/token_sale(git:master)❱✘≻ truffle test
Warning: Both truffle-config.js and truffle.js were found. Using truffle-config.js.
Using network 'test'.

Compiling your contracts...
===========================
> Compiling ./contracts/YarockToken.sol
> Artifacts written to /var/folders/v2/b8d1nl855pnd92c67c95j4nc0000gn/T/test--88304-0azTwJ2IV7q2
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

Warning: Both truffle-config.js and truffle.js were found. Using truffle-config.js.

  Contract: YarockToken
    1) set the total supply upon deployment
    > No events were emitted

  0 passing (149ms)
  1 failing

  1) Contract: YarockToken
       set the total supply upon deployment:
     ReferenceError: accounts is not defined
      at /Users/Kantemirovs/token_sale/test/YarockToken.js:13:35
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

Can someone please help me with this issue?


texts: How can developers test time-dependent contracts?

texts:
I'm working on a revenue distribution contract that lumps eth by week. In order to test it, I need some way to set the now variable. Is there any way to do that?

Using solidity/geth.


texts: Ethereum TX Fees/Gas Gambling Calculation

texts:
I'm wondering if there's a better way of handling the transaction fee limit. As I understand it at the moment, it's basically a gamble. You wager an amount. If it is too low, you lose it all when it gets rejected and returned. Set it too high and you waste money on faster processing you didn't want.

How can I set a sensible amount? Must I rely on online calculators to make the guess for me?

I sent 0.01 Eth with a 0.0003 fee, and it's been stuck for days, I'm guessing insufficient fee and thus rejected.


texts:
I'm trying to use the Infura or any other public provider to compile and migrate a simple test contract.

I don't get any errors when I run

truffle compile --network test

but it seems to hang and never complete

same with

truffle migrate --network live

here is a copy of my truffle.js (the mnemonic is made up in the below)

var bip39 = require("bip39");
var hdkey = require('ethereumjs-wallet/hdkey');
var ProviderEngine = require("web3-provider-engine");
var WalletSubprovider = require('web3-provider-engine/subproviders/wallet.js');
var FiltersSubprovider = require('web3-provider-engine/subproviders/filters.js');
var Web3Subprovider = require("web3-provider-engine/subproviders/web3.js");
var Web3 = require("web3");
var mnemonic = "know give beef link depth liberty fish forward ketchup fog either faculty";
var hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));
var wallet_hdpath = "m/44'/60'/0'/0/";
var wallet = hdwallet.derivePath(wallet_hdpath + "0").getWallet();
var address = "0x" + wallet.getAddress().toString("hex");
var provider_url = "https://testnet.infura.io/";
var engine = new ProviderEngine();
engine.addProvider(new WalletSubprovider(wallet, {}));
engine.addProvider(new FiltersSubprovider());
engine.addProvider(new Web3Subprovider(new Web3.providers.HttpProvider(provider_url)));
engine.start();

module.exports = {
  networks: {
    test: {
      network_id: 3,
      provider: engine,
      from: address
    }
  }
};

And my package.json is

    {
  "name": "Infura Test",
  "version": "1.0.0",
  "description": "",
  "main": "truffle.js",
  "directories": {
    "test": "test"
  },
  "devDependencies": {
    "bip39": "^2.3.1",
    "ethereumjs-wallet": "^0.6.0",
    "truffle": "^3.4.5",
    "web3": "^0.18.2",
    "web3-provider-engine": "^13.2.8"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "@bkawk",
  "license": "ISC"
}


texts: Call and send transaction function call without having to build transaction [web3.py]

texts:
Right now, when I want to send a transaction, I have to build it, sign it, and then send it like so:
function_call = contract.functions.function_call(parameters)
transaction = function_call.buildTransaction({'chainId': 42,
                                                  'from': my_address,
                                                  'nonce': nonce})
signed_txn = w3.eth.account.sign_transaction(transaction, private_key=os.getenv('PRIVATE_KEY'))
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)

This seems like a lot more work than what could be done. Is there a way to do something like:
contract.function_call(parameters, {'from': private_key})

Like in brownie's syntax?


texts: What signatures will be used for Casper bets?

texts:
In this blog post, Vlad Zamfir describes a bet as a object with a signature.

What kind of signature will Casper bets have? What is the length (in bytes) of those signatures?


texts: How to programatically change the current network with MetaMask

texts: I would like to have a button that switches between main net and ropsten on my app, in order to do so I need to programatically change the current network with MetaMask. But I cannot find aby reference about this. Do you guys have any idea on how to achieve this?


texts: I bought some ETH off CEX.io upon the recommendation of a couple friends, and tried to transfer it to my wallet in Bitfinex. This transfer was done around 24 hours ago and yet the transaction hash does not exist. CEX on Twitter announced that it stopped all ETH transactions and blames it on some "error on the blockchain". Did I just get screwed?


texts: Why incorrect number of tokens are sent according to the current rate to the contributor.?

texts:
Token Contract
https://ropsten.etherscan.io/address/0x6f5c43f62b4b18aa8ed37b42f2804f7049cbe0e9#code

CrowdSale Contract
https://ropsten.etherscan.io/address/0x9b94e1894abe2051e6e96bf1b57fe5d3adbbc5aa#code

Environment == Injected Web3 Ropsten MetaMask/Remix

Call Functions as follow :

setTokenOffering (offeringAddr: CrowdSale address),
Sent 0.1 ETH TO CrowdSale contract (successfull),
-amountRaised == 0: uint256: 100000000000000000
-balanceOf == 0: uint256: 100000000000000000
-tokenBalanceOf == 0: uint256: 680000000000000000000 / rate = 0: uint256: 6800

3.enableTransfer,

4.Transfer (to tokenReward address == 210 000 000 PDT ) (successfull),

5.approve (allowance == 210 000 000 PDT),

6.transferFrom (from:owner address, to: rewardAddress, value:0 (only with value "0" works)
Im not sure about that !, but is Success;

It shows me 0.1 PDT instead of 680 PDT.

Has anyone seen something similar and could help me overcome this problem.

I am asking for a straightforward answer. Thank You.Robert

7.(fallback) and "buy" give me "Gas estimation failed".


texts: Is it necessary to have the UDP port open for an Ethereum private net?

texts:
An Ethereum node requires both TCP (listener) and UDP (discovery) port (usually 30303) open and reachable by other nodes.

My question: is it possible to run a private network with my node only reachable by the peers via TCP port 30303, if those peers configure my node as a bootnode?

geth --bootnodes "enode://myID@myIP:30303"

Or will the peers drop my bootnode if only it's TCP but not the UDP port 30303 is reachable?

(edit: tried running it with TCP only and it seemed to work fine, so just want to make sure I don't miss anything)


texts: How do I convert an Exodus CSV private key export to JSON for Mist?

texts:
I have a csv file that was exported from the EXODUS app with the following columns:

  ADDRESS   PATH    BALANCE PRIVKEY

Is there a way to get this into json format standard so that I can import it in Ethereum Wallet?


texts: How do I simulate multiple users in a remix unit test?

texts:
In the following example, I want to test the assignVoter functionality with Remix unit test plugin. assignVoter should only be called by the owner.
pragma solidity >=0.4.22 <0.7.0;

contract Ballot {
    address owner;

    constructor() public {
        owner = msg.sender;
    }

    function assignVoter(address voter) public {
        require(msg.sender == owner);
    }
}

pragma solidity >=0.4.22 <0.7.0;
import "remix_tests.sol";
import "remix_accounts.sol";
import "../Ballot.sol";

contract BallotTest {
    Ballot private ballot;

    /// #sender: account-0
    function beforeAll() public {
        ballot = new Ballot();
    }

    /// #sender: account-1
    function testAssignVoter() public payable {
        ballot.assignVoter(TestsAccounts.getAccount(1));
    }
}

Remix provides the functionality of custom msg.sender of transaction using devdoc (NatSpec). In this example, such an annotation makes the unit testing framework call the testAssignVoter method with 0-th test account. In turn, the creation of the Ballot contract and the call to assignVoter --- both are made by the BallotTest contract; neither by account-0 or account-1. Therefore, I am not being able to simulate the situation where the Ballot contract is created by one account (account-0), and the assignVoter is called by another (account-1). Specifically, I want to simulate the failure scenario by hitting the require predicate. How can I achieve that?


texts:
Is it possible to use the name of the local variable of contract with sload code ?

contract Test {
  int a=999;
  function doIt() {
    assembly {
    sload(a);
    }
 }
}


texts: Can I use require() to ensure several function calls to other contracts are successfully executed in sequence?

texts:
Or is the only way to do this:

  Use delegatecall/assembly to access non-variably-sized function return
  values & validate that each function is executed successfully.

In other words:

Is the only way to verify the result of functions at runtime by checking out the state of the “Delegate” contract?

Thank you.


texts: Ethereum Merkle Patricia Trie (Extension node)

texts:
I do not have time to look through the source code right now. My questions is:
In Ethereum, when is the decision to replace part of a given path with an Extension-node made?

I suppose the sole idea of extension nodes is to limit the number of situations where leaf nodes would share the same sequence of nibbles.

Would you describe the algorithm in short?
I have two ideas in mind

1) create the trie in an unpacked manner then try to replace some of the paths using a compression algorithm which would replace some of the paths with 'extensions'. This would effectively introduce a second pass to the overall procedure and increase memory usage.

2)I've gone with a different approach and I construct the trie using largest blocks and divide when required. In this approach, I guess, when adding a new node to the trie, I would need to runforth down each branch of the sub-trie just to check if it is worth it to put an extension node just below the current branch and remember the (1-branch-N-Leafs set) which needs to be added to it. Is this the case with Ethereum? Looking forward to your reply and in the meantime, I'll implement this scenario. I am not sure if this approach would produce the optimal result when compared to the offline-second-pass-with-compression method.

So the question holds - when does the Ethereum's Trie construction algorithm decides to combine two or more paths into one extension.


texts: Can a Smart Contract receive and send E-Mails?

texts: As the title states, I would like to know whether one could create a smart contract on Ethereum that is able to send and receive E-Mails.


texts: eth-lightwallet example for keystore.addHdDerivationPath()

texts:
Can someone give an example of how to use the keystore's addHdDerivationPath() method, that actually runs properly?
The code I have below (using the default hdPath) is giving a strange error

lightwallet.keystore.deriveKeyFromPassword(password, function(err, pwDerivedKey) {
    let ks = new lightwallet.keystore(seed, pwDerivedKey);
    console.log(ks.isDerivedKeyCorrect(pwDerivedKey));//true
    ks.addHdDerivationPath("m/0'/0'/0'", pwDerivedKey, {curve: 'secp256k1', purpose: 'sign'});
})

EDIT: OK, I solved it myself - turns out my hdDerivationPath is wrong - it had a "/i" at the end (in my local version), which somehow caused the KS's encSeed to reset to undefined, and the error above.
The code snippet I posted above actually works.


texts: How does the User sign Ethereum transactions when interacting with blockchain via an web3j-based intermediate API?

texts:
We have a private Ethereum network running in our testbed. And a web3j-based (Java) API exposes various functionalities to the deployed smart contracts on the blockchain. The API connects to the blockchain using its own Ethereum identity/credentials.

A frontend application (under development) will be interacting with the blockchain via the web3j-based API. We might also use Metamask for user wallet management at the frontend app.

Our current concern is that all the transactions currently fired to the Ethereum blockchain are sent using the API's identity (msg.sender or tx.origin within the smart contracts). Is there a way where the end user doesn't have to pass on their credentials to the API but just authenticate/authorize/sign the transactions and the API can submit the transactions on the user's behalf to the Ethereum blockchain?

We're very new in this direction and would appreciate any help.
Thank you in advance!


texts: How to handle Ropsten's smart contracts with Truffle?

texts:
I work with Truffle, Metamask, and Windows PowerShell. I deployed my smart contract to Ropsten with Truffle by the below command in PowerShell:
truffle migrate --network ropsten

Now, I need to interact with the deployed contract. Is it possible to handle Ropsten's smart contract with Truffle from PowerShell? if yes, Please guide me.
Thanks.


texts: This question is related to my previous question: can I run an online forum on Ethereum, or a stand of free books on a given topic? Could these be considered blockapps? Thanks.


texts: What is the keccak256 reference in opcodes from solc?

texts:
Opcodes -
Opcodes:

  PUSH1 0x60 PUSH1 0x40 MSTORE CALLVALUE ISZERO PUSH1 0xE JUMPI PUSH1
  0x0 DUP1 REVERT JUMPDEST PUSH1 0xA0 DUP1 PUSH2 0x1C PUSH1 0x0 CODECOPY
  PUSH1 0x0 RETURN STOP PUSH1 0x60 PUSH1 0x40 MSTORE PUSH1 0x4
  CALLDATASIZE LT PUSH1 0x3F JUMPI PUSH1 0x0 CALLDATALOAD PUSH29
  0x100000000000000000000000000000000000000000000000000000000 SWAP1 DIV
  PUSH4 0xFFFFFFFF AND DUP1 PUSH4 0xC9116B69 EQ PUSH1 0x44 JUMPI
  JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST CALLVALUE ISZERO PUSH1 0x4E
  JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x54 PUSH1 0x6A JUMP
  JUMPDEST PUSH1 0x40 MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2
  POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH1
  0x0 PUSH2 0x370 SWAP1 POP SWAP1 JUMP STOP LOG1 PUSH6 0x627A7A723058
  KECCAK256 PUSH20 0x982391380BF2F8F878474D86DEC86AD0305FF533 0xd7 0xb9
  PUSH28 0xD93A3F18E8ACEFB40029000000000000000000000000000000000000

Code -

pragma solidity ^0.4.18;

contract d8 {

    function myBalance() pure public returns (uint) {
        return 880;
    }

}

How to get -

solc --opcodes d8.sol

I assumed at first it was the source code hashed but apparently not after I checked here - https://emn178.github.io/online-tools/keccak_256.html

So it must be a hash of something.

Does anyone know?


texts: eth.getBalance(eth.accounts[0]) Shows me 0 balance though my syncing is still Running

texts:
I am using geth on windows with 1.9.10 version.

I used geth --rinkeby --rpc --rpcapi="personal,eth,network,web3,net" command for launch my  geth.

I am on the Rinkeby testnet, i already transfer 3 ether through https://faucet.rinkeby.io/, to my 0xf80a5cd42ff3a5d154399c83376ce99323e3ff69 address. And on etherscan it also shows me that transaction has been done. But when I tried to see in the geth console through eth.getBalance(eth.account[0]) command, it showed me 0 balance. I tried too many times, but still it shows me 0 balance. When I try to eth.syncing, I am on the 3259367 current block and in my etherscan transaction block is 5846638. So why it's shows me 0 balance?

Do I need to Syncing all nodes till 5846638 in my local computer ? or there are any thing that I am missing?


texts: Compile errror in remix doesn't make the thing clear

texts:
Doing lesson 5 from here how to write smart-contract, lesson 5 I got compile error in remix. It goes:

  browser/ballot.sol:40:2: ParserError: Expected pragma, import
  directive or contract/interface/library definition.  function
  approve(address _spender, uint _value) public constant returns (bool
  success){

and the full code is:

pragma solidity ^0.4.18;

contract SimpleTokenCoin{

string public constant name = "Simple Coin Token";

string public constant symbol = "SCT";

uint32 public constant decimals = 18;

uint public totalSupply = 0;

mapping (address => uint) balances;

function balanceOf(address _owner) public constant returns (uint balance){ return balances[_owner]; }

function transfer(address _to, uint _value) public returns (bool success){ if(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]){ balances[msg.sender] -=_value; balances[_to] += value; Transfer(msg.sender, _to, _value); return true; } return false; }

function transferFrom(address _from, address _to, uint _value) public returns (bool success){ if(balances[_from] >= _value && balances[_to] + _value >= balances[_to]){
balances[_from] -=_value; balances[_to] += value; Transfer(_from, _to, _value); return true; } return false; } }

function approve(address _spender, uint256 _value) public constant returns (bool success){ return false; }

function allowance(address _owner, address _spender) public constant retuns (uint256 remaining){ return 0; }

function mint(address _to, uint _value) public { assert(totalSupply + _value >= totalSupply && balances[_to] +_value >= balances[_to]); balances[_to] += _value; totalSupply += _value;
}

event Transfer(address indexed _from, address indexed _to, uint value);

event Approval(address indexed _owner, address indexed _spender, uint _value);
}


texts: I do not understand the definition used to update a mapping stored inside a struct type as explained below

texts:
struct Payment {
 uint amount;
 uint timestamp;
 }

 struct Balance {
 uint totalBalance;
 uint numPayments;
 mapping(uint => Payment) payments;
 }

 mapping(address => Balance) public balanceReceived;

function sendMoney() public payable {
 balanceReceived[msg.sender].totalBalance += msg.value;

 Payment memory payment = Payment(msg.value, now);
 balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPa
yments] = payment;
 balanceReceived[msg.sender].numPayments++;
 }

In the above smart contract, why is this the definition used to add to the payments mapping inside the Balance struct:
balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;

and not:
balanceReceived[msg.sender].payments[_index] = payment;

Where is the connection with numPayments in the balance struct with obtaining the key


texts: TypeError: Data location must be “memory” for parameter in function, but none was given

texts:
Contract fail to  compile in IDE Remix.due to the following error:

  TypeError: Data location must be "storage" or "memory"  for parameter
  in function, but none was given.

version:0.5.6+commit.b259423e

I have no idea why this happened and i have not found any sufficient information on how i can fix it and was hoping you can help me. Thank you in Advance.

The error points to this function:

function bytesToAddress(bytes bys) pure private returns(address addr) {
        assembly {
            addr := mload(add(bys, 20))
        }


texts: Removing Array Element by Copying to Temp Array

texts:
I read you can delete an array element like this:
How to delete an element at a certain index in an array?

I was wondering if I can do it this way too:

  function playerUnjoins() {
    address[] newActivePlayers;
    for (uint32 index; index < activePlayers.length; index++) {
      if(msg.sender == activePlayers[index])
        newActivePlayers.push(activePlayers[index]);
    }
    activePlayers.length = newActivePlayers.length;
    activePlayers = newActivePlayers;
  }

This is shorter and looks more readable. activePlayers is an array of address stored in the blockchain.

Question

Is it possible? I get this warning:

When I write it with address[] memory newActivePlayers; I get (in https://ethereum.github.io/browser-solidity/#version=soljson-v0.4.2+commit.af6afb04.js):

Untitled:94:9: Error: Member "push" is not available in address[] memory outside of storage.
        newActivePlayers.push(activePlayers[index]);
    ^-------------------^


texts: Exucution of a payable function does not transfer any value between accounts when executing event on Ganache

texts:
I have created an smart contract that sends value from one account to another when calling the following function:
function buyEnergy(uint _sellOrderId, address _sellerAddress ) public payable /*isOwner*/{
    uint totalPrice=getTotalPriceOffer(_sellOrderId);
    uint unit = getUnitOffer(_sellOrderId);
    uint pricePerUnit = totalPrice/unit;

    //check the agent has been accepted on the exchange
    require(getExchangeRegistrationStatus()==true, "You are not a member of the exchange");

    //check the offer is still available
    require(getAvailabilityOffer(_sellOrderId)==true, "The sell offer is no longer available");

    //check the buyer is sending the required amount of money (no less or more)

    require(msg.value == totalPrice, "Please, send the exact amount of money");

    //make the payment
    _sellerAddress.transfer(msg.value);

    //register the buy operation in the exchange
    ee.saveBuyOrder(agentAddress,unit, pricePerUnit,totalPrice,_sellOrderId);
}

As you can see, //make the payment should transfer the money. When I tested that on both Remix and Truffle this was working fine.
But now the function is executed with no errors when called but the transfer of value does not happen (the last method its well executed because I can see the data added into the Blockchain). See how I call the function from the web:
async agentBuyEnergy(){

  let contractInstance = await this.getAgentInstance();

  await contractInstance.buyEnergy(this.state.inputSellOrderId,this.state.inputSellerOrderAddress ,{from:this.state.account,value:this.state.inputOfferTotalPrice},function(error,result){
    if (error){
      console.log("the error is",error);

    }
    else {

      console.log('successfull buy',result);

    }
  }.bind(this));

}

As you can see the value passed to the Solidity function is fetched from the web, but if I hardcoded a value happens the same.
Any ideas? I think that the problem is with how metamask process the value:

See the value set to 0. It is like specifing the value from react does the trick but not ethers are sent.
Thanks


texts: JavaScript console on Parity: cannot execute commands (by pushing Enter button)

texts:
I am trying to open my Parity in Chrome after having set it up in internet explorer.

When I do so, it wants me to generate a new token:

  "Unable to make a connection to the Parity Secure API. To update your secure token or to generate a new one, run parity signer new-token and paste the generated token into the space below."

I fire up the Parity/Web3 console and type the command. When I push "enter" nothing happens. I cannot execute commands in the console. I just want to access the same data except through Chrome and not Internet Explorer.

Does anyone know why this might be happening?


texts: Duplicate data in "returnValues" field of event emitted in solidity script

texts:
I am using quoram distribution through Azure blockchain service.. we are emitting few events according to our logic and these events are being used to get specific data from the transaction.. though we see that the data in each event is duplicated.

Event declaration in solidity -

event Added(
    address sender,
    string Key,
    string ControlNumber,
    string Content,
    Status Status,
    uint256 Index,
    string epochdatetime
);

Sample data emitted by the event :

{
    "address": "0xdummyaddress",
    "blockNumber": 298905,
    "transactionHash": "0xdummyhash",
    "transactionIndex": 0,
    "blockHash": "0xdummyhash",
    "logIndex": 0,
    "removed": false,
    "id": "log_1",
    "returnValues": {
        "0": "0xdummysenderAddress",
        "1": "110_E222222222",
        "2": "222222",
        "3": "content",
        "4": "0",
        "5": "11",
        "6": "1585329530",
        "7": "111113",
        "sender": "0xdummysenderAddress",
        "Key": "110_E222222222",
        "ControlNumber": "222222",
        "Content": "content",
        "Status": "0",
        "Index": "11",
        "epochdatetime": "1585329530"
    }
}

If you notice the returnValues is having duplicate data.. first it is using numbered keys ("0") for emitting the data, then it is having the same data, but key name is now same as what we defined in event definition ("sender" is same as "0").

Is there any way to suppress the numbered keys?


texts: web3.personal.newAccount() successfully created but not listed in ganache accounts.why?

texts:
I am using truffle framework for Dapp development and I am new in Blockchain.I used the command
    web3.personal.newAccount()
to create a new account.

But i cannot view this account when i take ganache ui. It still keeps showing the initially created 10 accounts.

1)How to get the list updated?
2)isn't the command web3.personal.newAccount() creating  the new account on my local blockchain?if isn't which list is web3.eth.accounts showing?
3)This code is part of an election Dapp.I cannot make a transaction after adding this account it is showing "failed".

Thanks in advance:-p


texts: Is it fine to use Ganache in a staging environment?

texts:
We are currently using Rinkeby in our staging environment, but planning to stop using it cause it doesn't make sense as our application will communicate with a private Ethereum network when it goes to production.

It seems that Ganache is the right tool to use, but after reading about it seems that people recommend using it as short lived environment only to run tests.

My question is: Is it fine to use Ganache as a long lived staging environment simulating a private ethereum network?


texts: Solc: Build from source code failed. Error: ‘mod’ is not a member of ‘z3’

texts:
I tried to build solidity compiler (solc) from source code, which was cloned from Solidity Git Repository. I followed the instructions in Solidity Documentation, but I ran into an error when execute: cmake .. && make. The cmake error is as follows:

[ 42%] Building CXX object libsolidity/CMakeFiles/solidity.dir/formal/Z3Interface.cpp.o
/my/path/to/solidity/libsolidity/formal/Z3Interface.cpp: In member function ‘z3::expr dev::solidity::smt::Z3Interface::toZ3Expr(const dev::solidity::smt::Expression&)’:
/my/path/to/solidity/libsolidity/formal/Z3Interface.cpp:166:14: error: ‘mod’ is not a member of ‘z3’
   return z3::mod(arguments[0], arguments[1]);
              ^~~
/my/path/to/solidity/libsolidity/formal/Z3Interface.cpp:166:14: note: suggested alternative: ‘cond’
   return z3::mod(arguments[0], arguments[1]);
              ^~~
              cond
libsolidity/CMakeFiles/solidity.dir/build.make:1166: recipe for target 'libsolidity/CMakeFiles/solidity.dir/formal/Z3Interface.cpp.o' failed
make[2]: *** [libsolidity/CMakeFiles/solidity.dir/formal/Z3Interface.cpp.o] Error 1
CMakeFiles/Makefile2:389: recipe for target 'libsolidity/CMakeFiles/solidity.dir/all' failed
make[1]: *** [libsolidity/CMakeFiles/solidity.dir/all] Error 2
Makefile:129: recipe for target 'all' failed
make: *** [all] Error 2

I have installed z3 prover with pre-built binaries (version 4.8.4 - 64 bit - build hashcode d6df51951f4c) provided here and z3/bin has been included in my PATH variable.

I was using Ubuntu 18.04.

Did I install z3 in a wrong way? Solidity Documentation mentions that z3 is optional, so I don't think this error is related to my z3 installation.

Can anybody help? Thanks very much!


texts: Concatenation of different datatypes and hashing it

texts:
How can I concat two different datatypes and then hash it?
for example: sha3(int8 + address)

Or it is also good for me hash them separately, and then  hash together.
like this: sha3(sha3(int8) + address)

How to do that most efficient way?


texts: Can somebody check my understanding of DApps and Smart contracts

texts:
can somebody check my understanding on DApps and smart contracts in general? (Please excuse the long winded-ness I’ve only been reading about DApp’s for 3 days now so I’m very new and I’m kind of walking myself through how it works as I’m talking about)

My current understanding of smart contracts says that when any processing takes place on the EVM, there’s a certain amount of gas required for the work done. That gas is paid in a certain amount of ETH, determined by whomever initiated the transaction.

This makes sense to me in regular ETH transactions and smart contracts. In order to run your code or send your ETH you pay a small fee for the work done to make that transaction happen. Cool. That’s not much different from bitcoin.

But then when you add DApps and, by extension, tokens into the mix, it gets a little more complicated.

Let’s say I have a DApp that runs a decentralized version of Runescape or something. Let’s say the DApp uses RUNE as it’s token.

In the RuneScape DApp’s ico, I set some arbitrary amount to be what RUNE is worth in ETH. People buy a bunch of RUNE using ETH and all of this ETH is stored in the contract itself, which is then itself used as gas to fuel the DApp on the platform.

The RUNE token allows certain utility on the RuneScape DApp, such as allowing the use of certain spells or dungeons or whatever. This utility can be converted into real-world value (entertainment value in this case), and thus the RUNE token is worth something. The token can be mintable or non-mintable depending on the architecture of the DApp.

Once people have access to the token and circulation becomes regulated, the market will begin to determine the value of these tokens. At this point you have your fully fledged erc20 token and DApp.

Is this correct? Or do I have something mixed up somewhere?

Also, how does one ensure that their DApp doesn’t have the gas in the contract expended if no more ETH is being added to the contract in the case of a non-mintable token?


texts:
I have been trying to connect remix to my machine and I have tried the following command:
remixd -s ./contracts --remix-ide http://remix.ethereum.org
Also, I have tried the https and other combinations which are mentioned here
but, still I have not been able to connect to the remix and sometimes it shows me Connection from origin http://remix.ethereum.org rejected. but sometimes it doesn't mention if it has been connected to the remix or not.
I have tried both the old and new version of remix but the problem persists on both.


texts: Private Clique network, where can I get block sealer and block reward?


texts: Simple contract to contract token transfer failing

texts:
I'm trying to write a contract that combines two different function calls into one transaction, for which I then can hopefully use the CHI gas token. However, for now I can't even get my contract to make a simple uniswap trade.
  contract ProxyChi {
     Uniswap uni = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

     function simpleTradeCall(uint amtTkIn, uint amtTkOut, address[] memory path) public returns (uint[] memory amounts){
     return uni.swapExactTokensForTokens(amtTkIn, amtTkOut, path, msg.sender, now+120);
    }
 contract Uniswap{
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
}

Anytime I want to make a trade in remix, I get the TOKEN_FROM_FAILED problem. I've approved the ProxiChi contract for the outgoing token. Is this just a uniswap specific thing, or am I doing something wrong? My mainnet functions don't have arguments, but do spend tokens. I pass the path as ["addr1", "addr2"] in remix. Is there maybe some other contract I can try that spends a lot of gas (on ropsten)? Thanks!


texts: What happens if a token symbol has four letters? Do exchanges display it as only first three letters, don't display it at all or? If they display only first three letters I would have a problem with duplicates... Should I be ok with 4 letter symbol on exchanges? If somebody can explain. Thanks. (and yes I checked similar threads but found not what I was looking for)


texts: Parity Mnemonic or Keyfile not compatible with MEW?

texts:
I'm on a new computer and I have 2 ETH addresses I created on parity in december 2017 and february 2018. Now I thought I followed the plan on what to do to secure the addresses but when I enter the 12 words Mnemonic in MEW and give the password, it claims the Mnemonic isn't correct. "Invalid Mnemonic".

Is it incompatible?

Greetings!


texts: How does the Microsoft Azure Ethereum Blockchain as a Service differ from the platform offered by Eris Industries?

texts:
On Nov 2015, Microsoft announced with ConsenSys, the addition of Ethereum Blockchain as a Service (ETH-BaaS) on their Azure platform.

Meanwhile, Eris Industries also have been offering, what appears to be, at first sight, a similar hosted Ethereum platform.

From the marketing collateral, it is difficult to do establish what the key distinctions are between the two platforms. Any one with direct experience using either or both of these platforms can distill what the key differences are?


texts:
I've written a simple ether forwarding contract coupled with a sweep function which when called automatically, sweeps all tokens of specified token contract address to pre-defined recipient addresses.
Would like to seek solidity experts and audit assistance to vet thru the integrity of the code and if it's "relatively" safe to be used in production.
pragma solidity ^0.5.16; //declare solidity version to use

//Standard interface functions for erc20 token contracts
contract ERC20 {
    function balanceOf(address _owner) public view returns (uint balance);
    function transfer(address _to, uint _value) public returns (bool success);
}

contract SweepFunds {

    //address declaration
    address payable public merchant = RECIPIENT_ADDR; //merchant account
    address payable public admin = ADMIN_ADDR; //admin account

    //Events Logging
    event LogForwardedEther(uint total, address indexed merchant, uint merchVal, address indexed admin, uint adminFee);
    event LogForwardedToken(uint total, address indexed merchant, uint merchVal, address indexed admin, uint adminFee, address indexed token);

    //Fallback function; Gets called when Ether is deposited, and forwards it to merchant and admin
    function() external payable {
        transferFunds(msg.value);
    }

    //It is possible that funds were sent to this address before the contract was deployed; flush those funds to the designated addresses.
    function flushEther() public payable {
        uint ethBal = address(this).balance;
        transferFunds(ethBal);
    }

    //Sweep tokens method by specifying token contract address and amount.
    function sweepTokens(address _token) public {
        transferFunds(_token);
    }

    //General transfer funds function (Ether)
    function transferFunds(uint _value) private {
        require(_value > 0);
        uint _fee = (NUMERATOR*_value)/(DENOMINATOR*100);

        //Perform Ether transfer method
        emit LogForwardedEther(_value, merchant, _value - _fee, admin, _fee);
        merchant.transfer(_value - _fee);
        admin.transfer(_fee);
    }

    //General transfer funds function (Token)
    function transferFunds(address _token) private {
        uint _value = ERC20(_token).balanceOf(address(this));
        require(_value > 0);
        uint _fee = (NUMERATOR*_value)/(DENOMINATOR*100);

        //Perform Token transfer method
        emit LogForwardedToken(_value, merchant, _value - _fee, admin, _fee, _token);
        ERC20(_token).transfer(merchant, _value - _fee);
        ERC20(_token).transfer(admin, _fee);
    }
} //end of SweepFunds contract

The above contract will be programatically generated by substituting the following strings with values:

RECIPIENT_ADDR
ADMIN_ADDR
NUMERATOR
DENOMINATOR

Example
Scenario 1
If fee is 1.5% (NUMERATOR: 3, DENOMINATOR: 2), and 100 ether was sent to the contract address; 98.5 ether will be automatically forwarded to RECIPIENT_ADDR, whereas 1.5 ether will be sent to the ADMIN_ADDR.
Scenario 2
If fee is 1.5% (NUMERATOR: 3, DENOMINATOR: 2), and 100 USDT token was sent to the contract address; 98.5 USDT will be automatically forwarded to RECIPIENT_ADDR, whereas 1.5 USDT will be sent to the ADMIN_ADDR by calling the sweep function, specifying the contract address USDT token contract address.
So far it has been working fine; please let me know if you discover any vulnerabilities or any recommendations are much appreciated!
Thanks!


texts:
I'm using hardhat as a framework to develop my smartcontracts. So far it's been great, but im clueless as to why I can't call the mint function from my tests. Here's the error message:
Token.connect(...).mint is not a function

Here's a skinned down version of my TESTing code:
describe("Token contract", function () {
    let TokenContract;
    let Token;
    beforeEach(async () => {
        TokenContract = await ethers.getContractFactory("Token");
        [owner, alice, bob, carol, fakeRouter] = await ethers.getSigners();
        Token = await Contract.deploy(); //sender is by default owner/first address
     });
    it('onlyOwner modifier', async () => {
        await expect(Token.connect(alice).mint(bob.address,
        10)).to.be.revertedWith('operator: caller is not the operator')
    });

Here is the mint function residing in my smartcontract code:
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner(MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
    _mint(_to, _amount);
    _moveDelegates(address(0), _delegates[_to], _amount);
}

Anybody has an idea of what's going on?


texts: How to estimate gas limit for "payable" smart contract?

texts:
We all know that gas limit for EOA to EOA transfer is 21000.
I am got stuck at a point and unable to get dynamic gas limit estimation for "payable" smart contract using Web3.

When sending Ether from EOA to some external smart contract then facing "out of gas" error, because Web3's function estimateGas()

web3.eth.estimateGas({
  to: EOA/Smart Contract address,
  value: web3.utils.toHex(ethAmount)
})

always return 21000, regardless of the "to" address whether its EOA or Smart contract.

Could you please help me figure out this issue.

Thanks.


texts: Can't Send ETH out of my Mist ETH wallet

texts:
I tried to send some ETHs to another account (i tried different crypto based exchanges) from MIST Wallet but with no success. The amount of ETH in my wallet remains the same and no ETH show up in the exchanges' accounts.

I tried several times, and each transaction in MIST wallet is displayed as "sent" and has "0 of 12 confirmations". My MIST wallet has not completed full synchronisation yet.

Will the transactions happen only when MIST wallet is fully synchronised? If not, how I can get ETH out from the wallet.

Thanks for your help


texts: Can I use multiple Ethereum mnemonics in Metamask

texts:
When I first installed Metamask and each time I start testrpc, I get a new mnemonic section of words to use for that testrpc.

I've already configured my MetaMask with four accounts from a prior run of testrpc, with that coinbase having ether that I mined on the testrpc.

So I wonder, if I put in a new set of mnemonic words from the new testrpc run, will I loose the existing accounts in Metamask and invalidate them? Can I go back to them by putting the original mnemonics later?

Or should I have started up testrpc the second time with the mnemonics from when I installed Metamask per this question:

Thanks


texts:
I'm running into a  YulException: Stack too deep when compiling inline assembly: Variable headStart is 1 slot(s) too deep inside the stack. using a smart contract that has this function. I took this function off and the error goes away, so I assume the error is within it. I searched a bit for this error, read this and this and this and concluded the EVM stack has a 16 limit of variables. Although my function has 12, I changed my string to bytes32 cause I read that string take 2 spaces. I also tried removing one of the function params, and it works great again. Although I need all these parameters to create a new struct. Any suggestions on how I should fix this situation?

pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;
...
        function addObservacaoPragas(
                bytes32 _unidadeProducao,
                bytes32 _parcela,
                bytes32 _subParcela,
                uint256 _estadoFenologico,
                bytes32 _armadilha,
                uint256 _tipo,
                bytes32 _praga,
                uint256 _leitura,
                uint256 _inicioOperacao,
                uint256 _fimOperacao,
                bytes32 _responsavel,
                bytes32 _nota
            ) public returns (...) {
              ...
            }
    ...

Here is a full example in case you want to try it in remix:

pragma solidity ^0.6.2; pragma experimental ABIEncoderV2;

contract Operacoes {
    All all;
    uint256 operacaoId;

    // All Operations inside All
    struct All {
        ObservacaoPragas[] observacoesPragas;
    }

    // Common to all operations
    struct CommonOperacao {
        uint256 id;
        uint256 inicioOperacao;
        uint256 fimOperacao;
        bytes32 responsavel;
        bytes32 nota;
    }

    struct ObservacaoPragas {
        bytes32 unidadeProducao;
        bytes32 parcela;
        bytes32 subParcela;
        EstadoFenologico estadoFenologico;
        bytes32 armadilha;
        ObservacaoPragasTipo tipo;
        bytes32 praga;
        uint256 leitura;
        CommonOperacao op;
    }
    // Enums
    enum EstadoFenologico {
        GOMO_DE_INVERNO,
        INICIO_DO_INCHAMENTO_DOS_GOMOS,
        FIM_DO_INCHAMENTO_DOS_GOMOS,
        ABROLHAMENTO,
        FOLHAS_LIVRES,
        CACHOS_VISIVEIS,
        CACHOS_SEPARADOS,
        BOTOES_FLORAIS_SEPARADOS,
        FLORACAO,
        PLENA_FLORACAO,
        BAGO_DE_ERVILHA,
        FECHO_DOS_CACHOS,
        PINTOR,
        MATURACAO
    }
    enum ObservacaoPragasTipo {LEITURA, INSTALACAO, REMOCAO, TROCAR_PLACA}

    constructor() public {
        operacaoId = 0;
    }

    /********************/
    /* Observação Pragas*/
    /********************/
    function addObservacaoPragas(
        bytes32 _unidadeProducao,
        bytes32 _parcela,
        bytes32 _subParcela,
        uint256 _estadoFenologico,
        bytes32 _armadilha,
        uint256 _tipo,
        bytes32 _praga,
        uint256 _leitura,
        uint256 _inicioOperacao,
        uint256 _fimOperacao,
        bytes32 _responsavel,
        bytes32 _nota
    ) public returns (ObservacaoPragas memory) {
        ObservacaoPragas memory obs = ObservacaoPragas(
            _unidadeProducao,
            _parcela,
            _subParcela,
            EstadoFenologico(_estadoFenologico),
            _armadilha,
            ObservacaoPragasTipo(_tipo),
            _praga,
            _leitura,
            CommonOperacao(
                operacaoId,
                _inicioOperacao,
                _fimOperacao,
                _responsavel,
                _nota
            )
        );

        all.observacoesPragas.push(obs);
        operacaoId++;
        return obs;
    }

    /*****************/
    /* Common to all */
    /*****************/
    function retrieveAllOperacoes() public view returns (All memory) {
        return all;
    } }


texts: How do I view the transaction status in Geth?

texts: I am using Geth v1.7 and send a transaction. How can I view the status of this transaction in the tx pool? I remember there has related command in Geth?


texts: Are there any android wallets for Ethereum?

texts: What Ethereum wallets are available for Android? Or which ones are still being developed?


texts: Solidity: solidity declarationerror identifier not found or not unique

texts:
Trying to create my first smart contract with the REMIX IDE, however getting into a Declaration Error. Here is the code of my contract :
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.2;

import "./Context.sol";
import "./IBEP20.sol";
import "./SafeMath.sol";
import "./Ownable.sol";

contract SampleTaken is Context, IBEP20, Ownable {

    mapping(address => unit) public balances;

    unit public totalSupply = 1000000 * 10 ** 18;
    String public name ="Sample Token";
    String public symbol ="KJA";
    unit public decimals = 18;

    /** Events aailable for the Contract**/

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    constructor(){
        balances[msg.sender] = totalSupply;
    }

    function balanceOf(address _ownerAddress) public view returns (unit){
        return balances[_ownerAddress];
    }

    function transfer(address _toAddress, unit _noOfTokens) public view returns (bool){
    require(balanceOf(msg.sender) >= _noOfTokens, "Total balance is less than the number of Tokens asked for !!!");
    balances[_toAddress] +=_noOfTokens;
    balances[msg.sender] -= _noOfTokens;
    emit Transfer(msg.sender,_toAddress, _noOfTokens);
    return true;
    }

    function transferFrom(address _from, address _to, uint _value) public returns (bool){
     require(balanceOf(_from) >= _value, "Balance is less than the number of Tokens asked for !!!");
     require(allowance[_from][msg.sender] >= _value, "Allowance too low");
     balances[_to] += _value;
     balances[_from] -= _value;

     emit Transfer (_from, _to, _value);
     return true;

    }
}

While trying to compile it, I am getting the following error :
DeclarationError: Identifier not found or not unique. --> SampleToken.sol:13:24: | 13 | mapping(address => unit) public balances; | ^^^^

What could be missing here?


texts: What's the point in the 'gas' parameter passed to function 'signTransaction'?

texts:
I am using web3.js v1 in order to sign and send transactions:

async function signAndSend(transaction) {
    let options = {
        to  : transaction._parent._address,
        data: transaction.encodeABI(),
        gas : SOME_GAS_AMOUNT
    };
    let signedTransaction = await web3.eth.accounts.signTransaction(options, PRIVATE_KEY);
    return await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
}

In order to compute how many gas units were used, I do:

let gasPrice = new BigNumber(await web3.eth.getGasPrice());
let bgnBalance = new BigNumber(await web3.eth.getBalance(PUBLIC_KEY));
await signAndSend(myTransaction);
let endBalance = new BigNumber(await web3.eth.getBalance(PRIVATE_KEY));
console.log(`Total cost: ${bgnBalance.minus(endBalance).div(gasPrice)} gas units`);

I observe the following:

When SOME_GAS_AMOUNT is too low, I get base fee exceeds gas limit
When SOME_GAS_AMOUNT is high enough, I always get the same total cost

My conclusion is, just use a large enough (hard-coded) value.

Am I right?

If yes, then what's the point in this parameter to begin with?

The docs for function signTransaction say:

  gas - String: The gas provided by the transaction.

What does "gas provided by the transaction" even mean? I thought that I was the one providing gas for the transaction to take place!

By the way, initially, I used to set the gas parameter as follows:

gas: await transaction.estimateGas({from: PUBLIC_KEY});

However, this occasionally gave me the base fee exceeds gas limit error.

So I figured I was kind of on the wrong track with that one.

In short, any clarifications on the gas parameter would be highly appreciated.

Thank you very much for you help!

UPDATE:

I am not asking about the meaning of the term "gas".

Please refer to my observation (quoting from above):

I observe the following:

When SOME_GAS_AMOUNT is too low, I get base fee exceeds gas limit
When SOME_GAS_AMOUNT is high enough, I always get the same total cost

My conclusion is, just use a large enough (hard-coded) value.

Am I right?

If yes, then what's the point in this parameter to begin with?

If no, what exactly should I set this parameter to?

I initially used to set the gas parameter as follows:

gas: await transaction.estimateGas({from: PUBLIC_KEY});

However, this occasionally gave me the base fee exceeds gas limit error.

So I figured I was kind of on the wrong track with that one.


texts:
I have been watching Ethereum for a couple years, have had that Mist thing installed, I lost $40 in The DAO. The time has come around again for me to pay attention and I want to do a testnet.

I have OSX on my desktop, a Linux system sitting in the corner. I can load random stuff from Git and I do a little programming in Python.

I want to get some sort of testnet going on the Linux box, and a client/wallet on OSX, then maybe on Android if it's not too much of a nuisance.

I want to be able to run this testnet stuff as a service, worst case shell in and run it under tmux. I really want a command line client, preferably Python. This installed without complaint:

https://github.com/ethereum/pyethereum

And this is where I get confused. I see there are three testnets, I see tutorials on configuring them for other clients, but I don't find a current pyethereum HowTo anywhere.

https://testnet.etherscan.io/

Is pyethereum the right way to go about this? Or do I really have to suck it up and get familiar with the Go client? I tried that thing a while ago and I forget exactly how it made me mad, but it did.


texts: Can Ethereum network exist without ETH currency?

texts:
Theoretically speaking, is ETH currency necessary in the future to run the Ethereum network with all its possibilities like Dapp and Smart Contracts?

I understand that you need to pay gas to miners, which in return converts to Ethereum currency for them, therefore Ethereum keep its currency value.

But is that just a system design created for purpose of making the Ethereum currency valuable, or in the future can we see Ethereum network running completely without Ethereum currency?

Simple question, can the Ethereum network function without the ETH currency. Can someone in the future redesign the network  keeping all the good things working, but remove ETH currency component from it.

Or are ETH currency and miners an inseparable part of the Ethereum network, Dapp and smart contracts?


texts: unique deposit address for each investor in ico

texts: How can I create a unique deposit/contribution address for each investor in ICO. Is it possible to do it for both BTC and ETH ?. How can funds be transferred to one mutisig wallet from each unique address. Is there a way to achieve this using the smart contract ?


texts:
So right now I'm using 2miners and I rented 1.06GH/s to mine Ethereum. It says every 2 months I should find a block solo at 11k reward. Pool mining I'll get .55eth if pool finds a block now. It never says when a pool with find a block and I need to mine with a pool for the daily payout so I can keep buying the same hashpower. My question is How long in a pool will it take to find a block? Is there a pool better than 2miners out there? The only other pool I use (For the last 3 days) is antpool to get ltc+doge.
Oh, My end game is to keep investing the daily earnings and withdraw the blocks. When I have enough I will buy a asic machine built for either or gpus to mine diff coins.


texts: Importing Ethereum Account Private Key and Using on Different Servers

texts: Let's suppose i have a wallet on one remote server, R-1. Is it possible to get the private key of that wallet/account and use it on different remote server R-2? I know, i can copy/paste files under keystore of a specific wallet from R-1 server to R-2 server but I am more interested in getting a private key, which when exporting from CLI on R-2 will import my account without copying/pasting. As per my understanding, Ethereum must have my account's information, if yes, then how can use that available information to use my wallet on different server.


texts: how to use node await syntax with web3 version 1.x

texts:
I am trying to use node await syntax but keep getting errors. I run

web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io'));
let isListening = await web3.eth.net.isListening();
    let numPeers = await web3.eth.net.getPeerCount();
    console.log( "node " + infuraUrl + " listening: " + isListening.toString() + " with " + numPeers + " peers");

and I keep getting this error:

let isListening = await web3.eth.net.isListening();
                        ^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3


texts: passing defaultBlock "pending" param to a truffle-contract call

texts:
I need the pending balance of my contract.
As far as I understand I could do it with web3:

web3.eth.call(callObject [, defaultBlock] [, callback])

Can I pass defaultBlock to truffle-contract abstraction as well or I need to call web3 directly?

I.e. When I'm trying to pass a defaultBlock to a truffle-contract call:

import { default as Contract } from "truffle-contract";
let contractDef = Contract(artifacts);
contractDef.setProvider(provider);
let instance = await contractDef.deployed();
let balance = await myContract.instance.balanceOf(
         address,
         "pending"
     );

I get:

Error: Invalid number of arguments to Solidity function


texts:
I have a Node-js application where cards are generated with unique number (ID11234). So I am planning to map a token for each card. In order to get uniqueness, I went through some of the documents, at-last planned to use ERC721 token for my application.

I understood the basic functionalities used in this token, but I didn't see the execution flow of token in any documents.

How should I execute ERC721 token solidity files (ERC721.sol,
ERC721BasicToken.sol, ERC721Token.sol, ERC721Basic.sol)?
How can I map generated tokens with each card?

Referral Links  :
https://medium.com/blockchannel/walking-through-the-erc721-full-implementation-72ad72735f3c


texts: How to make geth keep states for the last 10000 blocks instead of 128

texts:
If I understand it correctly, geth preserves states for the last 128 blocks and prunes states for all other blocks. I would like to keep states for a bigger number of last blocks, say 10000 blocks. Is it possible?

Thank you!

EDIT: Suggested question isn't the same as mine. I was hoping I don't need to run a full fledged archive node to be able to see states for the last 10000 blocks. I'm certain I wouldn't need to get state for any block that is more than a week old


texts: How to use Exit function on this smart contract in solidity?

texts:
This is on Tron but its a pure solidity openzeppelin code so I assume this is the right place to look.

https://tronscan.org/#/contract/TEzjbwwYda6WMQAQ8p7GoXq4W3Xo532KJj/code

I want to use EXIT function, yet it needs some _pid_uint256 and i am not sure what to put there.


texts: How is the block gas limit dynamically adjusted?

texts:
What mechanism lies behind adjusting the block gas limit dynamically?

Is it the miner that mined the most recent block who decides whether to adjust the gas limit or not?

How much can the block gas limit vary from block to block when adjusted?


texts: Error while trying to invoke function via web3

texts:
I read all the documentation, but this simple example that tries to invoke function doesn't work.

The initiation:

  var contractAbi = web3.eth.contract(myABI);

  var myContract = contractAbi.at(myAddress);

seems to be okay. But:

  myContract.methods.dummy().call({from: web3.eth.accounts[0],data:getData}, function(error, result){
    if(!error)
    {
        console.log(JSON.stringify(result));
        console.log(result);
      }
    else
        console.error(error);
  });

raise the following exception:

  myContract.methods is undefined

while the following code:

  var getData = myContract.dummy.getData()
  web3.eth.sendTransaction({to:myAddress, from:web3.eth.accounts[0],data:getData, gas:30000 },function(error, result){
      if(!error)
      {
          console.log(JSON.stringify(result));
          console.log(result);
        }
      else
          console.error(error);
  });

Pops a metamask transaction creation pop-up, and the return value is not my function "dummy" value.

Thanks for the help.

More information:

I includes :

  < script language="javascript" type="text/javascript" src="web3.min.js">

and also the following standart code:

  window.addEventListener('load', function() {
    // Checking if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      web3js = new Web3(web3.currentProvider);
      startApp()
    } else {
       console.error("Please use a web3 browser");
      // Handle the case where the user doesn't have Metamask installed
      // Probably show them a message prompting them to install Metamask
    }
    // Now you can start your app & access web3 freely:
  })


texts: Conversion of address to string in Solidity

texts:
The Solution given in Convert address to string did not help.
Motive: To convert an address to string type so that I can use it as a parameter to a function for which string type is necessary.
Code Snippet:
function toString(address x) returns (string) {
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++) {
        b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
    }
    return string(b);
}

function getResult() constant returns (string) {
    string memory myAddress = toString(msg.sender);
    return myAddress;
}

Now, when I call getResult() using truffle I get the following error.
Error: Invalid continuation byte
    at Error (native)
    at readContinuationByte (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59394:9)
    at decodeSymbol (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59423:12)
    at Object.utf8decode [as decode] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59469:33)
    at Object.toUtf8 (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:5184:17)
    at SolidityTypeString.formatOutputString [as _outputFormatter] (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:24766:18)
    at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28364:25
    at SolidityTypeString.SolidityType.decode (C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:28365:11)
    at C:\Users\perecept\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:59736:29
    at Array.map (native)

Please help understand the root cause of this error as I failed to detect any mistake in my code.
Thank you in advance!


texts: I understand that Ethereum have gas mechanism to avoid infinite loop and network abuse, but I was wondering whether other blockchain platforms also have gas concepts? Say Cardano, Hyperledger,...


texts: How can we decode transaction and event data shown on blockchain explorer. I have tried couple of blockchain explorer like (epirus-free, blockscout) but they are showing only encoded values of events and functions....how can I show human readable values in my blockexplorer?


texts: Differenciate ERC20 / ERC223 / ERC677 Tokens

texts:
Are really mind blogging!

I am having difficulties to check which version of Token I am handling when I am creating a new contract.

How can I easily tell the token that I need to transfer is ERC20 or ERC223 or ERC677? (in addition to 721)

(I know 677 is more downward compatible to 20 compare to 223)

In my opinion, all these will get out of control sooner or later unless we implement a simple field in the contract just to tell which version this token is

Example:

string public tokenSpec;

function MyToken() public {
    tokenSpec = "ERC223";
}


texts: What is (fallback) method in a contract?

texts:
I'm new to Solidity programming and I don't know what is (fallback) function generated when I deploy a DAO contract. It is not defined in the contract code.

Sample code I used:

pragma solidity ^0.4.24;

contract Fundraiser {
    mapping(address=>uint) balances;

    function withdrawCoins(){ // vulnerability inside
      uint withdrawAmount = balances[msg.sender];
      Wallet wallet = Wallet(msg.sender);
      wallet.payout.value(withdrawAmount)();
      balances[msg.sender] = 0;
    }

    function getBalance() constant returns (uint) {
        return address(this).balance;
    }

    function contribute() payable {
        balances[msg.sender] += msg.value;
    }

    function() payable {

    }
}

This method is used as Adding a fund to that contract, and by this, tokens are added to that DAO, and contributing or withdrawing is enabled.

Does this mean I have to put ETH into a DAO contract to get token of that DAO contract? How can I define that (fallback) method, and where can I get the documentation or reference for how to use it?

Thank you in advance for your answer.


texts: I can't access my ETH wallet (made on wallet.ethereum.org in 2017)

texts:
In 2017, when I first started to mine, I made a wallet in wallet.ethereum.org (I stopped briefly after, so I have around 2.2 ETH in that wallet).
Now in 2021 I tried to go to wallet.ethereum.org but the website seems to be down... and according to some instructions I have to transfer it to MEW using JSON or Keystore, which I don't have them anymore..
The only thing I have is the public address, a username and a password,(key icon) address 0x.........
Is there anything I can do with this to access to my ETH address and transfer my 2.2 eth?
Is there someone that can guide me through this?
Thank you in advance.


texts: During the launch of the frontier network, users were cautioned not to reuse keys from the Olympic testnet in order to prevent "replay attacks".  What is a replay attack, and why would re-using a key from the testnet make someone vulnerable to one?


texts: Explicit declaration, the "var" keyword is not allowed syntax error

texts:
While trying to compile this contract I'm getting a syntax error complaining about the "var" keyword being disallowed. How do I fix this?

pragma solidity ^0.5.0;

contract Courses {

    struct Instructor {
        uint age;
        string fName;
        string lName;
    }

    mapping (address => Instructor) instructors;
    address[] public instructorAccts;

    function setInstructor(address _address, uint _age, string memory _fName, string memory _lName) public {
        var instructor = instructors[_address];

        instructor.age = _age;
        instructor.fName = _fName;
        instructor.lName = _lName;

        instructorAccts.push(_address) -1;
    }

    function getInstructors() view public returns (address[]) {
        return instructorAccts;
    }

    function getInstructor(address _address) view public returns (uint, string memory, string memory) {
        return (instructors[_address].age, instructors[_address].fName, instructors[_address].lName);
    }

    function countInstructors() view public returns (uint) {
        return instructorAccts.length;
    }

}