texts: How to handle enums as arguments for public functions?

texts:
Assume this simple contract:

pragma solidity 0.6.3;

contract InvalidOpcode {

    enum Dir {UP, LEFT, DOWN, RIGHT}
    Dir public currentDir;

    function changeDir(Dir newDir) public {
        require(uint8(newDir) <= uint8(Dir.RIGHT), "Out of range");
        currentDir = newDir;
    }

}

The exposed interface of the function accepts an uint8 as argument.
When run on Remix with a value of 4 (or greater) as the input, the tx will throw with this error:

transact to EnumTest.changeDir errored: VM error: invalid opcode.
invalid opcode
    The execution might have thrown.
    Debug the transaction to get more information.

Debugging reveals that the require statement is not reached (and is thus useless). The invalid opcode occurs while accesing the argument. The debugger shows the local variable newDir: INVALID_ENUM<4> enum.
I think the transaction then throws and stops using gas, but I am not sure!

When I run the same thing in a truffle environment, the transaction will exit with status 0.
truffleAssert.fails(instance.changeDir(4),"status 0") will catch it, but all gas will be consumed in the transaction! From what I know, it is not possible to debug further (on opcode level) in truffle.

My questions are:

Does this transaction indeed consume all gas?
If so, is there a way to prevent this?
Is there a way to revert the transaction with a meaningful message?
What is the best practice to expose an Enum argument to the public interface?

Edit:

One way to potentially solve the problem is to change the argument to an uint8:

contract FixedInvalidOpcode {

    enum Dir {UP, LEFT, DOWN, RIGHT}
    Dir public currentDir;

    function changeDir(uint8 newDir) public {
        require(newDir <= uint8(Dir.RIGHT), "Out of range");
        currentDir = Dir(newDir);
    }

}

This behaves as expected. But is the type conversion Dir(newDir) safe and is this the recommended way to expose the function?

I would still like to get into what is happening if an enum is directly exposed to the interface and if that is something that can be improved in the compiler. In my opinion, the first contract above should revert with a failing assert.


texts: What are the truffle console commands to interact with a mapping function of struct

texts:
Im writing a simple smart contract to store and retrieve data of series of patients' name and blood group with an id using mapping function in solidity. I don't know the commands to interact with the deployed contract via truffle console. Anyone please write me the truffle console commands to interact with this contract. I'm using solidity version of 0.5.0.
pragma solidity ^0.5.0;

contract PatientDB {

    mapping (uint => patient) public patient_db;

    struct patient {
        string name;
        string blood;
    }

    function addPatient (uint _id, string memory _name, string memory _blood) public {
        patient_db[_id] = patient (_name, _blood);
    }
}


texts: Prevent 'truffle test' from invoking 'truffle deploy (migrate)'

texts:
It seems that truffle test automatically invokes truffle deploy (aka truffle migrate).

As far as I'm concerned, these two functionalities are completely unrelated.

So I cannot quite figure out why Truffle works this way to begin with.

The docs do not seem to mention anything on this subject.

I would like to use truffle test for one thing and truffle deploy for another thing.

Is there any way to "tell" truffle test to avoid running truffle deploy?

Thank you!!!


texts: For some purpose. I use web3.js 0.20 to deploy contracts.(eg. press button to deploy contracts automatically, not through remix IDE). When I deploy contracts, etherscan need to verify solidity. Is there a method that verifies contracts automatically through Web3? Thanks a lot.


texts: I am calling geth rpc method eth_getStorageAt using json-rpc-cpp libarary. I need to know the parameters' names for the method. I can find parameters' names for eth_sendTransaction from here, which includes "from", "to" and so on. My questions is where to find the similiar ones for eth_getStorageAt, thanks.


texts:
I tried to Verify & Publish Contract Source Code for my token
and the error happened like this Compiler debug log:
Error! Unable to generate Contract ByteCode and ABI (Compiler Exception)
For troubleshooting, you can try compiling your source code with the Remix - Solidity IDE and check for exceptions
you can take a look at the attached image

what is wrong with it? why did this error happen?
how I can correct it?
regards


texts: When I run the truffle v command in my powershell and get these results

texts:
Truffle v5.2.2 (core: 5.2.2)
Solidity v0.5.16 (solc-js)
Node v12.19.0
Web3.js v1.2.9
where is that solidity version coming from? I know i install truffle globally sometimes, so does it ship with solidity or what. Also does solidity version automatically mean solidity compiler version?


texts:
I came across MEV in this reddit posted by Flexpool (i think) because Flexpool was claiming MEV was a big improvement and good for miners.
The close I could get to an explanation is that there are traders trying to do fast trades. So they pay extra to a pool to get higher priority and MEV is a way to pass that payment on to miners.
What is MEV?
How is it a big improvement and good for miners?


texts: Use of fallback function for ICO fund collection

texts:
I want to implement the callback function for simplicity's sake, so people can just send ether without calling a function.

However, I'm worried my callback function will require too much gas. It:

* records how much that address invested (in a mapping)
* adds address to an array
* increments a counter
* sends funds to collection wallet
* triggers an Event

1) I know the contract would run out of gas when getting called by another contract. Is it the same when someone manually sends ether from their account?

2) I've tested the fallback function on Rinkeby and it works fine. Is it safe to assume it'll work fine on the main net as well?

3) If not, what's a better way of collecting funds for an ICO?

4) Just to confirm: the fallback function is atomic right, so if the last operation runs out of gas, nothing writes and ether is not sent?


texts:
The architecture of my dapp consists of a backend (metamask + web3.js or web3.js + geth) and a smart contract that offers different services (functions). I want a function on the smart contract to run on a certain date. Can my backend call a smart contract function to be executed on a certain date?
I have been looking for an answer to my question for days but I can't find any clear explanation.


texts: Catch Internal Out of Gas Exception in Solidity Code

texts:
I ran this transaction which executed correctly, but one of the internal calls gave me back an out of gas error.

I had a try/catch mechanism to let my code terminate silently (to set some really important business logic actions after internal executions, as you can see from the Transaction).

But I really need to manually revert the transaction only and only if there is an out of gas internal error.

Original code is quite complicated, so I reproduced it in a more simple way, but it is quite similar to the original one.

<!-- language: lang-solidity -->

pragma solidity ^0.6.0;

contract GasEstimation {

  event CorrectExecution(bool result, bool outOfGas);

  function callMe(address location) public payable {
    bool result = false;
    bool outOfGas = false;
    try ToBeCalled(location).externalCall() {
      result = true;
    } catch (bytes memory lowLevelData) {
      //How can I check if externalCall() failed because ran out of gas?
    }
    if(result) {
      /* Some other Gas-Consuming Operations */
      _inCaseOfSuccess();
    } else if(outOfGas) {
      revert("Out Of Gas!");
    }
    emit CorrectExecution(result, outOfGas);
  }

  function _inCaseOfSuccess() private {
    //My other Gas-Consuming Stuff
  }
}

interface ToBeCalled {
  function externalCall() external;
}


texts: Plans to migrate go-ethereum to rust-ethereum?

texts:
Is anyone planning to migrate go-ethereum to rust-ethereum? Rust with all its features such as zero-cost abstractions, safe memory management, fearless concurrency really outshines Go.

Nathan Aw (Singapore)


texts: UniSwap V3 API : How to track **unclaimed fees** programmatically?

texts:
I have invested in UniSwap-V3 Liquidity Pool.
And how to track  unclaimed fees programmatically?
I plan to have server-backend API fetch data to track  unclaimed fees ($27.92 in picture)

I have tried  to query position from EthScan Read Contract (in as second picture), but don't know how to get unclaimed fees from this data??
https://etherscan.io/address/0xc36442b4a4522e871399cd717abdd847ab11fe88#readContract


texts:
Do you have to use Meteor for building Dapps? Are there any alternatives for Meteor JS to build DApps?

Is it maybe even possible to build distributed applications for Ethereum without utilizing JavaScript?


texts: Can non-default port (not 30303) be a reason for the small number of peers?

texts:
I have two ethereum full nodes in Rosten network with non-default port (not 30303).

One has net.peerCount = 3, the next one has net.peerCount = 0 and I can't sync it more then 24 hours.

Also, I have one geth node in MainNet with a non-default port as well. It has  net.peerCount = 6 more than 24 hours.

If I change the port to 30303, can it increase the number of peers for my nodes?


texts:
I need to send tokens from my eth address with 0 gas fee.On my address has script autobot which automatically sends ether to self or on other address after getting within 1-2 minutes,sometimes 3-7 minutes.
Hope you offer how to decide.Also I see that some people may send any tokens or ether with absolutely 0 fee,I see that on some transactions


texts: Transfer funds without accessing to JSON wallet

texts: My question cause by my potention misunderstanding of how network works. Situation: I have my wallet number (only number) and its password. Can I (and how) transfer amount from this wallet to any other address? Or I must provide JSON wallet/key phrase/etc.?


texts: Historic transaction debug_traceTransaction discrepancy

texts:
I am currently looking at internal transaction in historic transactions, and wonder if I have encountered a bug for a particular tx: 0xd8aaf9c7f3b5e2389e6899914d6421085e6d3b932fd427180dd7cdb67f83e18d

Ether camp vmtrace lists 44 steps, and no CALL among them
https://live.ether.camp/transaction/d8aaf9c7f3b5e2/vmtrace#0

However debug_traceTransaction for that same transaction returns 64 steps, including a CALL a step 52. That CALL does not seem to be reflected in eth_getBalance, so it looks like a bug of debug_traceTransaction, but is there another possibility?

Edit: opened https://github.com/ethereum/go-ethereum/issues/2522


texts: Are events permanently stored and reliably available to contracts in the future?

texts:
I've seen this forum post about using Ethereum as an event store:
Events in Solidity, using blockchain as eventstore.

However, it doesn't seem conclusive. For instance it says:

  I confirmed with Vitalik and since confirmed by Chris that events are permanent. In future, some nodes may prune historic data.

If nodes prune historic data I'm not sure what the implications are for the availability of Event data.


texts:
In https://ethresear.ch/t/the-eth1-eth2-transition, Vitalik wrote:

  If you are a developer, you can eliminate the largest part of
  disruption from gas cost changes by proactively making sure you don’t
  write apps with high witness sizes, ie. measure the total storage
  slots + contracts + contract code accessed in one transaction and make
  sure it’s not too high.

How, exactly, does one do this? What is the metric? What is 'too high?'


texts: Simple question about pre/post hard fork of July 2016

texts:
I have searched the messages and, while I did find some info on the hard fork, I didn't see my answer.  I believe it is because it is such a simple question.  Thank you for any clarification you can provide!
I am a novice regarding cryptocurrency in general.  If you owned 50 Ethereum prior to the hard fork in July 2016, would those 50 coins be considered ETH or Classic?  I have read some conflicting articles trying to figure this out myself.  Some say that Classic forked off ETH to remain "pure"; thus, I would think the 50 would be considered ETH.  I read a different article saying that the Classic remained "pure" and ETH forked off it, meaning the original 50 would be Classic.  Now, reading some message threads on here, it seems to be that the fork gave owners the same of each ETH and Classic; therefore, you would have 50 of each.  I sincerely hope someone can answer this for me.  Thank you again!


texts: How to get rid of Infinite/HIGH gas limit warning of a function?

texts:
I'm getting the warning

Gas requirement of function helloWorld.getGreeting() high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)

in the following contract

pragma solidity ^0.4.22;

contract helloWorld {

    string public greeting;

    string[] public greetings;

    constructor() public {
        greeting = 'hello World';
        greetings.length= greetings.length + 1;
    }

    function setGreeting(string _newGreeting) public {
        greeting = _newGreeting;
        greetings.push(_newGreeting);
    }

    function getGreeting() public view returns (string) {
        return greeting;
    }
}

I would like to be able to have the contract with none of these warnings, any help would be great !

thanks in advance !


texts: With rising DApps number on Ethereum....won't this bloat the blockchain too much?

texts:
Blockchains are praised everywhere as improving most of our today's tech problems. They are proposed for Recordkeeping, Title protection, Health records, etc.

Let's say hundreds of organizations start using Ethereum to build their DApps on, they all get deployed.

Won't this bloat the Ethereum blockchain to unusuable levels? Is there any sharding, compartamentalization or something on the blockchain which helps scaling here? Does every DApp run in some sort of private space? Or does it need to create private blockchains? Even private network Ids?


texts: Can i recover ethereum sent to and invalid address?

texts: i've mistakenly pasted "2.5" in address field submitted a withdrawal request. can i get my coins back since the address is an invalid or the coin will be sent? I'm afraid i may loose my coins.


texts: how to import UTC-JSON file through web3-eth methods

texts: hey I am working on ethereum wallet. in this i want to import my account through UTC json file, but i didn't find any solution for this in web3-eth command someone can please help to find out the solution. thanks in advance.


texts: Web3j directly gets string from contract by eth_call

texts:
I just have a simple solidity contract:

pragma solidity ^0.4.19;

contract SampleContract {
    string value;

    function SampleContract() public {
        value = "hello world";
    }

    function getValue() public view returns (string){
        return value;
    }

    function setValue(string str) public {
        value = str;
    }
}

I am attempting to interact it with web3j. For now I have already deployed successfully and get the address.
I am trying to call method getValue() by codes:

static String call(String from, String contractAddress, String callData) throws Exception {
        Call call = new Call(from, contractAddress, callData);
        return service.ethCall(call, DefaultBlockParameter.valueOf("latest")).send().getValue();
    }

String callData = encodeGetValueFuncWithParams();
System.out.println(callData);
String result = call(from, contractAddress, callData);
System.out.println(result);

I indeed get the result but in hex. The result I get is

0x
0000000000000000000000000000000000000000000000000000000000000020
000000000000000000000000000000000000000000000000000000000000000b
68656c6c6f20776f726c64000000000000000000000000000000000000000000

I converted this vaue and it is "hello world" but how can I directly get the value as string "hello world" instead of "0xxxxxxxx".
The way I create my calldata is shown below:

static String encodeGetValueFuncWithParams(){
    Function function = new Function(
            "getValue",
            Collections.emptyList(),
            Arrays.asList(new TypeReference<DynamicBytes>(){})
    );
    String encodedFunc = FunctionEncoder.encode(function);
    return  encodedFunc;
}

My question is:
How do I construct my calldata so that I can directly get string value instead of hex value from contract.


texts:
I am studying consensus algorithm. In the case of the proof-of-work algorithm, a double spending attack was possible by the miner making a transaction and presenting the longest block from which the transaction was missing through 51% hash power. So, most of the transactions seem to pass the confirmation time and confirm the transaction.
The proof-of-authority algorithm provided by Ethereum allows only verified nodes to participate in consensus. Then, I think that the confirmation time will be lost in terms of transaction finalization.
Then.. In proof-of-authority, if a specific node is malicious, what are possible attack scenarios?
((For example, is it possible for an attack to allow two transactions with the same nonce for a specific account to exist on the blockchain?


texts: Calling event.watch() and event.get() prevents truffle JS tests to terminate

texts:
My contract is

contract SimpleContract {
    uint storedData;
    event SimpleEvent(uint p); // EVENT

    function set(uint x) public
    {
      storedData = x;
      SimpleEvent(x); // TRIGGER EVENT
    }
    function get() public returns (uint) { return storedData; }
}

When I execute this test with truffle test, the console listens forever and the test never ends.

var SimpleContract = artifacts.require("SimpleContract");

contract('SimpleContract', function(accounts) {
  let contract;
  let owner;
  let web3Contract;

  before(async () => {
    contract = await SimpleContract.deployed();
    web3Contract = web3.eth.contract(contract.abi).at(contract.address);
    owner = web3Contract._eth.coinbase;
  });

  it("test", async function() {
    let event = contract.SimpleEvent({_from: owner}, {fromBlock: 0, toBlock: 'latest'});

    // THIS TRIGGERS THE EVENT
    await contract.set.sendTransaction(10);

    // PRINT THE PAST EVENT, BUT DOESN'T STOP THE EXECUTION
    event.get((error, logs) => {
      console.log(logs)
    })
  });
});

If I keep executing the test (using truffle develop and then test multiple times), I get this message after 11 executions:

  (node:382) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 unhandledRejection listeners added. Use emitter.setMaxListeners() to increase limit

Same behaviour with watch(), but in that case I can fix with:

event.watch(function(error, result) {
  if (error) {
    console.log(error)
  } else {
    console.log(result)
  }
  event.stopWatching() // WITHOUT THIS, EXECUTION NEVER ENDS
})

There is some memory leak, I'm not releasing/unregistering correctly. Any idea?


texts: Is there any way to determine how long it took for the DAO attacker to deploy the attack?

texts: Yeah, we heard that the DAO has been attacked. I am so curious about how long it took for the attacker to perform the whole transactions?


texts: Sending transaction to a Web3 contract object in Truffle test produces 'file import callback not supported'

texts:
I need to send a state-changing transaction to a Web3 contract object in my Truffle tests, which is hitting a fork of Kovan in my local ganache chain (ganache-cli --fork https://kovan.infura.io/v3/[api_key]@latest).

The contract I'm sending a transaction to is a Web3 contract object of an already-deployed contract on Kovan.

const theirContractABI = require("./abi/TheirContract");
const theirContractAddress = "0x123456789...";
const theirContract = new web3.eth.Contract(theirContractABI, theirContractAddress);

contract("MyContract", accounts => {
   it("can update a TheirContract property", async () => {
      await theirContract.methods.someFunction().send({ from: accounts[0] });
      ...
      assert(some condition);
   });
}

When I run this specific test, all I get is Error: Returned error: VM Exception while processing transaction: revert, and it's not produced by a falsified require statement. So, I tried using @0x/sol-trace. When I run yarn trace, I get

error InitializableAdminUpgradeabilityProxy.sol:3:1: ParserError: Source "/Users/slider/Desktop/myProject/node_modules/@openzeppelin/upgrades/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol" not found: File import callback not supported

import './BaseAdminUpgradeabilityProxy.sol';
^------------------------------------------^

and

error InitializableAdminUpgradeabilityProxy.sol:4:1: ParserError: Source "/Users/slider/Desktop/myProject/node_modules/@openzeppelin/upgrades/contracts/upgradeability/InitializableUpgradeabilityProxy.sol" not found: File import callback not supported

import './InitializableUpgradeabilityProxy.sol';
^------------------------------------------^

TheirContract imports @openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol, but I have the @openzeppelin/upgrades package installed, and BaseAdminUpgradeabilityProxy.sol & InitializableUpgradeabilityProxy.sol are indeed located in the same file within node_modules as InitializableAdminUpgradeabilityProxy.sol.

So, I'm fairly unsure of where the issue stems from and how to resolve it. Would greatly appreciate a point in the right direction.


texts: truffle migrate with testrpc vs geth testnet

texts:
Truffle migrate works when I use testrpc but not geth.

Here's what I did for testrpc:
In one console

node-modules/.bin/testrpc

In another

truffle console
compile
migrate

resulting in

Using network 'development'.

Running migration: 2_deploy_contracts.js
  Deploying GoodFund...
  GoodFund: 0x18c9f7f2468714dab06264cf06446f66251ac930
Saving successful migration to network...
Saving artifacts...

However when I use

geth --testnet console
admin.startRPC("127.0.0.1", 8545, "*", "web3,db,net,eth")
personal.newAccount('blah')
personal.unlockAccount('account key', 'blah', 15000)

and in another console

truffle  migrate

resulting in

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: authentication needed: password or unlock

I've tried changing truffle.js host from 'localhost' to '127.0.0.1' and got the same error.

This is what I have in 2_deploy_contracts.js

var GoodFund = artifacts.require("./GoodFund.sol");

module.exports = function(deployer) {
  deployer.deploy(GoodFund, '0x6196bc7c252ac811ce06824cd5abbbe4b36db6dc', {gas:4000000});
};

Thanks for y'alls help!


texts:
can someone please send some test ether.i have been trying last 2 weeks but somehow mining not working on testnet. thanks dsyed

0xB8017ed5b72fA08605EBF39Ee6433DD559c02f68


texts:
Yesterday I sent this tx on Ropsten network. It is a transfer for 999 ethers.

eth.sendTransaction({from:"0x8c60d40a2e848251d139fc2b0b6b770bb3351ffd", to:"0xf9e33261328a1cdc62d3dc6b95880656a1f2a5d9", value: web3.toWei(999, "ether"), gas:4700000, gasPrice: 10000000000});
    0x86329f1a1022c4d7cfe7c66b319c31481d66c83e0554980ec1b3e567d6f79c97

Transaction 0x86329f1a1022c4d7cfe7c66b319c31481d66c83e0554980ec1b3e567d6f79c97 became lost. First 10 hours was seeing on etherscan https://ropsten.etherscan.io/tx/0x86329f1a1022c4d7cfe7c66b319c31481d66c83e0554980ec1b3e567d6f79c97 as a pending tx, but then it just disappeared and it doesn't exist anymore.

Is there any explanation to such a behaviour? Is no guarantee for a sent tx to be mined?


texts: Having a problem compiling a ERC20 token smart contract - Code inside

texts:
Basically i'm using a cut and paste erc20 token code from this site:

https://hashnode.com/post/how-to-build-your-own-ethereum-based-erc20-token-and-launch-an-ico-in-next-20-minutes-cjbcpwzec01c93awtbij90uzn

NOT SURE IF THIS TEMPLATE IS IS OUTDATED OR NOT

i am not familiar with solidity, but learning atm

Also i'm using the remix IDE with the new interface

The error that i'm getting in the Remix IDE solidity compiler is:

ParserError: Expected identifier but got 'uint8'
uint8 public decimal; 25;
^---^


texts: Geth with clique block sealing without unlock account

texts:
Hello I have a local blockchain, Geth client, 2 nodes and clique proof of authority algorithm.

I start geth with this command:

geth --datadir node2/ --syncmode 'full' --port 30312
     --rpc --rpcport 8546 --rpccorsdomain "*"
     --ipcpath geth.ipc --rpcapi 'personal,db,eth,net,web3,txpool,miner'
     --bootnodes 'enode://702efed8e606...ad041b4371a91989@127.0.0.1:30310'
     --networkid 2456 --gasprice '1' --mine
     --unlock '0x46004DEAfddb60d11cA04501df8C52aE4679Be8f' --password password.txt

but because of unlock now everyone can transfer ether from this account to some other account

like so:

const Web3 = require("web3");
var web3Client = new Web3(new Web3.providers.HttpProvider("http://localhost:8546"));
await web3Client.eth.sendTransaction({
  from: "0x46004DEAfddb60d11cA04501df8C52aE4679Be8f",
  to: "0xE77e5634A46153e1cfCa02350cf212BdbC18fbC6",
  value: 23
});

but if I remove --unlock from geth command I can no longer seal blocks

WARN [06-01|14:44:52] Block sealing failed    err="authentication needed: password or unlock"

is it possible to seal blocks without having to unlock the account?


texts: Searchable database of popular smart contracts?

texts:
Is there a searchable database of smart contract somewhere?  I'm starting to run across a lot of useful open source smart contracts, from entities like Open Zeppelin, others found in a whole bunch of articles on Medium,  smart contract GitHub repos I stumble across, etc. and I am now officially in a state of "fear of missing out (FOMO)" when I start coding a new smart contract, because there might be something better and safer out there already.

Given that mistakes in a smart contract live forever on the blockchain and can cost users money if there are bugs, I'm more aggressive than usual about finding well-tested existing code before writing something myself.


texts: Solidity get() function only returning one string when i ask for all strings in mapping

texts:
Can anyone tell why my get() function only returns the string "name" in Remix? I'd like it to return all the values within the users mapping like i've defined, can you help me accomplish this?
pragma solidity ^0.5.0;

contract Profile {

    struct User {
       string name;
       string subtitle;
       string sdescription;
       string ldescription;
       string weburl;
       string memehash;
    }

    mapping(address => User) public users;

  function set(string memory _name, string memory _subtitle, string memory _sdescription,string memory _ldescription, string memory _weburl, string memory _memehash) public {
    users[msg.sender] = User(_name, _subtitle, _sdescription, _ldescription, _weburl, _memehash);
  }

  function get() public view returns (string memory) {
    return users[msg.sender].name;
    return users[msg.sender].subtitle;
    return users[msg.sender].sdescription;
    return users[msg.sender].ldescription;
    return users[msg.sender].weburl;
    return users[msg.sender].memehash;
  }
}

"test" is the name i set in Remix with the set() function. ^


texts: Remix error while running the following Inherited Solidity Model

texts:
UPDATED BELOW: (What worked for Me)

While compiling and running the following code on Remix.   When I try to initialize Master with _ownerName, I get the following error  "This contract does not implement all functions and thus cannot be created".

I wanted to create new Customer Contracts using the CustomerTemplate Contract

pragma solidity ^0.4.11;

//------------------------------------------------------------------------------------
//----- Templates
//-----
//------------------------------------------------------------------------------------

contract CustomerTemplate {

    bytes32 public customerName;
    bytes32 public customerLoc;

    function CustomerTemplate (bytes32 _customerName, bytes32 _customerLoc)  {

        customerName    = _customerName;
        customerLoc     = _customerLoc;

    }

}

//------------------------------------------------------------------------------------
//----- Master
//----- Initialize Customer Master with Customer Name and Total Budget
//------------------------------------------------------------------------------------

contract Master is CustomerTemplate{

    address public owner;
    bytes32 public ownerName;
    address[] newCustomers;

    modifier onlyByMaster()  {
        require(msg.sender == owner);
        _;
    }

    function Master (bytes32 _ownerName) {

        owner = msg.sender;
        ownerName = _ownerName;
    }

    function createCustomer (bytes32 _customerName, bytes32 _customerLoc) {

        address myCustomer = new CustomerTemplate(_customerName, _customerLoc);
        newCustomers.push(myCustomer);
    }

    function killContract() constant onlyByMaster {

        if (msg.sender == owner) selfdestruct(owner);

    }

}

(UPDATE) The following worked for me:

pragma solidity ^0.4.15;

contract Template {

    bytes32  public custName;
    bytes32  public custLoc;
    address  public contractAddress;

    function Template () {

        custName            = "0xDEFAULT";
        custLoc             = "0xDEFAULT";
        contractAddress     = address(this);

    }

    function AssignCustomerAttributes (bytes32 _custName, bytes32 _custLoc)
        returns (bool isSuccess) {

        custName    = _custName;
        custLoc     = _custLoc;

        contractAddress  = address(this);

        return true;

    }

}

//------------------------------------------------------------------------------------
//----- Master
//----- Initialize Customer Master with Customer Name and Total Budget
//------------------------------------------------------------------------------------

pragma solidity ^0.4.15;

contract Template {

    bytes32  public custName;
    bytes32  public custLoc;
    address  public contractAddress;

    function Template () {

        custName            = "0xDEFAULT";
        custLoc             = "0xDEFAULT";
        contractAddress     = address(this);

    }

    function AssignCustomerAttributes (bytes32 _custName, bytes32 _custLoc)
        returns (bool isSuccess) {

        custName    = _custName;
        custLoc     = _custLoc;

        contractAddress  = address(this);

        return true;

    }

}

//------------------------------------------------------------------------------------
//----- Master
//----- Initialize Customer Master with Customer Name and Total Budget
//------------------------------------------------------------------------------------

contract Master {

    address  public     masterContractAddress;
    bytes32  public     masterName = "";
    Template    myCustTemp;

    function Master () {

        masterContractAddress = address(this);

    }

    function updateOwnerName (bytes32 _masterName)  {

        masterName = _masterName;

    }

    function createCustomer (bytes32 _custName, bytes32 _custLoc)  returns (bool flag) {

        Template myCust = new Template();

        if (myCust.AssignCustomerAttributes(_custName, _custLoc)) {

            return true;

        } else return false;

    }

}


texts: Web3.js call() on view function on Smart Contract is failing

texts:
I am trying to access a simple variable on my smart contract, locally inside my nodejs application. The relevant parts of my contract look like this
import "@openzeppelin/contracts/utils/Counters.sol";

contract MyContract is ERC721, Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    function getToken() public view onlyOwner returns (uint256) {
        return _tokenIds.current();
    }

}

However when i try to call that function in my javascript code using web3.js, i get an error
const tokenId = await Contract.methods.getToken().call()

Error:
(node:49556) UnhandledPromiseRejectionWarning: Error: Returned error: execution reverted

I have no idea why this is happening or how to debug it really. Seems simple enough so not sure what i've done wrong. Any help would be really appreciated.


texts: During fork, how tx that was sent from full node is been mined on the two blockchains?

texts:
My full node connected to 0,...,n peers and follows the longest chain after Istanbul fork - the miner's chain.

General transaction flow: full-node get the tx, validates and broadcast to its peers.

If I understand right the only way it reaches the Istanbul fork chain is that a peer of my node will be connected to the Istanbul chain.

Is it possible to be a mixed peer, that has peers on Miner's chain and another peer on the Istanbul chain?


texts: Puppeth running on Mac with localhost always return err="docker configured incorrectly: bash: docker: command not found\n"

texts:
Anybody tried running puppeth on Mac (Sierra or higher) with localhost as the servers with any success? Please share it here, because I always get
err="docker configured incorrectly: bash: docker: command not found\n"

Docker version:
Client:
 Version:   17.12.0-ce
 API version:   1.35
 Go version:    go1.9.2
 Git commit:    c97c6d6
 Built: Wed Dec 27 20:03:51 2017
 OS/Arch:   darwin/amd64

Server:
 Engine:
  Version:  17.12.0-ce
  API version:  1.35 (minimum version 1.12)
  Go version:   go1.9.2
  Git commit:   c97c6d6
  Built:    Wed Dec 27 20:12:29 2017
  OS/Arch:  linux/amd64
  Experimental: true

$ ./puppeth -v
puppeth version 0.0.0

I tried this with Linux VM and it works ok (after adding the user logged on into docker group). But for Mac, it always produce that docker not found. While tested with ssh localhost, then run docker it's there.

Please share and help how to do this on Mac OS. Thanks.


texts:
I'm using RunKit to test out very simple code that just imports web3 and creates an instance of it. For some reason I get an error saying:

  Cannot find module 'bignumber.js'

This is the code.

If you're wondering why I'm using RunKit, it's because I keep getting a bunch of errors when trying to install web3 on my machine so I thought I'd use RunKit just to play around with Web3.


texts: Is it possible to send transaction in Binance Smart Chain using web3 and ethereumjs-tx?

texts:
I want to send transaction in Binance Smart Chain and I got an error: new Error("Chain with name " + chain + " not supported");
const Tx = require('ethereumjs-tx').Transaction;
const Web3 = require('web3');

const web3 = new Web3("https://mainnet.infura.io/v3/xxx");

const privKey =
    Buffer.from('xxx', 'hex');
const addressFrom = '0xXXX';
const addressTo = '0xXXX';

web3.eth.getTransactionCount(addressFrom, (err, txCount) => {
        const txObject = {
            nonce: web3.utils.toHex(txCount),
            to: addressTo,
            value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
            gasLimit: web3.utils.toHex(100000),
            gasPrice: web3.utils.toHex(web3.utils.toWei('100', 'gwei'))
        };

        const tx = new Tx(txObject,  {'chain':'smart chain'});
        //const tx = new Tx(txObject,  {'chain':'56'});
        //const tx = new Tx(txObject,  {'chain':'binance'});
        tx.sign(privKey);

        const serializedTrans = tx.serialize();
        const raw = '0x' + serializedTrans.toString('hex');

        web3.eth.sendSignedTransaction(raw, (err, txHash) => {
            console.log('txHash:', txHash)
        });
    }
);

And if using these libraries it is impossible to send a transaction, what is better for me to use to send a transaction in Smart Chain?
I found a couple of sites https://docs.binance.org/smart-chain/wallet/wallet_api.html and https://github.com/drunken005/binance-utils but it seems to me they are for a regular Binance network (as I see wallets in examples start with bnb...) or am I wrong?


texts:
Is there any way to enable/disable compiler optimisation when using

web3.eth.compile.solidity(...)

PS: using solc-js is not considered


texts:
Yesterday I have installed the Ethereum-Wallet on my Mac.

When it was installing, a popup showed up to exchange some bitcoins into ethers using an app called Shifty.

I made the transfer, and the bitcoin transaction was confirmed.

Even after the bitcoin transaction confirmation, the ethers doesn't showed up in my wallet. Reading about that on the internet, I saw that some people had this problem, and they only need to wait the full sync to the wallet be updated with the correct information.

Today my sync is complete, and I don't have the ethers yet.
Worse than that: when I inspect my address on etherchain, it says that address is not found

Anyone have any idea on how to solve this?


texts: Ipfs. Adding files using http request in meteor

texts:
Good day,

I've spent some time trying to upload file to ipfs using http request (from meteor).

Meteor.startup(() => {
  // code to run on server at startup
        Meteor.methods({
                "getFile": function(){
                        var results = HTTP.get('http://127.0.0.1:5001/api/v0/object/get', {timeout:5000, params:
                        {"arg": "QmcNHzJeDphzamLVgKq1R3wmFXqw8EbWLVS6qhAPGohobM",
                        "encoding": "json"}});
                        return (results)
                },
                "uploadFile": function(){
                        var results = HTTP.post("http://127.0.0.1:5001/api/v0/add", {timeout:5000, params:{
                        "path": "/home/shultzi/trial.txt",
                        "stream-channels": "true",
                        "arg": "/home/shultzi/trial.txt",
                        //"Content-Type": "multipart/mixed",
                        //"file": "trial.txt"
                        //"Content-Type": "multipart/form-data"

                        }, header: {
                        //"Content-Type": "application/octet-stream",
                        "enctype": "multipart/form-data",
                        "Content-Type": "multipart/form-data",
                        }});
                    return (results)
            }

    })
})

The first http request (getFile) works just fine, but when I'm trying to upload the file I constantly get the error message

  "File argument 'path' is required"

. I've tried to modify my http request in many ways, adding stream-channels and changing multipart, but nothing seems to work.

I know there're some js apis out there, but I really want to work with my own http requests.

I'll highly appreciate any type of help, suggestion or insight you might have!


texts: How to set msg.value in solidity function call

texts:
If I have a function:

contract one {
      function buyTokens(address _beneficiary) public payable {
        require(msg.value == 1 ether);
       // do something...
      }
}

How do I call that function and also pay ether using solidity?

contract two {
    ...
    function doBuy(uint _amount) public {
       one.buyTokens(msg.sender, _amount);
    }

How do I set msg.value as part of the function call?


texts: Can chain states be processed faster or in parallel? (geth full node syncing)

texts:
I am trying to understand more about chain states. Basically Geth is capable of downloading blocks pretty fast now, but getting "known" and "pulled" states takes much longer and seems to be bottlenecked in an unclear way.

syncing chain states exclusively doesn't use much CPU, it seems to use a lot less network bandwidth, and not much disk I/O

Is there any insight into why this can't be done faster? It most likely could be optimized, I am just wondering what it is actually doing? I am guessing it asks other nodes for states and sees what the consensus of those states are before processing it again locally. Still seems like certain states could be processed in parallel, like in some kind of graph or tree until it finds a state that is related to a on another branch and waits for that branch to catch up.


texts: Can someone please help me understand address(this) in Uniswap liquidity

texts:
So I'm learning Solidity in creating a new token. I successfully created a token and implemented custom tax and burn functionalities. Now I'm trying to understand the Uniswap liquidity features. The thing I don't understand is the address(this) function. In many example code's I see liquidity being added FROM this address and the pair tokens are stored there aswell.
However, how do I access this address through metamask? How are the tokens stored there? Does a simple contract where totalSupply is transferd to owner() or (msg.sender) also have tokens in address(this)? Address(this) totally confuses my mind.
So this piece of code:
uniswapV2Router.addLiquidityETH{value: ethAmount}(
        address(this), //What is this address, shouldn't this be the owner address?
        tokenAmount, //Custom token amount
        0, // slippage is unavoidable
        0, // slippage is unavoidable
        address(this), //Liquidity tokens are stored here and are inaccesible?
        block.timestamp
    );

So in this code example above. The first parameter and the second last parameter is address(token). The first parameter should be according to the docs "The contract address of the desired token." Which is my own token of course. Now the second param is the amount of this token. How does address(this) contain tokens to add to the liq pool? The second last param is according the docs "Recipient of the liquidity tokens.", are they inaccessible?


texts:
I bought 73 eos tokens using metamask a month ago.
I was always able to see the tokens on metamask till today, when they disappeared. I can only see them on the EOS distribution App now.


texts: Won't Casper mean that the processing power of the network is reduced?

texts:
Something just occurred to me. The whole point of Ethereum is to act as a giant global computer. Currently that computer utilises many thousands of GPUs.

When we switch to Casper I will end up mining something else and I will stake my Casper wallet on something like a raspberry pi, I'd imagine that lots of other people will do the same thing.

I understand that things will be more efficient without PoW but surely this huge drop in resources will impact the performance of smart contracts?

Joe


texts:
I have trying to store a JSON string in my solidity code string variable, it only stores the string on the constructor, but if  try and store the same data in the function call it never saves it.

contract BOLData {

    string public SData;
    string public SCData;

    function BOLData(string S_Data)
    {
        SData= S_Data;
        SCData= '';
    }
    function getSData() constant returns (string retVal)
    {
        return SData;
    }
    function setSCData(string SC_Data)
    {
        SCData = SC_Data;
    }
    function getSCData() constant returns (string retVal)
    {
        return SCData;
    }

}


texts:
I have a problem when get string value from smart contact:

pragma solidity >=0.4.22 <0.7.0;
pragma experimental ABIEncoderV2;

contract Election {
    // Model a Candidate
    struct Candidate {
        uint256 id;
        string name;
        uint256 voteCount;
    }

    // Store accounts that have voted
    mapping(address => bool) public voters;
    // Store Candidates
    // Fetch Candidate
    mapping(uint256 => Candidate) public candidates;
    // Store Candidates Count
    uint256 public candidatesCount;

    // voted event
    event votedEvent(uint256 indexed _candidateId);

    constructor() public {
        addCandidate("Candidate 1");
        addCandidate("Candidate 2");
    }

    //vote condinate name
    event voteCandidatEvent(string[] _arr);

    function getListCandidate() public returns (string[] memory) {
        string[] memory arr = new string[](candidatesCount);

        for (uint256 i = 0; i < candidatesCount; i++) {
            Candidate memory _candidate = candidates[i];
            arr[i] = _candidate.name;
        }

        emit voteCandidatEvent(arr);
        return arr;
    }

    function addCandidate(string memory _name) public {
        candidatesCount++;
        candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
    }

    function vote(uint256 _candidateId) public {
        // require that they haven't voted before
        require(!voters[msg.sender]);

        // require a valid candidate
        require(_candidateId > 0 && _candidateId <= candidatesCount);

        // record that voter has voted
        voters[msg.sender] = true;

        // update candidate vote Count
        candidates[_candidateId].voteCount++;

        // trigger voted event
        emit votedEvent(_candidateId);
    }
}

I compiled the contract via solcjs Election.sol --bin --abi --optimize -o ./output, and then generate java code with web3j-4.0.1.

When I call function getVoteCandidatEventEvents, the error below is raised:

Election_sol_Election.VoteCandidatEventEventResponse recipt = contract.getVoteCandidatEventEvents(contract.getListCandidate().send()).get(0);
                String s = recipt._arr.get(0);

Exception : org.web3j.abi.datatypes.Utf8String cannot be cast to java.lang.String

How can I solve it?


texts: Private Blockchain transactions throughput

texts:
I'm looking for a way to maximize the transactions throughput of my ethereum private blockchain.

I noticed that calling eth.sendTransaction() takes about 0.3 seconds to complete which is a considerable amount of time for me.

I limited the mining difficulty in the genesis file but this delay is even before the mining starts.

So is there a way to have faster transactions in ethereum?


texts: Why does Bitcoin need to change receiving address for privacy, but not Ethereum?

texts: Exactly as it says in the title. Why is it that, for the sake of privacy, wallets change your Bitcoin receiving address for every transaction, but not for Ethereum. Do they just not care about Ethereum privacy as much as they care about Bitcoin privacy, or are there privacy protections in place for Ethereum that Bitcoin doesn't have? I doubt it's the latter because you can publicly view transactions to Ethereum addresses just like you can with Bitcoin, so why the difference in treatment?


texts: Warning: Unreachable code in for loop in solidity version 0.5.3

texts:
As soon as I upgraded the code from solidity version 0.5.2 to 0.5.3, it showing warning in my for loop.

Warning: Unreachable code.
for(uint256 i=0; i < totalHoldTransactions; i++ ){
                                            ^-^

This SO article which gives idea in other programming languages. But I am still not sure why that increment variable is unreachable!

Any ideas will be appreciated. Thanks.


texts:
A question about geth attach. I am opening a geth console and then in another terminal I make geth attach. Everything looks OK when I execute web3 commands etc. (like eth.accounts) in both terminals. Then, I deploy a contract through the console (1st terminal) using loadScript(), and as usual it is successfully mined as I see from the console messages. However, after that moment, when I want to use the deployed contract through the attached console (2nd terminal), I am unable to do it. It does not event see it.

Any ideas?


texts: contract invoke another contract function

texts:
Parity version: 1.6.8
  Operating system: MacOS
  And installed: docker

start on

  --chain dev

here's test contract A

contract A {
    mapping (address => uint256) balances;
    function testFunc1(address _to, uint256 _value) {
        balances[_to] += _value;
    }
    function testFunc2(address _to, uint256 _value) {
        balances[_to] += 1;
        balances[_to] += 1;
    }
    function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
    }
}

here's invoker contract B

contract B {
    function testSend1(address _contract, address _to, uint256 _value) {
        _contract.call.gas(400000)(bytes4(keccak256("testFunc1(address,uint256)")), _to, _value);
    }
    function testSend2(address _contract, address _to, uint256 _value) {
        _contract.call.gas(400000)(bytes4(keccak256("testFunc2(address,uint256)")), _to, _value);
    }
}

  excute A's testFunc1 & testFunc2 is work
  excute B's testSend1 is work
  why excute B's testSend2 happened nothing ?【actually, the selected address should +2 on balances】

What's wrong with my contract code?


texts: Why are contracts in Ethereum Blockchain called as 'Smart Contracts'?

texts: We write smart contracts in ethereum blockchain. How did contracts get its name as Smart Contracts? Why are they called as Smart Contracts?


texts: Gas estimation failed in geth private network with remix

texts:
My environment is Web3 Provider (127.0.0.1:8080) which is a private network in my Mac. I have tried to deploy and run transaction in Remix with a simple solidity as follows.

pragma solidity >=0.4.21 <0.6.0;
contract Simple {
   uint256 storedNumber;

   function setNumber(uint256 x) public {
        storedNumber = x;
   }
   function getNumber() public view returns (uint256) {
        return storedNumber;
   }
}

Deployed contract well, but it made error at transaction as follows.

"Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? gas required exceeds allowance (8000000) or always failling transaction."

My Genesis.json file as follows.

{
    "config": {
        "chainId" : 15,
        "homesteadBlock" : 0,
        "eip150Block" : 0,
        "eip155Block" : 0,
        "eip158Block" : 0,
        "constantinopleBlock": "0",  // Added here
    },
    "nonce" : "0x0000000000000042",
    "timestamp": "0x00",
    "parentHash":
    "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",
    "gasLimit": "0x800000",
    "difficulty": "0x400",
    "mixhash":
    "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x3333333333333333333333333333333333333333",
    "alloc": {
        "0x4D2A52F18D5dC0e2A0E44945D387346FdD4eCc2f": {
            "balance": "10000000000000000000"
        }
    }
}


texts: The official library for work with ethereum payments

texts:
I looking for way to generate ether wallet (priv-pub pair), handle incoming transaction to that wallet and make/push to network transaction from it.

How to do that via go-ethereum or pyethereum (full node sync via geth is in progress now)?


texts: How can you implement two way pegged Ethereum  Ethereum sidechain?

texts:
If you want to create an Ethereum sidechain which is two-way pegged to main (public or private) Ethereum, how can you implement sidechain?

For example,

How can you lock ether?
How can you verify main net ether?


texts: Uncaught ReferenceError: TruffleContract is not defined 2

texts:
Firstly, I have viewed (Uncaught ReferenceError: TruffleContract is not defined) and am getting the same error for my smart contract:

However, I received this error while having the contract script defined in index.html:
<script src="js/truffle-contract.min.js"></script>

Additionally, I have tried adding the turffle contract through npm by adding var contract = require("@truffle/contract"); to app.js and have bundled with browserify which results in an Unexpected identifier in app.js:

Both the solutions purposed in 2018 to this issue seem to have failed. Perhaps I am using browserify with App.js wrong? Or am missing something since the deprecation of truffle-contract to @truffle/contract?
App.js Code:
    App = {
  web3Provider: null,
  contracts: {},
  account: '0x0',
  loading: false,
  tokenPrice: 1000000000000000,
  tokensSold: 0,
  tokensAvailable: 750000,

  init: function() {
    console.log("App initialized...")
    return App.initWeb3();
  },

  initWeb3: function() {
    if (typeof web3 !== 'undefined') {
      // If a web3 instance is already provided by Meta Mask.
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // Specify default instance if no web3 instance provided
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
      web3 = new Web3(App.web3Provider);
    }
    return App.initContracts();
  },
  initContracts: function() {
    $.getJSON("NyankoCoinSale.json", function(nyankoCoinSale) {
      App.contracts.NyankoCoinSale = TruffleContract(nyankoCoinSale);
      App.contracts.NyankoCoinSale.setProvider(App.web3Provider);
      App.contracts.NyankoCoinSale.deployed().then(function(nyankoCoinSale) {
        console.log("Nyanko Coin Sale Address:", nyankoCoinSale.address);
      });
    }).done(function() {
      $.getJSON("NyankoCoin.json", function(nyankoCoin) {
        App.contracts.NyankoCoin = TruffleContract(nyankoCoin);
        App.contracts.NyankoCoin.setProvider(App.web3Provider);
        App.contracts.NyankoCoin.deployed().then(function(nyankoCoin) {
          console.log("Nyanko Coin Address:", nyankoCoin.address);
        });

        App.listenForEvents();
        return App.render();
      });
    })
  },


texts: Contract methods calls return empty array

texts:
I'm quite stuck with this issue. It seems like it must work, but it doesn't :D

Have a contract on rinkeby network which is working perfectly through remix(load by address) and truffle console. However method calls through web3 client refuse to work.

init:

import Web3 from 'web3';

// @ts-ignore
const web3 = new Web3(window.web3.currentProvider);

***got address & abi***

export default new web3.eth.Contract(abi, address);

usage example:

console.log(registryContract.options.address);
console.log(registryContract.methods);
const owner = await registryContract.methods.owner().call();

In console.log() i can see the actual contract address and methods.
Metamask is active and web3.eth.defaultAccount shows me my correct account at rinkeby network => provider must be working.

calling the owner from remix working. with web3 i'm getting an empty array as response. Same for other methods calls.

What is possible going wrong? "web3": "^1.0.0-beta.37"


texts: Raspberry Pi: Geth slow sync every time reboot

texts:
Since the first sync (I copy the chaindata folder from my local machine to the RPI), every time I start the RPI it takes hours to just sync 20k blocks.

I tried geth --cache=512, etc.

I am using WIFI and the OS is the one given in http://ethembedded.com


texts: Assigning a 2D byte array and accessing via Web3

texts:
So I'm trying to work with two-dimensional byte arrays and am experiencing some results that I don't quite understand. I am using Truffle v2.0.4 for compiling/deploying my contracts with ethereumjs-testrpc as a blockchain backend.

Consider this super simple contract. It initilizes a 2D array of bytes, assigns the third element in the first array, and returns:

contract Sandbox {

    function retArr()
    public constant returns (byte[3][10] ret) {
        ret[0][2] = byte(2);
    }

}

I can then access this contract via Truffle's Web3 wrapper:

Sandbox.deployed().retArr().then(function(res) {
    console.log(res)
})

Which produces the following output:

[ [ '0x00', '0x00', '0x02' ],
  [ '0x00', '0x02', '0x00' ],
  [ '0x02', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ],
  [ '0x00', '0x00', '0x00' ] ]

The first child array looks correct (0x02 is assigned to the third position), but then 0x02 pops up in the second and third arrays as well.

Why did multiple elements get assigned with one call? If this is expected behavior, what's the rationale behind this design decision? How can I only assign one element at a time in a 2D array?


texts: One big transfer function or separated over multiple functions

texts:
Is it better to just keep all the logic within the transfer function or separate it out over 3 functions like I did? Thanks in advance!

function transfer(address _to, uint256 _value) public returns (bool) {

    require(_to != address(0));
    if (updateBalance(_to, _value)) {
        if(allowedContracts[_to]) {
            BIHReceiver receiver = BIHReceiver(_to);
            receiver.tokenFallback(msg.sender,_value);
        }
        Transfer(msg.sender, _to, (_value.sub(feePaid)));
        Transfer(msg.sender, feeWallet, (feePaid));
    }
    return true;
}

function updateBalance(address _to, uint256 _value) public returns (bool) {

    require(_to != address(0));
    if (checkBalance(_to,_value)) {
        uint256 feePaid = (_value.mul(fee).div(10000);
        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value.sub(feePaid));
        balances[feeWallet] = balances[feeWallet].add(feePaid);
        return true;
    }
}

function checkBalance(address _to, uint256 _value) public returns (bool) {

    require(_to != address(0));
    if(_value > 0) {
        if(balances[msg.sender] == 0) {
            addresses[indexes[msg.sender]] = addresses[lastIndex];
            indexes[addresses[lastIndex]] = indexes[msg.sender];
            indexes[msg.sender] = 0;
            delete addresses[lastIndex];
            lastIndex--;
        }
        if(indexes[_to]==0) {
            lastIndex++;
            addresses[lastIndex] = _to;
            indexes[_to] = lastIndex;
        }
        return false;
    } else {
        return true;
    }
}


texts: How to wait until transaction is confirmed web3.js?

texts:
I am new to web3. I am trying to connect UI with web3. Metamask version is 6.0.1 and web3 version injected by (don't know who), but it is 0.20.3.
Following is my code to send ethers to a function of my contract which is inside using Oracalize as well,

var option = {from: accounts[0], to: contractAddress, value:4000000000000000};
        mycontract.update.sendTransaction(option, function(error,result){});

I want to run some other code on basis of confirmation of this transaction. What is the best way to wait until transaction is confirmed and then I can run some more code? Make sure, I am stuck with this version of web3 and I cannot use 1.0.0 version and so does the "send" function.


texts:
Im trying to estimate the gas of this kind of tx to send to a contract

 var estimateGas = this.web3.eth.estimateGas({
  to: toContractAddress,
  gasPrice: this.web3.toHex(40000000000),
  nonce: 10,
  value: this.web3.toHex(forwardingValueInWei)
})

And I get as return this value: 4 712 388
which is super big gas, while the MyEtherWallet estimate  127 943

are those estimations the same unit?
Why is too big from web3?


texts: How to sort values in a map in solidity?

texts:
I am trying to create a leaderboard depending upon who has received maximum votes.
I have implemented the following code:

function dashboard(bytes32[] candidateListNew) public returns(bytes32[])
        { for(uint i = 0; i < candidateListNew.length; i++){
        for(uint j = i+1; j < candidateListNew.length; j++){
            if(votesReceived[candidateListNew[i]] > votesReceived[candidateListNew[j]]){
                uint8 temp = votesReceived[candidateListNew[j]];
                votesReceived[candidateListNew[j]] = votesReceived[candidateListNew[i]];
                votesReceived[candidateListNew[i]] = temp;
        }
      }
    }
    return votesReceived[candidateListNew]; //gives me conversion type error
 }

struct voter {
     bytes32 votedFor;
     bool hasVoted;
  }

  mapping (bytes32 => uint8) public votesReceived;
  // Mapping for persons who have already voted
  mapping (bytes32 => voter) public voters;

  bytes32[] public candidateList;
  bytes32[] public candidateListNew;

I am able to sort the values but I am having difficulty sorting the keys(candidate names) based on the values.

Any help would be appreciated.
Thank you!!


texts: How to check amount that was mined? And other concerns

texts:
I am fairly new to the whole concept of ETH and mining. Firstly, I know that my setup is weak for mining, but I wanted to get some knowledge and experience before investing money in mining...

My "setup" is a MacBook Pro 15 early 2015. I know, I know. Not the best way to mine ETH...

I have installed go-ethereum, created an account, I ran geth --rpc for about 3 days, it went to block no. arount 3900000 (I'm giving You this information, I don't know if it is relevant).

After that I started mining. It's been another few days of mining, and when I do geth attach and I check the amount, both commands, either this one: eth.getBalance(eth.coinbase), or this one: web3.fromwei(eth.getbalance(eth.coinbase) ether) are both returning 0.

Does that mean that I haven't dug up even a 0,000000000000000000001 ETH, or am I doing something completely wrong?


texts: Can I run a javascript file using geth attach?

texts:
I want to automatize one thing. Aftert installing the Quorum nodes, I have to run:

docker exec -it quorum_node1_1 geth attach /qdata/dd/geth.ipc

Then I am pasting the JS code

But I want to automatize this in a bash script. Can I somehow pass the javascript file as an argument in this command?

EDIT:

I have created a command like this:

docker exec -it quorum_node1_1 geth --exec "loadScript(\"/deploy.js\")" attach /qdata/dd/geth.ipc

But when I run it it returns

false

And that's all...


texts: Why does ethereum chaindata sometimes sync while syncing?

texts:
I am doing a fresh geth 1.9.18-stable sync, which I believe is fast by default. I am keeping an eye on the size of the .ethereum/geth/chaindata/ directory and have noticed that it does not increase monotonically. Sometimes the size goes down.
Why?


texts: Does Ethereum support just bilinear pairing calculation not the pairing check?

texts: I need to implement bilinear pairing calculation on my contract. Specifically, I have uploaded some parameters and need other users to calculate the pairing for me and I will pay for them if their answers are correct. Therefore, I need to check their answers on my contracts, that is, implement the pairing equation. I have already found some similar solutions just like zksnark contracts which use the precompiled contracts. But these schemes just provide the pairing check module e(p1[0],p2[0])*e(p1[1],p2[2])...=1. What I want is to get whether e(a,b) is equal to P1. I hope someone can give me some hints or use precompiled contracts to implement my pairing calculation demand. Thanks!


texts: What if I find a bug in my published smart contract? What is the best way to resolve it? I guess I can't undo the contract and some folks can still use it?


texts: Parity - Syncing Very Slow Around Block 4.700.000 and overload disk

texts:
I'm running:

Which Parity version: v1.10.7-stable-ba79cad-20180619/x86_64-linux-gnu/rustc1.26.2
Which operating system Linux: Centos 7
installed: from source

My parity config

db_compaction = "ssd"
pruning = "archive"
fat_db = "off"
cache_size = 4096

Computer uptime more than 5 days, and i get: 4.731.002 blocks and disk is: 452G/500Gb SDD
now, syncing very slow and disk is full. Where did I go wrong? eth blocks occupy more drive space.
When disk full 500Gb, what should I do?
Please help me


texts:
I restored old UTC key file from another computer: UTC--2016-07-27T13-36-55.890168500Z--89f8704b0fdaabbb51c128c7fd9664ef218e1795
and added it into keystore folder.
I also created fresh account with new installation:
UTC--2017-05-31T18-10-39.282369700Z--f89d2b29ee41dd4ad71e720ecf4b883f14137d56
When I open Ethereum wallet and Mist I only see the new one inside.

How to display old account from UTC file? Is there additional step to restore/import the old account?

Thank you!


texts: MetaMask - Quorum - Network - Custom RPC - Could not fetch chain ID. Is your RPC URL correct?

texts:
Instructions from scratch
https://docs.goquorum.consensys.net/en/latest/Tutorials/Creating-A-Network-From-Scratch/
genesis.json
Directly from the tutorial:
"chainId": 10,
startnode1.sh
#!/bin/bash
PRIVATE_CONFIG=ignore nohup ~/quorum/build/bin/geth --datadir new-node-1 --nodiscover --verbosity 5 --networkid 31337 --raft --raftport 50000 --rpc --rpcaddr 0.0.0.0 --rpcport 22000 --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3,quorum,raft --emitcheckpoints --port 21000 >> node.log 2>&1 &
node.log
Snippet:
INFO [10-28|07:05:16.741] Initialised chain configuration          config="{ChainID: 10 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: 0 EIP155: 0 EIP158: 0 Byzantium: 0 IsQuorum: false Constantinople: 0 TransactionSizeLimit: 0 MaxCodeSize: 0 Petersburg: <nil> Istanbul: <nil> PrivacyEnhancements: <nil> Engine: unknown}
IsQuorum: false - unsure?
Running cakeshop
https://docs.goquorum.consensys.net/en/latest/HowTo/GetStarted/Cakeshop/
java -jar cakeshop-0.11.0.war

I would like to send some transactions to see the block mining process...
http://localhost:8080/manage.html

It super easy for sure, if you know it. New to the Quorum business. Quorum and Metamask are on the same box, no need to enable CORS: How to connect Quorum with Metamask?
EDIT: Not sure if that matters but I did geth --datadir new-node-2 init genesis.json using the default geth not quorum geth. See this issue not sure if that matters.


texts: Issues running oraclize callback function

texts:
I've been trying to run two contracts on a private net, using oraclize brigde. First one runs perfectly, however the second one for some reason doesn't call the callback function (despite having sent a query) unless I delete some of the code from the function.
Here is the problematic part of the code from it:

pragma solidity ^0.4.16;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
import "github.com/Arachnid/solidity-stringutils/strings.sol";

contract CFDBroker is usingOraclize {

   using strings for *;

   mapping (uint => uint) instruments;
   mapping (bytes32 => uint) queries;
   uint public GOLD;
   uint public EURUSD;
   uint public DJI;
////////////////////////////////////////////////////////////////////////////////

   function sendFunds() payable {

       getData();

   }
////////////////////////////////////////////////////////////////////////////////

   function __callback(bytes32 myid, string result, bytes proof) {

       require(msg.sender == oraclize_cbAddress());

       if (queries[myid] == 1){
           //parse and update gold
           var s = result.toSlice();
           GOLD = parseInt(s.beyond("$".toSlice()).until("/".toSlice()).toString())*100;
           instruments[1] = GOLD;

       } else{
           if(queries[myid] == 2){
               //parse and update eur/usd
               s = result.toSlice();
               var r = result.toSlice().beyond(".".toSlice());
               EURUSD = parseInt(s.beyond("$".toSlice()).until(".".toSlice()).concat(r));
               instruments[2] = EURUSD;

           } else{
               if(queries[myid] == 3){
                   //update DJI
                   DJI = parseInt(result)*100;
                   instruments[3]=DJI;

               }
           }
       }

       update();

       //getData(); --supposed source of the problem

   }

   /**
    *  Instrument IDs:
    *  0 - ASK FOR ALL
    *  1 - GOLD
    *  2 - EUR/USD
    *  3 - DJI
    */
   function getData() private{

       queries[oraclize_query(50, "WolframAlpha","gold price in usd")] = 1; //ask for gold
       queries[oraclize_query(50, "WolframAlpha","eur/usd")] = 2; // ask for eur/usd
       queries[oraclize_query(50, "WolframAlpha","DJI price")] = 3; //ask for DJI

   }}

It's a model of a CFD broker, the quoted part is supposed to update prices of 3 financial instruments every 60 seconds. It works fine, when getData() in callback is commented.
All in all, it seems very similar to this problem: link.

The contract is a part of my student project, I'd be very grateful for any help :).


texts:
Is it possible to build DApp which can accept Fiat currency? Because for an existing business to move to blockchain, the existing users should be able to transition to DApp seamlessly. I would like to propose a blockchain solution without hurting the current user base.

Does any blockchain offer this solution? Is hyperledger an option?

Thanks in advance for your time and response.


texts:
I am trying to make an Ethereum contact that accepts ether and gives a key if the payment is enough. Obviously, the key needs to be private until the user pays, but I want this to be a contact such that the user can be sure he'll receive the files in exchange of money.

Is there any way to do this?


texts: I'm planning to run a Ethereum server for getting wallet balances at a specific time, which type of node  should i run, fast sync will work ? or should i go for archive node ?


texts:
I have found this mixer proposal https://hackmd.io/@HWeNw8hNRimMm2m2GH56Cw/rJj9hEJTN?type=view

I'm is interested in this topic, but from my point of view with a current ethereum state it won't work. Let me share my view

Below i described my understanding mixer implementation in Ethereum and possible weaknesses.

General  mixer description:
Address A make a deposit to a mixer contract M. Address B sends to contract M prof that he made a deposit, but the proof doesn't reveal that he was A when he did it, and asks to withdraw his deposit to address C. As soon as there is no connection between A and C mixer successfully does what we expected.
We investigated two possible implementation of such mixer:
zk-SNARKs mixer
Ring signature mixer
zk-SNARKs - when A deposits money he also add a proof (a leaf) to a merkle tree inside the contact. When B wants  to withdraw he send a proof that his leaf exists in the tree and a proof that he has never sent such request before( double spending protection)
Issues with this approach - merkle tree will constantly grow, BarryWhiteHat who investigated this mixer said that he faced problem with amount of computations, for 1.5M (number of leaves) tree it takes 7 minutes to create a proof. We didn't check how much gas it takes to check the proof, but the problem is the merkle tree will grow and grow, and proof generation will became very hard. As I know for now we don't have solution to this problem.

Ring signature mixer - when B wants to withdraw he sends to the mixer a list of public keys (PKs) and proof that he has a private key of one of them, it is impossible to say which public key belongs to B. As soon as the mixer knows public keys which were used for deposit it can confirm that this person can withdraw money, also it makes double spend check.
The main issues with this approach is - the check is quite expensive, to check 5 PKs  the contract spends ~1M GAS, so if you want to withdraw money with let say 1% probability that A and B is the same person, you have to withdraw with 10 PKs ring 1-10 times, if you have a public key in a ring which withdraw money from the mixer before it should be replaced with the ring it took money from, so if you are lucky you can get much better probability then a ring size and you will pay 2M - 20M GAS + (some gas to deposit money).
This method doesn't have problem with accumulation of deposits, computation depends only on size of ring not number of people who made deposits.  But flat ring computation is expensive.

Also we have general Ethereum mixer issue - when B send a withdraw request he must pay for this transaction, and for this he has to have money. It mean that it is impossible to just create a random account and send withdraw request from it. Even if a link between A and C doesn't exist there is a clear link between B and C, if an adversary is able to find a link between A and B he will define that A and C is the same person. As we said before B needs money to use the mixer so A needs some safe way to send this money to B, if A has this way he doesn't need the mixer he can send money to C without mixer. We can create some off chain services to send money to B or play role of B, but it will create a centralization/failure point.
There is a improvement suggestion for ETH2.0 which will let contracts pay for transactions, in this case C can send a transaction to the mixer and the mixer will pay for it. If this suggestion become real the problem with gas trace will be solved.

Combination of problems described above makes mixer implementation in the current version of Ethereum very questionable. By my opinion the fundamental issue is gas traceability. It converts our task from hide from/to to implement hidden/safe gas supply for random accounts. To solve "create hidden transactions" task, we have to have hidden transactions. A snake bites its own tail.

Does anybody knows a good approach which will let us solve these problems and help to convert a mixer to a real application?


texts:
I'm having difficulty getting going with truffle and testrpc.

The steps I've taken are:

Create a blank project and initialise with truffle init
Start testrpc with testrpc

Trying truffle migrate or truffle test then gives me "

Error: authentication needed: password or unlock
at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/errors.js:35:16)
at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/requestmanager.js:86:36
at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:118:13)
at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)

From what I've read this seems like an error with accounts being locked, but testrpc's documentation suggests that by default it will create 10 accounts which are unlocked - unless you specify --secure?


texts:
I am using the following Drizzle (Truffle) component to call a function from a smart contract:

<ContractData contract="Market" method="priceOf" methodArgs={this.props.id}/>

The result is a React Element that contains number in Wei: 4000000000000000

Now, I am saving this in the state, and this is rendered when this.state.price is rendered.
However, when I want to pass {this.state.price} as props price={this.state.price}, it does not work, the error message is that the React element can't be cloned.

Is there any way to get/parse/query/copy the raw data of the React Element? I need that 4000000000000000 as a number (Number() and parseInt() are giving NaN, toString() gives [object Object])


texts: How to check the hashrate per GPU running Ubuntu nvOC

texts:
Running nvOC with 9 1070 GTX GPUs. First time I set it up the hash-rate was 270 (Mining Eth) which make sence, however, it dropped to 240.

All the GPUs still running, I am new to this and I was wondering if there is a way where I can check individual GPU hash rate (So the hash rate per GPU) so that I can diagnose what is wrong.


texts: What is the use of a interface or function without implementation?

texts:
Take, for example, this code.
The interface contains function without implementation, so how it's useful.

pragma solidity ^0.5.0;

interface Calculator {
   function getResult() external view returns(uint);
}
contract Test is Calculator {
   constructor() public {}
   function getResult() external view returns(uint){
      uint a = 1;
      uint b = 2;
      uint result = a + b;
      return result;
   }
}

How does this code working is different from the first one? What are the benefits of using an interface or function without implementation?

pragma solidity ^0.5.0;

contract Test {
   constructor() public {}
   function getResult() external view returns(uint){
      uint a = 1;
      uint b = 2;
      uint result = a + b;
      return result;
   }
}


texts: Ethereum Dapp Account Login Protocol with Metamask

texts:
I'm building an Ethereum dapp for users to use with Metamask. We're going to have an account management system and I was trying to follow this post on how to achieve a "password-less" account system using Metamask: https://hackernoon.com/never-use-passwords-again-with-ethereum-and-metamask-b61c7e409f0d.

However, there is a problem with the suggested protocol as the signed data never changes, so an attacker could just intercept the signed message and could authenticate as that user.

I was trying to find a previously devised public-key algorithm on Wikipedia, but most protocol involve a trust authority -- I don't know if that's necessary here.

What's a simple, but secure or established protocol for authenticating a user in this way? I was considering a nonce system + signing with eth wallet private key.


texts:
So there is a way to call other contract using abstract prototype of that contract.
But what about delegate calls?
I need to split my huge contract into separate pieces.
So i can call my functions via delegate call (to make them able to change global state of main storage).
The problem is that unlike the simple call (using abstract method), i have to call my own functions via such ugly way:
contract_address.delegatecall(bytes4(sha3("foo(uint,uint)")),bar1,bar2);

Is there any way to perform abstract delegate call? Or maybe such plans to add this feature?
Thank you.


texts:
BTCPay Server is a self-hosted, open-source cryptocurrency payment processor for Bitcoin. It also allows to add other crypto currencies like Litecoin, Monero.
But is there a similar open-source project for Ethereum and ERC20 crypto currencies?


texts: Is there somewhere I can find what commands can be used within geth attach, and some examples of scripts as well?


texts: invoking smart contract through geth console

texts:
i am trying in invoke the smart contract through geth i am successful in doing it but the problem is i have a function in the contract which should give me the list of candidates. i getting it but the last item is not getting displayed properly(it is not behaving the way i want ) the code and the output of it is below

pragma solidity ^ 0.4 .25;
pragma experimental ABIEncoderV2;
contract Election {
  //owner of the contract
  address public owner;

  constructor() public {
    owner = msg.sender;
    addCandidate("NOTA");
    addCandidate("BJP");
    addCandidate("CONGRESS");
    addCandidate("JDS");
    addCandidate("others");
    addCandidate("jdu");
    addCandidate("amma-party");

  }

  //storing the valid users added by owner(admin)
  address[] validVoters;

  //store accounts(voters) that have already voted
  mapping(address => bool) voters;

  //logging the actiion performed on voter validation
  event LogAccess(address indexed by, string method, string desc);

  //Candidate structure
  struct Candidate {
    int id;
    string name;
    int voteCount;
    address[] votersList;
  }

  //store names into the array
  string[] candidateNames;

  //store id's into array
  int[] candidateIds;

  //store the Candidates(for final result)

  mapping(int => Candidate) public candidates;

  //store the Candidates id
  int candidateId = 100;

  //adding candidates into list
  function addCandidate(string name) private {
    candidateId++;
    address[] memory votedPeople;
    candidates[candidateId] = Candidate(candidateId, name, 0, votedPeople);
    candidateIds.push(candidateId);
    candidateNames.push(name);

  }

  //to get the list of Candidate id's'
  function getCandidateIds() public view returns(int[]) {
    return candidateIds;
  }

  //to get the list of candidates names
  function getCandidateNames() public view returns(string[]) {
    return candidateNames;
  }

  //adding the valid voters into the array(only owner(admin) of contract can)
  function addVoters(address voter) public {
    require(msg.sender == owner);
    validVoters.push(voter);
  }

  //to delete a voter from the list if required only admin is allowed
  function deleteVoter(address voter) public {
    require(msg.sender == owner);
    for (uint i = 0; i < validVoters.length; i++) {
      if (validVoters[i] == voter) {
        delete validVoters[i];
      }
    }
  }

  //validating the voters
  function isValidVoter(address voter, string method) private returns(bool) {
    for (uint i = 0; i < validVoters.length; i++) {
      if (validVoters[i] == voter) {
        emit LogAccess(voter, method, "successful access(eligible to vote)");
        return true;
      }

    }
    emit LogAccess(voter, method, "access failed(not eligible to vote)");
    return false;
  }

  //voting function
  function vote(int _candidateId) public {
    if (isValidVoter(msg.sender, "vote")) {
      //require to check user as not voted
      require(!voters[msg.sender]);

      //check for valid Candidate
      require(_candidateId > 0 && _candidateId <= candidateId);

      //record the vote
      voters[msg.sender] = true;

      // update candidate vote Count
      candidates[_candidateId].voteCount++;

      //add voter address to the cadidate
      candidates[_candidateId].votersList.push(msg.sender);

    }

  }

  function getVotersList(int id) public view returns(address[]) {
    require(msg.sender == owner);
    return candidates[id].votersList;
  }
}


texts:
I'm trying to migrate a contract into a ganache chain. It needs to use Oraclize - in the end, the plan is to have a private chain using Oraclize via ethereum-bridge.
However, truffle migrate fails with the message:

Error:  *** Deployment Failed ***

"VatValidator" hit a require or revert statement somewhere in its constructor. Try:
   * Verifying that your constructor params satisfy all require conditions.
   * Adding reason strings to your require statements.

    at /Users/alex/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/packages/truffle-deployer/src/deployment.js:364:1
    at process._tickCallback (internal/process/next_tick.js:68:7)

Here's the contract:

pragma solidity >=0.5.0;
import "./Oraclize.sol";

contract VatValidator is usingOraclize {

    string public isValid;

    event newOraclizeQuery(string description);
    event newVATResult(string price);

    constructor() public {
        // oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
    }

    function __callback(bytes32 myid, string memory result, bytes memory proof) public {
        require (msg.sender != oraclize_cbAddress());
        isValid = result;
        emit newVATResult(isValid);
        update();
    }

    function update() public payable {

        emit newOraclizeQuery("Oraclize query was sent, standing by for the answer.");

        oraclize_query("URL", "json(http://url.com).valid",'{"arg1":"abc", "arg2":"def"}');

    }
}

I don't have any revert or assert statements at all in the constructor however.


texts: WalletUtils.loadCredentials takes a while to answer,about 2 minutes

texts:
WalletUtils.loadCredentials takes a while to answer, about 2 minutes, running on the android devices,
Credentials credentials = WalletUtils.loadCredentials("password","path to file");
just this method, none other codes, has anyone ever encountered this problem?thanks.


texts: What's the order of execution for multiple function modifiers?

texts:
I don't know why nobody is asking this question (I've done my homework and did tons of Googling for an answer) but I am having hard time understanding how function modifiers actually work.

Sure it's trivial when you just use one modifier, or if you use the _ notation always at the end. But I come across code that looks something like this:

modifier modA {
  // verify something
  _;
  // verify something
  _;
}
modifier modB {
  // verify something
  _;
  // verify something
  _;
}
modifier modC {
  // verify something
  _;
  // verify something
  _;
}

function Fun() modA modB modC {
  // Do something
}

Then I finally realize that I have had no idea what is going on underneath.

In above case, how is it supposed to work? Looking at the documentation doesn't really help because it just says the modifiers simply replaces the _ with the function code. But what if there are multiple of these?

So if we go from modA to modB, do the _ get replaced with the next modifier? What do they mean by "get replaced by the original function"?


texts: Sending a transaction with a value parameter to a contract method

texts:
Here's a simple contract:

pragma solidity ^0.4.0;
contract Test {
    uint public sum;
    function makeRequest(){
      sum += msg.value;
    }
}

Here's JS code:

function onLoad(){
    const web3 = window.web3;
    const address = "0x26c5267d77348d2748f075d884c75f1a6274149b";
    const abi = [{"constant":false,"inputs":[],"name":"makeRequest","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"sum","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}];
    const contract = web3.eth.contract(abi).at(address);

    const txo = {
        from: "0x6Ca2f35Ff53c3764ADD78d52378bbFb41CbEef63",
        value: 10000000000000000
    };
    contract.makeRequest(txo, (error, result) => {});
}

Executing JS code results in failed transactions like this one.
Error:

  Bad jump destination

What am I missing?


texts: In truffle, a dapp is deployed using the port of running geth node (in testnet). Then how will another machine node will communicate to that dapp because it is impossible to run a node on same port with different machine?


texts: About security problem on hard fork named "Spurious Dragon"

texts:
What is the specific problem with the secuirty of "Spurious Dragon" (EIP-170)?
I've heard that EXTCODESIZE isn't checked when accessing the constructor and doesn't cost a gas fee, but I'm not sure why the attack code can generate a looping calculation.
Can you find a specific PoC for that vulnerability?


texts: My ethereum wallet transactions not going through

texts: Hi I know this has been asked but I used my ethereum wallet to do a test transaction I moved the gas slider all the way up and my transaction still has been processing for over 5 hours..am I doing something wrong? What can I check?..https://etherscan.io/tx/0x5b6f64f0577d13fb85b877c970094867980be39e0d834da302f429e0e8ef6857 ..Can someone give me some advice? Thanks guys


texts: solidity, how to keep it DRY for similar but different structs?

texts:
I have a bunch of Actions in the dApp i'm building. Each action has different data associated with it. At the same time, they have a few common fields. Is there a way to model this to handle the different data associated with it?

Or do I have to make different structs for each action type I have?

Note that If I have 1 struct for all my action types it makes my code cleaner to write. I.e. I can keep the loop and common testing conditions DRY.

If I have multiple structs I have to loop through each different struct so that adds one loop per struct (plus other code that tests common members). Given this concern, is there a suggested way to handle structs with different data?

enum ActionType { A, B, C }
struct Action {
    ActionType actionType;
    string name;
    string description;
    uint createdAt;
    // should i put optional data fields?
    string someFieldOnlyExistsForA;
    bool someBoolOnlyExistsForB;
    uint someIntOnlyExistsForC;
}

//example what i mean

Action[] actions;

for (uint i = 0; i < actions.length; i++) {
    if (actions[i].createdAt < now - 1000) {
        if (actions[i].actionType == A) {do something with the string field}
        if (actions[i].actionType == B) {do something with the bool field}
        if (actions[i].actionType == C) {do something with the int field}
    }
}

vs

for (uint i = 0; i < A_actions.length; i++) {
    if (Aactions[i].createdAt < now - 1000) {
    }
}
for (uint i = 0; i < B_actions.length; i++) {
    if (Bactions[i].createdAt < now - 1000) {
    }
}
for (uint i = 0; i < C_actions.length; i++) {
    if (C_actions[i].createdAt < now - 1000) {
    }
}


texts: How can you test with a mock when the address is hard coded in the real contract?

texts:
For testing purposes, is there any way to replace a contract referenced by a hardcoded address with a mock?

I'm defining an interface in my contract

address interfaceAddress = 0x...;
IInterface if = IInterface(interfaceAddress);

But now I need to test against a mock version of this contract but don't know how without passing the interfaceAddress as an argument in the constructor. I do not want to do this because I'm interfacing with a lot of contracts and don't want to have to pass all of them in the constructor.


texts:
I have a truffle project which was running on another machine without problem. But now I'm trying to npm install and I'm getting this error:

>truffle install

Error: project ID is required
    at Object.InvalidResponse (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\ethpm-registry\~\truffle-contract\~\web3\lib\web3\errors.js:35:1)
    at C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\ethpm-registry\~\truffle-contract\~\web3\lib\web3\requestmanager.js:86:1
    at XMLHttpRequest.request.onreadystatechange (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\web3\lib\web3\httpprovider.js:128:1)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:64:1)
    at XMLHttpRequest._setReadyState (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:354:1)
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:509:1)
    at IncomingMessage.<anonymous> (C:\Users\Home\Desktop\Authcoin-truffle\node_modules\truffle\build\webpack:\~\xhr2\lib\xhr2.js:469:1)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1129:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! authcoin@1.0.0 postinstall: `truffle install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the authcoin@1.0.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Home\AppData\Roaming\npm-cache\_logs\2020-02-24T19_10_25_922Z-debug.log

This is what I'm getting when running "truffle version"

Truffle v5.1.14 (core: 5.1.14)
Solidity v0.5.16 (solc-js)
Node v10.16.0
Web3.js v1.2.1

I found similar error in infura related questions but I'm not using infura at all.
So how can I get rid of this error?


texts:
I have been looking into sharding and I wanted to figure out how much extra fee or gas does a person needs to spend on a cross shard transaction compared to a transaction within a shard.

What could be the relationship between the two gas prices and how are they calculated?


texts: What are the self destructs in this transaction for?

texts: I have been using websites like Etherscan and Bscscan for almost 2 months and recently I have found this random transaction and realised that I have no idea what is going on with this self destructs... I mean I know that it is used for removing a contract from the blockchain and its also useful for saving some transactions fees but after calling self destruct the contract is gone from the blockchain and cannot be used afterwards am I right? Also why is this guy calling it that often?


texts: Truffle Develop Could not find suitable configuration file

texts:
Basically, after I installed the truffle the command: nom truffle -g . Then I went to set up the metamask on the google chrome. Once the metamask is set up then I try the command: truffle develop and I get this:  Could not find suitable configuration file.
Any suggestions ? Please Thank you.


texts: Contract constructor parameter which is also a contract

texts:
I have contract in solidity MasterChef.sol which can be seen at the link below https://github.com/pancakeswap/pancake-farm/tree/master/contracts
I want to deploy it using truffle on the Binance smart chain and the question is that the constructor of the MasterChef.sol takes in 5 args and two of them are contracts I want to know that how to pass the other two contracts i.e CakeToken.sol and SyrupBar.sol as the first two args in the deploy_contracts.js file.


texts: how to see all old commited transactions of a node in geth

texts:
I created a ethereum node using geth and I made certain number of transactions. All the transactions are mined and showing the correct balance.

How can I see all my old transactions?

Also I did transaction by sending the data. It is no where visible to the receiver.

How to see the data sent along with transactions?


texts: Signing transactions with Ledger Nano S on Ganache with Metamask

texts:
I am trying to sign transactions and move funds on a private Ethereum Blockchain with my Ledger Nano S on MetaMask. So far I have tried to do so in Ganache and via blockchain setup via custom RPC.

And I have failed.

These are my screen caps:

And this is the segment of my metamask log

[
        {
          "note": "transactions:tx-state-manager#fail - add error",
          "op": "add",
          "path": "/err",
          "timestamp": 1582819262703,
          "value": {
            "message": "Error: Ledger: The transaction signature is not valid",
            "stack": "Error: Ledger: The transaction signature is not valid\n    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:1227764\n    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:1229279\n    at n (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:1:205090)"
          }
        }
      ],
      [
        {
          "note": "txStateManager: setting status to failed",
          "op": "replace",
          "path": "/status",
          "timestamp": 1582819262706,
          "value": "failed"
        }
      ]
    ],


texts: cross-chain atomic swaps for integration between enterprise blockchain solutions (quorum, hyperledger, R3 corda)

texts:
Understand that cross-chain atomic swaps is for asset transfer between different cryptos.

In a world where there are different enterprise blockchains, cross-chain atomic swaps as a concept/foundation for integration between enterprise blockchain solutions (quorum, hyperledger, R3 corda) is the way forward.

Has anyone integrated enterprise ethereum (quorum) with hyperledger and/or R3 corda via cross-chain atomic swaps?


texts:
The error I get when trying to make ethertoDai() run is:

{ "message": "VM Exception while processing transaction: revert",
"code": -32000, "data": { "stack": "o: VM Exception while processing
transaction: revert\n at Function.o.fromResults
(/app/ganache-core.docker.cli.js:6:120966)\n at e.exports
(/app/ganache-core.docker.cli.js:41:2269990)", "name": "o" } }

/// @title Kyber Network interface
interface KyberNetworkProxyInterface {
    function maxGasPrice() public view returns(uint);
    function getUserCapInWei(address user) public view returns(uint);
    function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
    function enabled() public view returns(bool);
    function info(bytes32 id) public view returns(uint);

    function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
        returns (uint expectedRate, uint slippageRate);

    function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount,
        uint minConversionRate, address walletId, bytes memory hint) public payable returns(uint);

    function swapEtherToToken(ERC20 token, uint minRate) public payable returns (uint);

    function swapTokenToEther(ERC20 token, uint tokenQty, uint minRate) public returns (uint);

}
contract Playground {

    address public daiAddress = 0x6b175474e89094c44da98b954eedeac495271d0f;
    address public kyberAddress = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
    address private ETH_ADDRESS = 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
    address public UniDaiAddress = 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667;

    constructor(){

    }

    function etherToDai(uint256 quantity) payable returns (uint256) { // Buy DAI on the KyberNet
        KyberNetworkProxyInterface KNPI = KyberNetworkProxyInterface(daiAddress);
        uint256 expectedRate;
        uint256 slippageRate;
        ERC20 daiToken = ERC20(daiAddress);
        (expectedRate, slippageRate) = KNPI.getExpectedRate(ERC20(ETH_ADDRESS), daiToken, quantity);
        uint256 received = KNPI.swapEtherToToken.value(quantity)(ERC20(daiAddress), slippageRate);
        require(daiToken.transfer(msg.sender, received));
        return received;
    }

    function () external payable  {

    }
}

What is the problem, and how am I supposed to debug an error like this?


texts: Truffle testing a contract against an already-deployed external contract

texts:
Let's say I'm writing an escrow contract. The conditions of this escrow are based on the properties of a second already-deployed contract on Kovan and mainnet. Should I skip testing my escrow contract on Ganache and deploy to Kovan every time I need to test to access the other contract? Or should I somehow find a way to replicate the conditional logic into a contract that I can deploy to Ganache and test against that?

It would be great if I could clone a deployed contract with its current state to my Ganache chain. Is there anything like this?


texts: is contract.allEvents scalable for a metamask dapp?

texts:
In my dapp, I am calling contract.allEvents({from: 0, to: 'latest'}.

I am doing this for every user and every time they first enter the site.

Is this scalable? What if my contract gets to 1 million events? How long will take take to load? Are those 1 million individual requests?

Should I use web3.eth.filter instead?

I like the simplicity of allEvents over the "topics" method of filter but if it doesn't scale I guess I would have to change.


texts: Calculate approximative block height at a certain time?

texts:
What would be a formula for calculating the block height at a certain point in time, approximative
How would I calculate the block height for a date like next Christmas 0h midnight?