texts: Modifier to only allow access via staticcall

texts:
I'm trying to create a modifier that only allows a function to be called using staticcall. Using the view declaration in Solidity 0.5.0 guarantees that a function won't change state, but it still allows the function to be invoked with call from external sources. It would be interesting to be able to block all potentially-insecure calling methods directly.
My current solution tests for a staticcall by using a standard call into a function that will emit an event, and only allowing the transaction to proceed if that call fails. It exposes this feature via an onlyStaticCall modifier. There are a few issues with this approach:

Since the check uses a call, it will not allow for the modified function to also be declared as a view function. It would obviously be preferable for the two modifiers to coexist, although the onlyStaticCall modifier might make view redundant.
While the modifier seems to work, it makes a potentially superfluous external call to itself. A more efficient and elegant solution would be able to "try" to emit a log without needing to invoke call, or even introspect the calling method directly.
I'm not sure whether or not a delegatecall could circumvent this restriction.
Would there also be a way to enable web3 message "call" transactions (vs. regular "send" transactions) to succeed on the modified function? (The terminology here is a bit confusing, as the call opcode is for state-changing calls but web3 "call" is for read-only contract access.)

Any ideas on how to address these issues?
Existing Code:
pragma solidity ^0.5.0;

contract StaticCallChecker {
  // an event that signifies that the state is no longer unchanged
  event StateUnchanged(bool);

  // a function that changes state by emitting an (empty) event
  function changeState() public {
    emit StateUnchanged(false);
  }

  // example function that can only be called using staticcall
  // NOTE: making a "call" from web3 (vs. a "send") doesn't use a staticcall!
  function test() public onlyStaticCall returns (bool) {
    return true;
  }

  // make a staticcall to `test()` internally, should always return true
  function testStaticCall() external view returns (bool result) {
    // perform the staticcall and get success status and returned data
    (bool success, bytes memory data) = address(this).staticcall(
      abi.encodePacked(
        this.test.selector
      )
    );

    // if the staticcall was successful, load return bytes as a boolean
    if (success) {
      assembly {
        result := mload(add(data, 0x20))
      }
    }
  }

  // modifier that will only allow the caller to use staticcall
  modifier onlyStaticCall() {
    require(_isStaticCall());
    _;
  }

  // an internal function for checking if a caller is using staticcall
  function _isStaticCall() internal returns (bool) {
    // perform a call and get success status (ignore return data)
    (bool success, ) = address(this).call(
      abi.encodePacked(
        this.changeState.selector
      )
    );

    // the call should fail in order for the original call to be a staticcall
    return !success;
  }
}

Test output:
running tests...
 ✓ contract deploys successfully
 ✓ contract cannot change state via web3 "call"
 ✓ contract can change state via web3 "send"
 ✓ test reverts via web3 "call"
 ✓ test reverts via web3 "send"
 ✓ testStaticCall returns true via web3 "call"
 ✓ testStaticCall does not revert and does not log an event via web3 "send"
completed 7 tests with 0 failures.


texts:
This question is related to this one. I have a structure

struct File {
        uint256 fileId;
        uint256 filePrice;
    }

File[] files;

and try to initialize it as:

File newFile = File(0, 0);
files.push(newFile);

but get:

Error: Type struct File memory is not implicitly convertible to expected type struct File storage pointer.

I don't get which one is the storage and which one is the memory pointer? Is the struct File array stored in memory or as persistent storage?

Edit:

I have found the answer/reason here.


texts: Authentication of Ethereum Node on a private block chain

texts:
Problem: In a private block chain network, how does setting up a new node authenticate itself into the network. Is there anything which prevents one node from getting to the network and download data from other nodes.

I have seen the json file which contains a private and public key which is a config file for the node. I believe this is used for securing the data transmission between the nodes. however, this does not possible seems to have any correlation to authenticate of the node to the network.

i am a newbie to block chain so any help would be greatly appreciated. I am working on developing a startup around block chain


texts: Updating values in dynamic array - Solidity

texts:
I need to add a number to existing value in array under index 'id'. I have the following code:

 contract Store {

  uint256[] public totalamt;

  function append(uint256 id,uint price) payable{

    totalamt[id] = totalamt[id] + price;

}

   }

Array is not initialized.Each time I need to update the array.Help will be appreciated :)


texts: Truffle does not inject web3 into the test.js files

texts:
I get the following error while executing my truffle js files.
despite trying to use
web3 = new Web3();

or
web3Provider = new web3.providers.HttpProvider('http://127.0.0.1:7545');
web3 = new Web3(web3Provider);

I still get the following error
ReferenceError: Web3 is not defined
    at Object.<anonymous> (/Users/clydearnold/ethereum/multinumbet/test/multinumbetv5.js:5:1)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:390:36
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:387:14)
    at Mocha.run (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:961:10)
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/testing/Test.js:149:1
    at new Promise (<anonymous>)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/testing/Test.js:148:1)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
Truffle v5.1.49 (core: 5.1.49)
Node v12.18.3


texts: Truffle migrate: Could Not Find .sol file from any sources

texts:
I just started onto the blockchain journey a couple of hours back trying to create an elections program on the Ethereum blockchain. While trying to migrate the smart contracts using truffle migrate, I encountered a roadblock which says the following:

I'm stuck and need some help.
I have been following this tutorial: https://www.youtube.com/watch?v=3681ZYbDSSk

Thanks!


texts: What is the difference between local and remote transaction?

texts:
In latest go-ethereum, miners firstly try to mine local txs and
then try to mine remote txs.

what are the exact differences between them?


texts: How are the stored transactions receipts referred from the block?

texts:
Based on the data structure of Ethereum blocks and transactions which is also represented here, we know the following sentences about the transactions receipts:

1- The transactions receipts are stored in the LevelDB.
2- The transactions receipts tire is created in RAM when there is a need for it.
3- The root hash of the trie is stored in the block header.

But if the receipts are neither stored inside the block body nor in the transactions data structure, then what is the link inside the block to the receipts in the LevelDB? And how do we know which receipt is related to which transaction?


texts: Check if item exits in Solidity Mapping structure

texts:
How i can check if particular item exists in the Mapping list?

struct user {
    address userAddress;
    uint[] entries;
}

mapping (address => user) public userInfo;

I found such solution here but this solution is not working:

require(userInfo[msg.sender].length == 0);


texts: What does `JUMP [out]` stand for in Remix IDE?

texts:
After compiling this contract:

pragma solidity ^0.4.25;

contract Simplest {
    constructor() public {
    }

    function two_paths(bool _a) public pure returns (uint) {
        if (_a == true) {
            return 1;
        } else {
            return 0;
        }
    }
}

The following opcode output is observed in Remix:

...
tag 6           function two_paths(bool _a) pu...
      JUMPDEST          function two_paths(bool _a) pu...
      SWAP2             function two_paths(bool _a) pu...
      SWAP1             function two_paths(bool _a) pu...
      POP           function two_paths(bool _a) pu...
      JUMP [out]            function two_paths(bool _a) pu...
    .data

In particular, notice the JUMP operation with [OUT] attached to it. Normally Remix JUMP operations don't have attached data to them.

Can you help understand what that JUMP instruction stands for and perhaps is it a dynamic jump (as I don't see a PUSH statement ahead of it).


texts: go lang installation error - raspberrypi

texts:
I needed to create privatenet in raspberrypi and installed go1.9. Cloned geth, extracted it. When 'make geth' command is passed I get following error. Please help me out

github.com/ethereum/go-ethereum/vendor/gopkg.in/olebedev/go-duktape.v3
# github.com/ethereum/go-ethereum/dashboard
fatal error: runtime: out of memory

runtime stack:
# github.com/ethereum/go-ethereum/vendor/gopkg.in/olebedev/go-
duktape.v3
In file included from vendor/gopkg.in/olebedev/go-
duktape.v3/api.go:7:0:
vendor/gopkg.in/olebedev/go-duktape.v3/api.go: In function
‘_duk_error’:
vendor/gopkg.in/olebedev/go-duktape.v3/duktape.h:510:127: warning:
right-hand operand of comma expression has no effect [-Wunused-value]
(duk_error_raw((ctx), (duk_errcode_t) (err_code), (const char *)
(DUK_FILE_MACRO), (duk_int_t) (DUK_LINE_MACRO), __VA_ARGS__),
(duk_ret_t) 0)

vendor/gopkg.in/olebedev/go-duktape.v3/api.go:153:2: note: in
expansion of macro ‘duk_error’
duk_error(ctx, err_code, "%s", str);

# github.com/ethereum/go-ethereum/vendor/gopkg.in/olebedev/go-
duktape.v3
vendor/gopkg.in/olebedev/go-duktape.v3/duktape.go:119: cannot use fn
(type func(*Context) int) as type func(*Context) uint in argument to
d.PushGoFunction
vendor/gopkg.in/olebedev/go-duktape.v3/duktape.go:129: cannot use fn
(type func(*Context) uint) as type func(*Context) int in argument to
d.context.fnIndex.add
vendor/gopkg.in/olebedev/go-duktape.v3/duktape.go:132: constant
18446744073709551615 overflows int64
util.go:45: exit status 2
exit status 1
Makefile:15: recipe for target 'geth' failed
make: *** [geth] Error 1


texts: Is the interaction with the smart contract safe?

texts: I am working with ethereum and I have a doubt. In a real case, can a user interact directly with a smart contract? Are there no dangers? For example: a user wants to book a trip. What happens in these cases? Does the transaction start from the user or is there an intermediate component that collects the data and transmits it (via transactions) to the smart contract?


texts: A simple require makes the contract to fail

texts:
I have the following contract (truffle + zeppelin):

contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale {

    uint256 public cirCap;

    function SampleCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, address _wallet) public
    CappedCrowdsale(_cap)
    FinalizableCrowdsale()
    RefundableCrowdsale(_goal)
    Crowdsale(_startTime, _endTime, _rate, _wallet)
    {
        //As goal needs to be met for a successful crowdsale
        //the value needs to less or equal than a cap which is limit for accepted funds
        require(_goal <= _cap);
        cirCap = getTokenAmount(_cap);
    }

    function createTokenContract() internal returns (MintableToken) {
        return new SampleCrowdsaleToken();
    }

    function airdropCoins(address beneficiary, uint256 cirAmount) onlyOwner public {
        uint256 authorizedCoinsRemaining = cirCap - token.totalSupply();
        require(cirAmount > 0);
        require(cirAmount <= authorizedCoinsRemaining); // <== This fails to deploy !!!
        token.mint(beneficiary, cirAmount);
    }

}

Any ideas why the "require(cirAmount <= authorizedCoinsRemaining);" makes the contract to fail with the very cryptic message:

Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: The contract code couldn't be stored, please check your gas amount


texts: Ethereum Wallet suddenly cant find peers anymore

texts:
I have a problem with my Ethereum Wallet. It was fully synchronized previously and constantly resynched while it was open and also after several shutdowns of the machine. Now, it suddenly stopped working and cant seem to find any peers.
The strange thing is, it says its connecting to X peers everytime (in the little blue start screen) but then just cant download anything. When I open the application it says peers(no number)|880 blocks left|0%. That never changes. Only when I close and restart the application the number of blocks left jumps up. The application is responsive and all data (account, contracts) are still there.
This started while I was actually using it. I had just created a contract on the main network and send a transaction to it. Both those transactions went through normally. Right after I send another transaction to this contract and right then it stopped synchronizing.

Its running on Linux Peppermint in a VM hosted with Virtualbox. I have restarted both the linux vm and the windows host. The Linux has internet, I am using a browser on it to post this question. The problem has persisted over several hours now.
I have read somewhere that system time is an issue. I am new to Linux but I am fairly sure that the system time is synchronized. To check I have set the system time to "manual" and entered a random time. Saved, closed, and reopened, set it to automatic again and it automatically set the correct time. I am assuming this time must have come from some time server.
Geth is not running in another instance. I have checked with both ps and killall.
I have tried starting geth through the terminal. It says two different things:

  Peer de471bccee3d0422 [eth/63]: timed out DAO fork-check, dropping

which I googled and found to be just a peer using incompatible software, and:

  converting 1600000 canonical numbers...

Increasing the number in steps of 100000. There were a few of both these messages but nothing else after like half an hour.

At this point, I have no clue what the problem is or what else I could do to figure it out. What can I do to get it working again?


texts: How can I make an account in Ruby without using JSON-RPC?

texts: I'd like to build an application with rails. I want to make an account through Ruby. I got the advice that, in order to make an account, I should not use JSON-RPC for security. Instead I should use IPC and the javascript API, but I don't want to use javascript. I want to write with Ruby only. Could you tell me if there's a way to do that?


texts: Hello world not working. Function not found

texts:
I have a simple test contract that I've deployed using truffle:

pragma solidity ^0.4.4;

contract TestObject {

  uint public myValue;

    function TextObject() {
        myValue = 1000;
    }

  function deposit(uint value) returns(uint) {
        myValue += value;
        return myValue;
    }
}

If I do

var ob = TestObject.deployed();

ob

I can see that my object has been deployed:

.
.
.
 myValue:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  TextObject:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  deposit:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  sendTransaction: [Function],
  send: [Function],
  allEvents: [Function: bound ],
  address: '0xe43d2d9d7d0cb6d13100ded5548a78139d479047',
  transactionHash: null }

Also myValue seems to be present.

When I call ob.myValue I get undefined

If I try to set the value:

ob.deposit(23);

I get:

TypeError: ob.deposit is not a function
    at evalmachine.<anonymous>:1:4
    at ContextifyScript.Script.runInContext (vm.js:35:29)
    at Object.runInContext (vm.js:89:6)
    at TruffleInterpreter.interpret (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:209587:17)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:233:10)

Anyone know whats going on here?

Any help would be much appreciated. Thanks!

EDIT
Here's my deployment code in migrations/2_deploy_contracts.js:

var Adoption = artifacts.require("./Adoption.sol");
var TestObject = artifacts.require("./TestObject.sol");
const Storage = artifacts.require("./Storage.sol");

module.exports = function(deployer) {
  deployer.deploy(Adoption);
  deployer.deploy(TestObject);
  deployer.deploy(Storage);

};


texts: Having problem in getting array value in Solidity

texts:
Hi I am New to Solidity!. I have a simple array which adds some numbers in an array

pragma solidity ^0.4.11;
Contract TestArray{
    uint[] public numbers;
    function addNumber(uint number){
        numbers.push(number);
    }

This getNumbers() function is returning all the values

  function getNumbers() constant returns(uint[]){
        return numbers;
    }

But when I am trying to check if the no exists its returning true for only the first value. For the rest of the value it's returning false

function checkNoExists (uint no) constant returns(bool){
        for(uint i=0; i<numbers.length; i++){
            if(numbers[i]==no){
                return true;
            } else{
                return false;
            }
        }
    }

Please Help!


texts: Will code utilising web3.js be compatible with Ethereum 2.0?

texts: I'd like to start developing a solution targeting the Ethereum blockchain but I want to target the Ethereum 2.0 blockchain and I'm not so interested in 1.0 anymore. Can I already do the development using the current web3.js library? Is there an ETH2.0 version? Or perhaps a more low-level solution I can already use for ETH2.0? (JSON RPC API)


texts: estimateGas - how does it work when there's an internal call?

texts:
I've read the following:

The catch about gas estimation is that the node will try out your tx
with different gas values, and return the lowest one for which your tx
doesn't fail. But it only looks at your tx, not at any of the internal
call it makes. This means that if the contract code you're calling has
a try/catch that causes it not to revert if an internal call does, you
can get a gas estimation that would be enough for the caller contract,
but not for the callee.

Question 1) so, If I have contractA and contractB, does this mean that even If I don't have try/catch block at all in contractA  and the contratA calls contractB, estimateGas will still return the gas estimation for only contractA and won't include the gas estimation for contractB's function ?
Question 2)  Could you better explain if possible the snippet I copied  above ?


texts: Ethereum hangs after 3 days uploading the blockchain, do I even need the blockchain to have a wallet?

texts:
I have downloaded and run Ethereum Wallet 0.9.0 Mist. It started updating about 3 days ago. It runs, but then when it is very near the end, e.g. 300-ish blocks to go, it seems to slow down and stop. I tried rebooting my computer and it did the same thing: download a lot of blocks but get stuck at the end. I was about 95% complete. Then today, I rebooted again and started up the Ethereum Wallet again. Now it says I am 80% complete.
Is there a problem with the software?

All I want to do is move my Ethereum off my Jaxx wallet to the official wallet. With Jaxx apparently I can't import a paper Ether wallet. Am I even using the right software? I really don't care about the entire blockchain and actually would prefer not to have it take up all that room on my HD.

Also, in the Ethereum Wallet, I can't for the life of me find the private key. Where is it?

Sorry for these newbie questions, but any help would be appreciated.


texts: Getting ABI from contract source file offline

texts: Is there any way other than online solidity browser to get the ABI and bytecode of a contract?


texts:
I don't how initalize a variable with empty array ?

I have two structures :

    struct Concour {
    string theme;
    address admin;
    uint dateEndInscription;
    uint dateEndBet;
    uint dateResults;
    uint phase;
    Vin[] validatedVins;
    Vin[] proposedVins;
}

struct Vin {
    string url;
    uint nb_view_begin;
    uint nb_view_end;
}

And my function

function createConcour(string _theme, uint _dateEndInscription, uint _dateEndBet, uint _dateResults) {
        concours.push(Concour({
            theme: _theme,
            admin: msg.sender,
            dateEndInscription: _dateEndInscription,
            dateEndBet: _dateEndBet,
            dateResults: _dateResults,
            phase: 1,
            validatedVins: //empty list of vins hir,
            proposedVins: //maybe like this ? new Vin[](0)
        }));
    }


texts:
Simple question:
It seems like ethplorer doesn't expose the ETH price via their public api:

https://github.com/EverexIO/Ethplorer/wiki/Ethplorer-API

Am I missing anything, or do I have to rely on another API for this information?


texts: next step after blockchain synchronization

texts:
I am syncing using geth.
do I need to 'save' or secure the blockchain in some way after sync finishes? If i need to pause for some time (kill geth, restart machine) next time i run geth it will automatically pick up from the latest block? Or do I need to tell it from which block to continue?
thnx


texts: Importing private key: Why is it so fast?

texts:
I've just imported two private keys with both, geth and the zcash-cli. While the zcash-cli (a public t.* address) took more than 15 minutes* (I guess it scanned the whole blockchain), geth was finished importing almost instantly.

My question is: What goes on under the hood? Why is geth so much faster?

This answer suggests that other nodes in the network are queried for the balance?

Thanks!

*I left the computer to be honest, so this is only a rough estimate.


texts:
I've been reading a bit about Casper lately and I've seen that a lot of the miners are upset because they think their GPUs will become useless but there are tons of uses for GPUs besides cryptocurrency mining.

Has anyone thought about setting up smart contracts where people could contribute GPU power to pools that researchers could buy from, then the 'miners' could be rewarded with ETH?  That would help miners accept Casper more easily, helping to prevent another ETC/ETH type split and the GPU power would go to seriously useful things like machine learning, analyzing medical imagery, computational fluid dynamics, weather forecasting, etc.


texts:
I am getting an error when I run :

truffle migrate --network production

Error

Running migration: 1_initial_migration.js
Deploying Migrations...
... 0xc10be773bf8c2cbb38c789765bf063413d1de8285cab63b078f3ec48263f3579
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: Contract transaction couldn't be found after 50 blocks

I adjusted the gas value and checked whether syncing is running but eth.syncing returns false. It means its not syncing related issue.

truffle.js:

module.exports = {
  networks: {
    development: {
      host: '127.0.0.1',
      port: 7545,
      network_id: '*' // Match any network id
    },
    production:{
      host: '.....cloudapp.azure.com',
      port: 8545,
      network_id: '*', // Match any network id
      gas: 5000000,

    }
  },

}


texts: Can I watch an ENS name like I can watch a token?

texts:
When I buy an ERC20 token, I can 'watch' it with my Mist or Parity wallet. And, I don't have to go to any websites.

Is there a similar thing to do with an ENS name? I won four auctions a couple of months ago, but I can't figure out how to 'watch' them without going to a website.

When I go to the website (https://registrar.ens.domains/) with a parity-enabled browser, I do see my names, but I'm trying to live a fully decentralized life, which to me means no browsers and no https://. Does that even make sense?


texts: Why write uint256 instead of uint if they're the same thing?

texts:
Is uint the same as uint256 in Solidity?

If this is the case, then why do a lot smart contracts make extensive use of uint256 and not just write uint instead? Is this merely to be explicit?


texts:
When one deploys a smart contract onto the Ethereum blockchain, is the smart contract deployed on all nodes or just a few nodes? In short. where is the specified location that the smart contract is deployed?

The context of this question is to understand the resiliency of a smart contract in the event the node that contains the smart contract fails.


texts: Is there any websocket ethereum provider? Except etherscan one. Maybe there are paid wss subscriptions?


texts: creation of Simple errored: The transaction has been reverted to the initial state

texts:
contract Simple is Ownable {

    using SafeMath for uint;

    address                      public  fuel;
    uint                         public  initTime;

    constructor( address _fuel, uint timer) public {
        // factory = IJustSwapFactory(msg.sender);
        fuel = _fuel;
        initTime = now.add(timer) ;
    }
}

I am receiving this error when working my code:

creation of Trading errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance.

Why does the constructor need to be payable?


texts: how to verify a bitcoin or etherem address?

texts: My project allows a user to add their existing bitcoin/ethereum wallet address. Is there a way to call an API to verify these addresses?


texts: Sending ETH rather than ERC20 token Web3

texts:
I'm currently writing a function using Web3 to send our tokens, it's currently sending ETH instead. Since we're doing this straight on the main network (We like taking risks), the transaction fees are adding up.

If anyone can help us see how to send our token rather than ETH it would be really appreciated.

    const web3 = new Web3();
web3.setProvider(new
web3.providers.HttpProvider("https://mainnet.infura.io/XXXXXX"));
var count = web3.eth.getTransactionCount(from_addr);
var contract =  web3.eth.contract(abi).at(contract_addr);

var data = contract.transfer.getData(to_addr, 10, {from: from_addr});
var gasPrice = web3.eth.gasPrice;
var gasLimit = 90000;

var rawTransaction = {
  "from": from_addr,
  "nonce": web3.toHex(count),
  "gasPrice": web3.toHex(gasPrice),
  "gasLimit": web3.toHex(gasLimit),
  "to": to_addr,
  "value": 0,
  "data": data,
  "chainId": 0x01
};

var privKey = new Buffer(priv_key, 'hex');
var tx = new Tx(rawTransaction);

tx.sign(privKey);
var serializedTx = tx.serialize();

web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
  if (!err)
      console.log(hash);
  else
      console.log(err);
});

I've pretty much copied and pasted this question: How to send ERC20 token using Web3 API?. They seemed to have found the way to send tokens whereas I'm still sending ETH.

Any advice would be much appreciated.

Thanks


texts:
I was trying the code in https://gist.github.com/sogoiii/f0ced0a4e569b5f38d302e7072d78b43 to observe the difference between call and delegatecall.

pragma solidity ^0.4.18;
contract D {
  uint public n;
  address public sender;

  function callSetN(address _e, uint _n) public {
    _e.call(bytes4(keccak256("setN(uint256)")), _n); // E's storage is set, D is not modified
  }

  function callcodeSetN(address _e, uint _n) public {
    _e.callcode(bytes4(keccak256("setN(uint256)")), _n); // D's storage is set, E is not modified
  }

  function delegatecallSetN(address _e, uint _n) public {
    _e.delegatecall(bytes4(keccak256("setN(uint256)")), _n); // D's storage is set, E is not modified
  }
}

contract E {
  uint public n;
  address public sender;

  function setN(uint _n) public {
    n = _n;
    sender = msg.sender;
    // msg.sender is D if invoked by D's callcodeSetN. None of E's storage is updated
    // msg.sender is C if invoked by C.foo(). None of E's storage is updated

    // the value of "this" is D, when invoked by either D's callcodeSetN or C.foo()
  }
}

I deployed both contracts on Remix and called D.delegatecallSetN with the address of the E and an arbitrary value. Based on the comments, D.n should be modified. However, that was not the case.

Am I understanding something wrongly here?


texts: Hoe to get the gas used by each transaction in a block in a single API call?

texts:
I am working on service which monitors Ethereum based blockchains using web3 API calls. For each new mined block, it has to parse each of the transactions in the block. In addition, it needs to parse the amount of gas used by each transaction. The method I found of doing it is by calling eth_getTransactionReceipt.
I am facing a performance issue, since this API needs to be called per transaction. As a first improvement, I perform a batch of many eth_getTransactionReceipt calls in a single JSON RPC batch request.
I am looking for a way to further improve the performance by doing this with a single call per block, in a similar manner to trace_block.


texts: Generating an Ethereum wallet with an existing private key

texts:
I want to understand how Ethereum works and i want to calculate the public key and wallet address from private key.
I have read this tutorial: https://piyopiyo.medium.com/generating-an-ethereum-wallet-with-an-existing-private-key-5cda690a8eb8
Here is the code:
var Wallet = require('ethereumjs-wallet');
var EthUtil = require('ethereumjs-util');
const privateKeyString = '0x...MyPrivateKey...';
const privateKeyBuffer = EthUtil.toBuffer(privateKeyString);
const wallet = Wallet.fromPrivateKey(privateKeyBuffer);
const publicKey = wallet.getPublicKeyString();
console.log(publicKey);
const address = wallet.getAddressString();
console.log(address);

It sounds great but i have this runtime error:

TypeError: Wallet.fromPrivateKey is not a function

I think this is because ethereumjs-wallet has changed in the latest versions.
But how can i load a private key with latest version ?
Thanks


texts: Parity in --geth mode brings "unknown api" error

texts:
I'm trying to migrate wallets from Mist to Parity. Parity is already fully synced and after using --import-keys I was able to import old Mist accounts into Parity. But the wallet contracts are missing so I need to run parity.exe with --geth.

Problem is, I get this error while launching parity:

Unknown api: rpcpersonal


texts:
I have a lot of experience in programming but I'm a noob when it comes to ethereum programming. When I try to compile the code with truffle I have this error: ParserError: Expected event name or path on lines where I use events EthTransfered and EthRefunded.

My source code: https://github.com/amiramieng/simplebyte-contract/blob/master/contracts/SimpleByteTokenCrowdsale.sol


texts: How are new users authenticated into Quorum network

texts: I could find from online readings that Quorum has a Network Manager component that controls nodes access to network to created permissioned network of nodes. But, I couldn't see explanation on how Network Manager decides which nodes are trustworthy. For example, in the case of Corda network, a certificate is issued to nodes after validation process and it is used for identification nodes during transaction process. Does anyone know how new users are validated and allowed access to network?


texts:
While mining after a while i got this error message

"Error CUDA mining: an illegal memory access was encountered" or
"Runtime error - ethash_cuda_miner::search, line 365"

the miner works for some time then the error comes back.


texts:
In the following article (LINK) we read:

  "despite the fact that at the time of this writing a new block is
  produced approximately every 10–20 seconds the average time it
  actually takes for a transaction to be added to the blockchain is 1.2
  minutes, according to ETH Gas Station."

I checked ETH Gas Station ; however, I could not find out how the value 1.2 minutes has been calculated.

How to calculate average time it takes for a transaction to be added to Ethereum blockchain?

P.S. This time is different with the average time it takes for a new block to be produced.


texts: How to detect from web3 if method exists on a deployed contract?

texts:
Suppose a contract has been deployed and I don't have its source code or ABI. From web3, I would like to know if the contract has a method with a given signature. (An example application would be a blockchain service that responds to requests by invoking a specific callback method on the calling contract, like Oraclize.)

I can get close with the following:

methodSignature = web3.sha3('methodName(bytes32,bytes)');
calltx = {
  to: TARGET_ADDR,
  data: methodSignature.substring(0,10)
};
let result = web3.eth.call(calltx)

and then if result is not '0x' then the method exists because it returned some value. But '0x' doesn't mean the method doesn't exist, depending on the method itself. How do I tell the difference?

Related: What happens if you call a non-existent function of another contract that has no fallback function in Solidity?


texts: Test valid contract that is retrieved by an address

texts:
In the below code, I re-create a handle on a contract by 'instantiating' it using its address. This works if I pass in a legit address (that really is the concerned contract type). How can I test if someone passes a contract address that is not the right contract type?

function changeOwnership(address aContract, address bAccount) returns (bytes32){
    MyContractType work = MyContractType(aContract);
    /* How would I do this?
     if (work is definitely a MyContractType contract){
           work.hasNewOwner(bAccount);
     }
     */
    return work.getWorkName();
}


texts: Tron smart contract TransferOwnership function error

texts:
I want to implement TransferOwnership function in already made tron smart contract but it keep throwing error whenever I want to compile the code. I guess 1 thing maybe I'm using an Owner modifier and did not define an owner anywhere in the contract.
Please can anyone show me how to define Owner. Thanks for helping me out.
function changeOwner(address payable _newOwner) public ownerOnly{
       owner = _newOwner;
    }

And this is the error message whenever I compiled it
Compiled error: [{"component":"general","formattedMessage":"contract.sol:378:5: ParserError: Expected pragma, import directive or contract/interface/library definition.\n function changeOwner(address payable _newOwner) public ownerOnly{\r\n ^------^\n","message":"Expected pragma, import directive or contract/interface/library definition.","severity":"error","sourceLocation":{"end":12928,"file":"contract.sol","start":12920},"type":"ParserError"}]


texts: What are the benefits of deleting storage array elements?

texts:
I have been wondering as to what benefits we get from deleting elements from a storage array in ethereum contracts ?

That particular state is already in a block isn't it ?

Could someone please explain if it's a good practice to delete elements from storage arrays and if not why ?


texts: How to add two integer values using addition function in solidity using smart contracts?

texts:
pragma solidity ^0.4.18;
contract addition {

    address creator;
    uint a;
    uint b;
    uint c;

    function addition() public
    {
        creator = msg.sender;                                // msg is a global variable
        uint c = uint a + uint b; //here i am getting an error that expected token semicolon got identifier
    }

    function addition() constant returns (uint)
    {
        return uint c;
    }

    /**********
     Standard kill() function to recover funds
     **********/

    function kill()
    {
        if (msg.sender == creator)
            suicide(creator);  // kills this contract and sends remaining funds back to creator
    }

}


texts: How to encrypt a message with the public-key of an Ethereum address

texts:
I am writing some code in nodejs/browser.
I have successfully created ethereum-addresses with the secp256k1-library.
I was also able to sign and verify messages.
Now I want to encrypt/decrypt a message with the public and private-key of the generated addresses.
Has anyone done this before? Can I use CryptoJS to accomplish my goal?


texts: Etherscan showing item pending after 12 hours

texts:
I have a item pending on etherscan. I tried to sell some PIKA (V1) for ETH on uniswap- the reason being is that PIKA is going to version 2 and I wish to get rid of before the swap happens otherwise the coins are rendered useless. I have Paid the gas fees for the initial swap and the transaction is still pending 12 hours later. I’ve read up that I must throw ETH in metamask and send back 0ETH (to my Coinbase ETH wallet address) to fix this issue? Is this true & correct.
Do I need to have ETH in metamask from the same seed (as Coinbase- being transferred) or can I buy ETH in metamask and use that to spedfast the transaction.


texts: Cannot properly deploy smart contract with web3 1.2.4 provider in Geth 1.9.8

texts:
I have setup a private Ethereum node using the following configuration for the genesis block:

{
    "config": {
    "chainId": 143,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip155Block": 0,
    "eip158Block": 0
    },
    "alloc": {},
    "difficulty" : "0x40000",
    "gasLimit"   : "0x8880000"
}

I am running the geth client with the following commands cmd args:

geth --port 3000 --networkid 44444 --nodiscover --datadir=./blkchain --maxpeers=0  --rpc --rpcport 8543 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner" --allow-insecure-unlock

Once it is running I attach the geth JS client using: geth attach http://127.0.0.1:8543

I have created an account and have unlocked it as well.

I am trying to deploy a very simple smart contract:

pragma solidity >=0.4.0;

contract UnrealContract {
    function test() public pure returns (uint16) {
        return 15;
    }
}

I have tried both from Remix IDE and using the web3js library and although the deployment seems to work fine (I'm getting back a contract address) when I call the test() method I get a response of 0x0 in Remix while in my Javascript code I get an error:

  Returned error: gas required exceeds allowance (5000000) or always failing transaction

No matter the amount of gas and gasprice I set it always seems to return this error. Is this a problem with any of the versions of the software I'm using?


texts: Pending Transaction. How long may it take?

texts:
I have a question about this specific transaction: 0xd0dfbefc699ba79c2ddd86b0f7176e3e6491534db0a57597ec7aab9ce3e71726
the transaction is pending for some days now.
I offered 5 gwei as fee.
Max Amount of Gas 21.000
What will happen now? Will it be confirmed eventually?
How long may it take? Taking into account that the usual Gas prize is at the moment around 40 gwei or so.
I know that I could cancel or replace a transaction.
I do not mind waiting.
Maybe the gas price will drop if more people offer less ether/gwei?


texts: Why string variable must be memory from solidity v5.0?

texts:
May someone explain me why exactly string variable must be memory from solidity v5.0 and what does tha mean?

Thanks for your help.


texts:
I am sending some ethers and tokens to my smart contract. So how will the contract differentiate between ethers and tokens?
Code will be helpful


texts:
I am trying to understand the following function which appears in section 4.3.1 of the Ethereum Yellow Paper:

The function description state it "prepares" a transaction receipt, does it mean that the function does not actually perform the RLP encoding?. What is the purpose of this function?.
Any pointers would be great,thanks in advance.


texts:
I would be grateful if anyone can help me understand the storage of a smart contract. Before someone mention the question as duplicate i want to clarify that i had read the post here but i was confused. Moreover i read the solidity docs here that states:"Every account has a persistent key-value store mapping 256-bit words to 256-bit words called storage." So can i imagine the storage as an array with two columns and 256 rows, where each cell holds 256bits?

The reason i am asking is because i want to use the smart contract as a storage of hash values. So i want each time to store a new hash but i need to know how many 256hash values can be stored.


texts: Issues with Claymore cannot build OpenCL for GPU 0

texts:
Currently I am unable to start mining using Claymores software. I followed CryptoBadgers guide completely:

http://www.cryptobadger.com/2017/04/build-ethereum-mining-rig-linux/

I keep getting this error when I try to initiate my miner by typing this command

./miner.sh

ETH: 1 pool is specified
Main Ethereum pool is us1.ethermine.org:4444

Catalyst 15.12 is REQUIRED for best performance and compatibility
For Polaris cards, use latest drivers
At least 16 GB of Virtual Memory is required for multi-GPU systems
Make sure you defined GPU_MAX_ALLOC_PERCENT 100
Be careful with overclocking, use default clocks for first tests
Press "s" for current statistics, "0".."9" to turn on/off cards, "r" to reload pools, "e" or "d" to select current pool
OpenCL initializing...

AMD Cards available: 1
GPU #0: Pitcairn, 3072 MB available, 8 compute units
POOL/SOLO version
Cannot build OpenCL program for GPU 0
Segmentation fault (core dumped)

I am currently using a Radeon R9 370 for a GPU and I installed the following driver:

http://support.amd.com/en-us/kb-articles/Pages/AMDGPU-PRO-Driver-for-Linux-Release-Notes.aspx

This is also on Xubuntu 16.04.2.

Miner settings:

#!/bin/sh
export GPU_FORCE_64BIT_PTR=0
export GPU_MAX_HEAP_SIZE=100
export GPU_USE_SYNC_OBJECTS=1
export GPU_MAX_ALLOC_PERCENT=100
export GPU_SINGLE_ALLOC_PERCENT=100

./ethdcrminer64 -epool us1.ethermine.org:4444 -ewal 4d562bdab44696995251dd7bf743bbaf09b8b16e.Miner01 -epsw x -mode 1 -tt 68 -allpools 1

Can anyone explain what I have to do to fix the following error?

Cannot build OpenCL program for GPU 0
Segmentation fault (core dumped)


texts: The method eth_sendTransaction does not exist/is not available, when using Ropsten Network

texts:
My following code previously works perfectly at Ganache, but when i switched it to Ropsten Network, it give captioned error.
Here is Code:

async function finalSettersFunctions(){
  var myFunc;
  var  myContAddr ;
  for(i=0; i < contractAddressess.length; i++) {
      myContAddr = contractAddressess[i]
    for(j=1; j<finalSetters[i].length; j++) {
          myFunc = finalSetters[i][j];

            try {
              await web3.eth.sendTransaction(
                {from:account1,
                to:myContAddr,
                data: myFunc
                    }, function(err, receipt) {console.log("Normal Setters: ",receipt)});
            } catch (error) {
              console.log(" Normal Setters: ERROR !", error);
            }
    }
  }
}

It should be noted that all my setters function are in encoded form, means all their methodId and parameters are embedded i.e. myFunc= 0x34fcd000000000033400000000000678888800000000........

Here is detailed error:

The method eth_sendTransaction does not exist/is not available
    at Object.ErrorResponse (C:\Users\aa\node_modules\web3-core-helpers\src\errors.js:29:16)
    at C:\Users\aa\node_modules\web3-core-requestmanager\src\index.js:140:36
    at XMLHttpRequest.request.onreadystatechange (C:\Users\aa\node_modules\web3-providers-http\src\index.js:102:13)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (C:\Users\aa\node_modules\xhr2-cookies\dist\xml-http-request.js:289:61)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1143:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

Update: my provider is Web3.providers.HttpProvider("https://ropsten.infura.io/v3/

Update 2: i have changed my code as per comments (to sign my transaction and sendSignedTransaction) .... as is my new code

async function finalSettersFunctions(){
  var myFunc;
  var  myContAddr ;
  for(i=0; i < contractAddressess.length; i++) {
      myContAddr = contractAddressess[i]
    for(j=1; j<finalSetters[i].length; j++) {
          myFunc = finalSetters[i][j];
          /// here i have changed !
          rawTx = {
            nonce: await web3.eth.getTransactionCount(account1),
            gasPrice: '0x09184e72a000',
            gasLimit: '0x2710',
            to: myContAddr,
            data: myFunc
          }
          var tx = new Tx(rawTx);
          tx.sign(privateKey2);
          var serializedTx = tx.serialize();
          web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
          .on('receipt', console.log);
    }
  }
}

but it give this error Error: Returned error: invalid sender


texts: Typical architecture of a Dapp with a browser client

texts:
I am trying to understand the typical architecture of a Dapp with browser clients. Is the below understanding correct?

[Web Browser (end user)]  <==> [Server (web application/javascript <==> web3 <==> ethereum client like geth)] <==> [Ethereum Network (solidity code)]


texts: Can't see my NFT in Coinbase Wallet on Ropsten

texts:
I have created the following ERC721 contract:
pragma solidity ^0.6.0;

import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract MyNFT is ERC721PausableUpgradeable, OwnableUpgradeable {
  // keep the order of Status
  enum Status { Start, End}
  mapping (uint256 => Status) private status;
  string private constant MY_URI = "www.abc.com/metadata/start.json";

  function initialize() initializer public {
    __ERC721_init_unchained("MyNFT", "MNFT");
    __Ownable_init_unchained();
  }

  function mint(address to, uint256 tokenId) public onlyOwner {
    _mint(to, tokenId);
    status[tokenId] = Status.Start;
    _setTokenURI(tokenId, MY_URI);
  }
.
.
.

And I've tried the same with a plain-vanilla ERC721 as well:
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MyNFT is ERC721 {
    constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) public {
    }

    function mint(address holder, uint256 tokenId) public {
      _safeMint(holder, tokenId);
    }
}

Then on Ropsten I mint a token to my Coinbase Wallet address (Ropsten). However, I can't see my ERC721 under "Collectibles" in the Coinbase Wallet, although I can see in in the console. Does anyone have an advice how to make the ERC721 visible in Coinbase Wallet? ERC20 tokens I can see.
The same problems applies for both ERC721 contract version, for the upgradeable as well as for the plain-vanilla ERC721.
Is something special required for Coinbase wallets?


texts: Why does it typically make more sense to use a project's non WETH ERC20 token over a WETH token as a utility?

texts: I do not have any further details for this question.


texts:
I need to get the length of input which is an integer in bytes

function mine(string s , uint i ) public view returns () {
        return (length of i);
}


texts: Unable to locate transaction, unable to send any token

texts:
I have done atleast 5 transactions and all of them are just pending for over a day now. On metamask it says i should use more gwei but when i change it to even 30 gwei it still just is stuck forever.

Latest one is: https://etherscan.io/tx/0x950a62356c452cbaedff9ebf68306d0b1b8c20aabce96a345e85c2f46e0318ba

But the problem is, it's not even pending, you can't find it.

If i try to send a new transaction from this address its just going to get stuck with all the rest.

It's really a mess and all my tokens are just stuck, i can't even send them out somewhere else. They are basically rendered worthless unless i fix the problem somehow.


texts: As far as I understand Ethereum uses JSON-RPC to communicate between clients. What is the authentication mechanism? That is, how does the network know that the RPC request is coming from a legit client?


texts:
I have a mapping that maps addresses to uints:

mapping (address => uint256) mapAddress;

A function then assigns a counter to the address:

mapAddress[msg.sender] ++;

This gives me 1.

The problem is that I'm getting an error when trying to set the counter back to 0:

function resetCounter() public payable returns(bool) {
    if (mapAddress[msg.sender] > 0) {
        mapAddress[msg.sender] = 0;
        return true;
    } else {
        return false;
    }
}

the function above gives me this error:

transact to Contract.resetCounter errored: Error: Error: [ethjs-query] while
formatting outputs from RPC 'undefined' for method 'sendRawTransaction'
Error: [ethjs-format] hex string 'undefined' must be an alphanumeric 66 utf8
byte hex (chars: a-fA-F) string, is 0 bytes

What could be wrong here?


texts: How open local ethereum chain (leveldb) using Nodejs levelup package?

texts:
Read the article about how to get info from local chain, but example not work. My code stoped when i create connection to LevelDB of my local chain in var db = levelup(...):
var levelup = require('levelup');
var db = levelup('/Users/User/WebstormProjects/untitled/bin/chaindata');

//the genesis state root
var root = 'e5be92145a301820111f91866566e3e99ee344d155569e4556a39bc71238f3bc';

//Note: we are doing everything using binary encoding.
db.get(

    new Buffer(root, 'hex'),
        {
            encoding: 'binary'
        },

    function (err, value)
        {
            console.log(value);
        }
    );

"chaindata" is a copy of my local eth chain on Mac. Folder contains such files:

000002.ldb
000003.log
CURRENT
LOCK
LOG
LOG.old
MANIFEST-000004

So, when i try to open db get error: InitializationError: Must provide db.


texts: Can smart contract be used to enforce rule based auction?

texts:
I'm building a smart contract based auction system on top of ethereum, like this example.  Instead of the highest bidding price, the system will use a function f to compute the most optimal bid.

E.g., if each bid is represented with parameters (a, b, c), then the most optimal bid is the one that maximizes f(a, b, c).

The questions I have are:

Is this system feasible on ethereum?
Can function f be updated in the future?  How difficult is it?
Is it possible to pin a specific f for a contract, so attackers cannot implement a different function g and disrupt the decision making process?

Thanks


texts: What are the key criteria for meeting the ERC20 token standard?

texts:
I'm looking for a clear way to describe "the ERC20 token standard" to regular folks like me who are not developers, and can't seem to find a plain language articulation of the core components of that standard. Being a non-developer, the github thread where the ERC20 standard was developed is totally Chinese to me. Here is what I do understand and say about ERC20 at the moment (please edit if that is off):

The ERC20 token standard is a set of criteria developed by the Ethereum community for how to set up smart contracts on the blockchain in order to ensure optimal interoperability. ERC stands for Ethereum Request for Comments and this particular request was to help improve the standards to which developers should strive to adhere in developing smart tokens.

Below were my best sources for understanding ERC20 but none of them answer the question I asked above: What are the actual criteria?

themerkle.com/what-is-the-erc20-ethereum-token-standard/
www.ethnews.com/erc20-the-ethereum-token-standard
steemit.com/cryptocurrency/@cryptoadvocator/all-about-ethereum-erc20-token-standard


texts: Why do exchanges maintain their own wallet?

texts: On a crypto exchange, I transferred 1 ether from my account with let's say wallet A to my friend's wallet B. When I searched for my friend's wallet B on etherscan.io to see the transaction, the sender address belonged to crypto exchange's wallet C and not my wallet A. Why do the exchanges do not make the transaction directly from my wallet A to wallet B?


texts: Is it possible for a contract to auto-execute a function every hour?

texts: I have a contract with a manual function that checks the balance of the contract and if it's zero it changes certain values in mapping. How to make this happen automatically every hour?


texts: Calling an Ethereum contract function from PHP

texts: How can I call a contract function from PHP and print the return? Is there any good PHP libraries for that? thanks.


texts: How many Times I can Bid on Same domain name and Is There any way to increase bidding amount during auction

texts:
Is it Possible to increase my bidding during ENS auction period ?How can see highest bidding before reveling period.
How many times i can bid for the same doamin in 3 days aution period


texts: Unknown Accounts suddenly appearing in MetaMask wallet....?

texts:
My MetaMask wallet has multiple accounts which I did not create. I have no idea how they there.
Is my MetaMask wallet compromised? Or is this normal that MetaMask creates new wallet addresses when needed for certain transactions or webpages?
The unknown addresses are only visible in "Transfer between my accounts" which of course suggests that they are mine, but I cannot even access them or see the complete addresses.
I have attached a screenshot below the above account that is blurred out is mine, the other accounts below the blue line are the ones unknown and unaccessible to me. I cannot edit/delete them.
If any is familiar whit this please advice me on what to do.
Thanks guys


texts:
So I'm making a dapp. This portion uses smart contract for login. I need to add the ability to reset the user's password if they forget it.
contract Auth {
struct Credentials {
    string fullName;
    string email;
    string password;
}

mapping(string => Credentials) credential;

function createAccount(
    string memory name,
    string memory pass,
    string memory mail
) public {
    credential[mail].fullName = name;
    credential[mail].email = mail;
    credential[mail].password = pass;
}

function loginAccount(string memory mail, string memory pass)
    public
    view
    returns (string memory)
{
    if (
        keccak256(abi.encodePacked(credential[mail].password)) ==
        keccak256(abi.encodePacked(pass))
    ) {
        return
            string(
                abi.encodePacked(
                    credential[mail].fullName,
                    credential[mail].email
                )
            );
    } else {
        return "Wrong Password";
    }
}

function resetAccount(string memory mail) public {
    //reset acc
}

Sorry I have no idea where to go with this.


texts: Populus Unittesting: How to test a contract's fallback function?

texts:
How can I test the invocation of the fallback function by an external account of a contract using the Populus framework?
For example, this runs forever:
chain.wait.for_receipt(mycontract.transact({'value':10, 'from':accounts[1]}))

And these two simply fail:
chain.wait.for_receipt(mycontract.transact({'value':10, 'from':accounts[1]})())
chain.wait.for_receipt(mycontract.transact({'value':10, 'from':accounts[1]}).call())

I could just use one of accounts to send Ether to the contract, but how do I do that in Populus?


texts:
I am trying to run a test and I am getting the following message;

I have tried the following;

npm install scrypt

npm install web3

as to solve the yellow message and when running truffle test
truffle get's stuck and no test are shown...

This is the test code;

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

contract('TtdmToken', function(accounts) {

    it'sets the total supply upon deployment', function() {
    return TtdmToken.deployed().then()function(instance) {
    tokenInstance.totalSupply();
    }).then(function(totalSupply) {
        assert.equal(totalSupply.toNumber(), 100000,'sets the total supply to 1,000,000');
    });
  });
})

What might be causing the issue as it gets stuck with truffle test but other commands works but the yellow message keeps on showing...


texts:
While trying to connect Ganache-cli to remix, I get this error,

Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

But remix IDE is able to connect to testRPC and not Ganache-cli, i have both on my system, I tried with both local copy of remix as well with online remix IDE.


texts: Unable to understand buy and sell functions

texts:
As per my understanding Buy() allows main contact to buy coins in exchange of ether.
If I am correct, the question is how? We don't pass any value to the function like how much we want to buy. I executed the function on Mist, function executed fine but I couldn't detect any changes in my account. So it confused me about what actually buy() does.

function buy() returns (uint amount){
    amount = msg.value / buyPrice;                     // calculates the amount
    if (balanceOf[this] < amount) throw;               // checks if it has enough to sell
    balanceOf[msg.sender] += amount;                   // adds the amount to buyer's balance
    balanceOf[this] -= amount;                         // subtracts amount from seller's balance
    Transfer(this, msg.sender, amount);                // execute an event reflecting the change
    return amount;                                     // ends function and returns
}

Sell(): Allows user to sell coins and buy ether in exchange.
But the code didn't execute, giving Intrinsic gas too low error in Mist.

 function sell(uint amount) returns (uint revenue){
    if (balanceOf[msg.sender] < amount ) throw;        // checks if the sender has enough to sell
    balanceOf[this] += amount;                         // adds the amount to owner's balance
    balanceOf[msg.sender] -= amount;                   // subtracts the amount from seller's balance
    revenue = amount * sellPrice;
    if (!msg.sender.send(revenue)) {                   // sends ether to the seller: it's important
        throw;                                         // to do this last to prevent recursion attacks
    } else {
        Transfer(msg.sender, this, amount);             // executes an event reflecting on the change
        return revenue;                                 // ends function and returns
    }
}

Also couldn't understand use of if (!msg.sender.send(revenue)) throw;
I am beginner to ethereum.Help me to understand the buy an d sell functions.


texts:
I am new in ethereum blockchain and I am trying to understand completely how it works.

I have read this document, but there are still some points which are not obvious to me. One of these points is about transactions. In other words, I can't understand the exact structure and content of a transaction in ethereum.

As far as I am concerned, we have two types of accounts in ethereum. Regular accounts (Externally Owned Accounts - EOA) and contract accounts. Each account is identified by its address.

So, when we want to transfer some amount of money from EOA1 to EOA2 the transaction structure is:

Sender Id: Address of EOA1
Reciever Id: Address of EOA2
Amount of money: for example 1 Ether

But how about a contract transaction? For example, Suppose we have a contract with address A which has a function named Func1. So, when we call Func1 a transaction is created. But what is the content of this transaction?

these are the fields:

Invoker id
Contract address: In this case A
Gas price
Total cost = gasUsed * gasPrice

Is this correct?


texts: Can I create DApps over existing crypto in the network, if yes then please help me with some like or description of the process to create such DApps if anyone can point me some blog then it will be very good.


texts: Can I use web3js without setting the provider?

texts:
So I have two NodeJS applications, both implementing web3js.
The first node is used for creating and signing transactions, then it sends raw signed transaction to the second node. Finally, the second node submit it to Ethereum network using the set provider.

However, I wonder can I use web3js on the first node "without" connecting it to any provider? We do not want the first node to connect to Internet at all (except connecting to second node) since it contains private keys of accounts.


texts: Ethereum Wallet: error of no key for given address or file

texts:
In etherum wallet I am getting an error of no key for given address or file during deployment of the contract. What will be the reason for the same?

contract User{

    string public userName;

    function User(string _name){

     userName = _name;

    }

}


texts:
I'm developing a DAPP in a laptop. I setup a private test blockchain with one node to develop locally and do not have to spend real ethers.

It works fine, but when I start mining, the laptop gets noisy like a plane and the batteries get low too fast.

I'm asking if exists any trick to just mine slowly without consuming my batteries.

Right now, I'm mining about one block per second. It would be also good to mine one every 10-15 second or so. (Like the frontier chain).


texts: What's the minimum gaslimit guaranteed and sufficient for Dai v2 token transfer?

texts: I have (mulicollatral)Dai v2 in the wallet and I want to set the minimum possible gas limit such that my send transaction don't fail. Thanks


texts: I had version uped my metamask on firefox. It makes my metamask account renewed. I want login my old metamask accout

texts:
I had version uped my metamask on firefox. this version up makes my metamask account renewed.
I want to login my old metamask accout. I dont have my old acccunt private key or JSON for import old account.
but I have my old account seeds phrase.
please tell me how to login my old account. I think my metamask(firefox) is already installed and no way to input seeds phrase. should I remove metamask and reinstall on firefox , then ,  input my old account seed ? (and seed phrase is enought to login my old account?)


texts: trying to write a contract for Hotel menu in solidity, and try to map order and table number

texts:
I am new to programming, can any one help me to understand how to map the order number and the table number in a hotel contact, i tryed up to map both order and table but not able to get the proper linkage for both and out put as order 2 table number 1.
and adding items to a particular order as order1"item 1- Dosa, Qty2, item-2 idly Qty 1"
below is my source code.
pragma solidity ^0.5.0;

contract Menu{
    uint256 public BookingId;
    address public Guest;
    uint256 Qty;

    struct Menuitem{
        uint256  id;
        string name;
        uint256 Price;
    }
    struct table{
        uint256 tableid;
        uint256 numberofseats;
    }
      mapping (uint256 => Menuitem) public Order;
      mapping (uint256  =>mapping(uint256 => Menuitem)) public tableno;
      Menuitem[] itemarray;
      table[5] tablearray;

      function welcome() public {
          log0("welcome");   /*need to ask*/
      }

      function additem(uint256 _id, string memory _name, uint256 _price) public{

        Menuitem memory newitem = Menuitem(_id, _name, _price);
        Order[_id] = newitem;
        itemarray.push(newitem);
        Qty++;
      }
      function itemcount() public view returns(uint256){
          return Qty;
      }
      function deleteitem(uint256 _id) public{
          delete Order[_id];
          Qty--;
      }

      function getItem(uint256 _id) view public returns (string memory _name, uint256 _price) {
         return(Order[_id].name, Order[_id].Price);
    }
}

I have created a source code for menu contract, but not able to create order with more than the one 1 item
pragma solidity ^0.5.0;

contract HotelMenu{

                   struct Menu{
                                uint256 ID;
                                string Name;
                                uint256 Price;
                             }
                    uint256 ItemID;
                    mapping (uint256 => Menu) public Menuitems;
                    Menu[] public itemarray;

                    struct Order{
                                   //uint256 OrderId;
                                   uint256 ItemID;
                                   uint256 Qty;
                                }
                    uint256 NextOrder;
                    mapping (uint256 => Order) public Orders;
                    Order[] public orderarray;

                    event NewOrder (
                                        uint256 indexed ItemID,
                                        uint256 indexed OrderId
                                    );

                    function additemtomenu(string memory name, uint256 price) public
                                        {
                                        itemarray.push(Menu (ItemID, name, price));
                                        ItemID++;
                                        }
                    function PlaceOrder(uint256 _ItemID, uint256 Qty) public
                     {
                           //bookings[bookingId] = Booking(_propertyId, checkInDate, checkoutDate, msg.sender);
                           Orders[NextOrder] = Order(_ItemID, Qty);
                           //Property storage property = properties[_propertyId];

                           emit NewOrder(_ItemID, NextOrder++);
                     }

                    function GetOrder(uint256 OrderId) public returns(uint256 , uint256)
                     {
                         for (uint256 i=0;i<=orderarray.length;i++)
                         {
                             if(orderarray[i].ItemID == OrderId)
                             {
                                return (orderarray[i].ItemID, orderarray[i].Qty);
                             }
                         }

                     }

}

Regards,
Naresh


texts: Create Accounts Using Web3.js in Browser

texts:
TL;DR - Replicated Ethereum Blockchain. Running Local Node. Connecting Local Node to Web3.js in browser using RPC. Want to create addresses & send transactions

Details -

I have a blockchain that is forked from Ethereum. Thus all its functionalities are almost similar if not same. Before building a wallet for my blockchain, I'm trying to develop a wallet for Ethereum that works in the browser using web3.js.
I am not well versed with Node.js and hence want to use the browser version of web3.js

Having imported web3.js (version 0.20.6) from web3.min.js, I can view the web3 object in the console window. I can even use various functions such as web3.sha3 and web3.isConnected.

I can view the web3.personal.newAccounts() function and when I use it as web3.personal.newAccounts("passphrase"), it returns personal_newAccounts function is not available/does not exist

On trying to use web3.eth.accounts.create(), it tells me this function does not exist as the version I'm using is 0.x and version 1 stable release is not out yet.

How can I create addresses for my private blockchain local node and if possible send transactions using web3.js browser.


texts: Safe way to generate and store Ether on multiple paper wallets

texts:
I have a certain amount x of Ether in my wallet on my PC. Now I want to divide this amount x by 30, and print each x/30th of my Ether on a separate paper. So, basically, I'd just like to have 30 bills of Ether.

[Q1] Is there an intelligent, secure and convenient to do this?

[Q2] Is it even recommended to do this?


texts: Unable to send Ether from Mist, All funds & DAO tokens stuck in wallet!

texts:
Ever since I downloaded wallet version = Ethereum-Wallet-win64-0-7-5

Past transactions have disappeared!
Unable to send any funds, I can receive but nothing goes out!

Using earlier or later versions of the wallet has not solved the problem & its really frustrating because I am unable to work with my Eth & tokens.

I am currently using = Ethereum-Wallet-win64-0-7-6

PLEASE HELP!


texts: Unable to deploy smart contract through ether.camp on Ethereum Consortorium Blockchain

texts:
I have created a private ethereum block chain on azure using Ethereum consortorium block chain template.

After the deployment is suceeded I got the following attributes of block chain

ETHEREUM-RPC-ENDPOINT
Private key
User

Now by using ether.camp I am trying to deploy a contract by clicking a button "Send Contracts to Net". I am able to see the available contracts, configured the JSON RPC URL and Pkey .

When clicking on send I an getting the following message

  Account 0x2ad984558bd5c7df51024363e5752d65b2d4677d has only 0 wei, but
  need 7944040000000000 to create the contract(s).

The account being mentioned is not even my account.

Can any one help how to overcome this issue or any other ways to deploy a smart contract to the ethereum network.

Thanks in advance,
Mahesh Gupta


texts: I signed up for ethereum on my mac. I followed the instructions and this has been what has been going on since right after midnight last night. There is process, I'm just not sure what is going on. Am I mining?


texts: Ethereum POA ( proof of Authority ) for private network

texts:
I am trying to set up private network in ethereum with POA, but I am unable to do so.
getting below error

I have tried using puppeth manager to setup the genesis file.
The genesis file is set up to use clique as algo. Snip of genesis file is

I do understand from the error that it is related to the sealing/sealer of the block.. but how to define the accounts which can be used for sealing?
Any pointers in right direction would be helpful


texts: How to retrieve IP address and Port from Ethereum Node Records (ENR)?

texts:
Here are four Ethereum Node Records (as per EIP-778):

  - "enr:-Iu4QGuiaVXBEoi4kcLbsoPYX7GTK9ExOODTuqYBp9CyHN_PSDtnLMCIL91ydxUDRPZ-jem-o0WotK6JoZjPQWhTfEsTgmlkgnY0gmlwhDbOLfeJc2VjcDI1NmsxoQLVqNEoCVTC74VmUx25USyFe7lL0TgpXHaCX9CDy9H6boN0Y3CCIyiDdWRwgiMo"
  - "enr:-Iu4QLNTiVhgyDyvCBnewNcn9Wb7fjPoKYD2NPe-jDZ3_TqaGFK8CcWr7ai7w9X8Im_ZjQYyeoBP_luLLBB4wy39gQ4JgmlkgnY0gmlwhCOhiGqJc2VjcDI1NmsxoQMrmBYg_yR_ZKZKoLiChvlpNqdwXwodXmgw_TRow7RVwYN0Y3CCIyiDdWRwgiMo"
  - "enr:-Iu4QLpJhdfRFsuMrAsFQOSZTIW1PAf7Ndg0GB0tMByt2-n1bwVgLsnHOuujMg-YLns9g1Rw8rfcw1KCZjQrnUcUdekNgmlkgnY0gmlwhA01ZgSJc2VjcDI1NmsxoQPk2OMW7stSjbdcMgrKEdFOLsRkIuxgBFryA3tIJM0YxYN0Y3CCIyiDdWRwgiMo"
  - "enr:-Iu4QBHuAmMN5ogZP_Mwh_bADnIOS2xqj8yyJI3EbxW66WKtO_JorshNQJ1NY8zo-u3G7HQvGW3zkV6_kRx5d0R19bETgmlkgnY0gmlwhDRCMUyJc2VjcDI1NmsxoQJZ8jY1HYauxirnJkVI32FoN7_7KrE05asCkZb7nj_b-YN0Y3CCIyiDdWRwgiMo"

How to retrieve IP address and Port from the ENR? How do I know that this format is using my node's public IP address and not the local or private IP address?

What's the gain by not being easily able to verify the IP address?


texts: Fixed amount of Gas required for ether transfer

texts: why required gas for ether transfer fixed to  21000wei ?how they calculate the gas limit?could someone explain all computational steps involved during transfer ether from one account to another?


texts: Can't access to send_tokens function in erc20token-sdk-python library

texts:
I created the contract and trying to connect to ethereum mainnet using "erc20token-sdk-python" library. When I am trying to send tokens from one address to another it is showing "ValueError: No matching functions found". What am I doing wrong?

import erc20token
import json
contract_abi = '[{"constant": "True","inputs": [],"name": "name","outputs": [{"name": "","type": "string"}],"payable": "False","type": "function"},{"constant": "True","inputs": [],"name": "decimals","outputs": [{"name": "","type": "uint8"}],"payable": "False","type": "function"},{"constant": "True","inputs": [{"name": "_owner","type": "address"}],"name": "balanceOf","outputs": [{"name": "balance","type": "uint256"}],"payable": "False","type": "function"},{"constant": "True","inputs": [],"name": "symbol","outputs": [{"name": "","type": "string"}],"payable": "False","type": "function"}]'

token_sdk = erc20token.SDK(provider_endpoint_uri='https://mainnet.infura.io/12345678',
                           private_key='private_key_here',
                           contract_address='0x818fc6c2ec5986bc6e2cbf00939d90556ab12ce5',
                           contract_abi=json.loads(contract_abi),
                           gas_price=40, gas_limit=50000)
tx_id = token_sdk.send_tokens('address', 10)
print(tx_id)

Error logs:

  tx_id = token_sdk.send_tokens('0xbeb6f3FBA63E462fDA138c67b4ADbAd416859b8f', 10)
  File "/root/anaconda3/lib/python3.6/site-packages/erc20token/sdk.py", line 296, in send_tokens
    hex_data = self.token_contract._encode_transaction_data('transfer', args=(address, self.web3.toWei(amount, 'ether')))
  File "/root/anaconda3/lib/python3.6/site-packages/eth_utils/string.py", line 85, in inner
    return force_obj_to_text(fn(*args, **kwargs))
  File "/root/anaconda3/lib/python3.6/site-packages/web3/contract.py", line 734, in _encode_transaction_data
    fn_name, args, kwargs,
  File "/root/anaconda3/lib/python3.6/site-packages/web3/contract.py", line 663, in _get_function_info
    fn_abi = cls._find_matching_fn_abi(fn_name, args, kwargs)
  File "/root/anaconda3/lib/python3.6/site-packages/web3/contract.py", line 627, in _find_matching_fn_abi
    raise ValueError("No matching functions found")
ValueError: No matching functions found


texts: How to retrieve transaction hash value from the Promise object using web3js?

texts:
I'm trying to retrieve the transaction hash value after I call my smart contract method.

My Promise object looks like below.

returnPromise:
    Promise { "pending" }

    <state>: "pending"

    <prototype>: PromiseProto

    catch: function catch()

    constructor: function Promise()

    finally: function finally()

    then: function then()

    Symbol(Symbol.toStringTag): "Promise"

    <prototype>: Object { … }

Here's my code snippet:

const query = smartContract.methods.buyToken(Type, Title, Desc);
const encodedABI = query.encodeABI();
const tx = {
  from: walletAddress,
  to: contractAddress,
  gas: 2000000,
  data: encodedABI,
};
returnPromise = web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
  const tran = await web3.eth
    .sendSignedTransaction(signed.rawTransaction)
    .on('confirmation', (confirmationNumber, receipt) => {
      console.log('=> confirmation: ' + confirmationNumber);
    })
    .on('transactionHash', hash => {
      console.log('=> hash');
      console.log(hash);
      //console.log("HASH: ", hash);
      transHash = hash;
    })
    .on('receipt', receipt => {
      console.log('=> reciept');
      console.log(receipt);
    })
    .on('error', console.error);
});

console.log("returnPromise: " + returnPromise);


texts: Is there a decompiler for the binary data in the blockchain

texts: I want to know if there is a decompiler for the binary data in the blockchain, I want to know about the details of my contract after it was uploaded to the blockchain?


texts: ERC20 transfer function - Use "if, else" or "require"

texts:
Currently, I am planning to implement an ERC20 compliant transfer function in my ERC20 compliant contract as follows:

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

I would prefer to use "require" for the if block and not use the else, but then if it's false, I don't see how I'd then return a false. It would return an error or exception - correct?

Perhaps that would be the preferred behavior, but is it OK that a "false" does not get returned by the function when the require logic is not met?

I've also asked two instructors on Udemy, and I do believe that either of their answers would work, but their answers were different. Thus, it seems an important question to have discussed on record for our community.

I also plan to add openzepplin's safe math library functions as needed.


texts:
I am creating the api server for creating the interaction with crypto token smart contract , i want to know the required api's through which i can perform basic functionality of sending and receiving the tokens. And please suggest the required security measures for the api server .

Tech used for api server - node.js

Thanks in advance!


texts: What is the purpose of the "-1" in this code?

texts:
This is actually my own, contrived code, but it is based on what I am learning. In a video about creating arrays, he added a "-1" at the end of the line in which the ID number is pushed to the array.  He didn't explain, however, what the purpose of it was.  In my code, I added the "-1" for the array carListings, but left it out for the array truckListings.  Remix accepted the code and for the life of me, I cannot find any differences in the results.  It is important to note, however, that in the video, he used an address array, while I'm using integer arrays.  So, perhaps the "-1" has to do with addresses, but I still want to know either way, and there would still be the question of why my code was accepted with it.

// ---------- CARS ----------

uint public carID;
mapping(uint => Vehicle) cars;
uint[] public carListings;

function newCar(string _color, string _make, uint32 _year) public returns (uint ID) {
    carID ++;
    ID = carID;

    Vehicle storage car = cars[carID];
    car.color = _color;
    car.make = _make;
    car.year = _year;

    carListings.push(carID) -1;
}

// ---------- TRUCKS ----------

uint public truckID;
mapping(uint => Vehicle) trucks;
uint[] public truckListings;

function newTruck(string _color, string _make, uint32 _year) public returns (uint ID) {
    truckID ++;
    ID = truckID;

    Vehicle storage truck = trucks[truckID];
    truck.color = _color;
    truck.make = _make;
    truck.year = _year;

    truckListings.push(truckID);
}


texts:
I am setting up unit tests with for my contracts using truffle. I am using also testrpc, but having accounts with 2.123...... *10^37 Wei is not very helpful to visualise and debug things.

I am trying to setup custom testRPC account balances using $ testrpc --account="<privatekey>,balance" as seen here. However, what I get back is one account with again "infinite ether".

I have also tried to do :

var TestRPC = require("ethereumjs-testrpc");
var accountConfig = [
  {balance: 20000000},
  {balance: 20000000}
];
web3.setProvider(TestRPC.provider({accounts: accountConfig}));

as seen here and here , however truffle complains it cannot find the module "ethereumjs-testrpc".

In short the question then is : how to set up custom account balances for testRPC?


texts: Transaction reverted when testing requires/asserts in non void functions

texts:
im trying to test the requires of a Smart Contract using just solidity according to this article:

http://truffleframework.com/tutorials/testing-for-throws-in-solidity-tests

This is the contract, the throw proxy contract and the test:

/* Testing with solidity tests. */

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";

contract TestMyContract {

function testInitialStoredValue() {
    MyContract mycontract = new MyContract();

    uint expected = 24;

    Assert.equal(mycontract.mynumber(), expected, "First number set should be 24.");
}

function testTheThrow() {
    MyContract mycontract = new MyContract();

    ThrowProxy throwproxy = new ThrowProxy(address(mycontract));
    uint num = 7;
    MyContract(address(throwproxy)).storeNum(num);

    bool r = throwproxy.execute.gas(200000)();

    Assert.isFalse(r, "Should be false because is should throw!");

}

function testNoThrow() {
    MyContract mycontract = new MyContract();

    ThrowProxy throwproxy = new ThrowProxy(address(mycontract));

    MyContract(address(throwproxy)).storeNum(22);

    bool r = throwproxy.execute.gas(200000)();

    Assert.isTrue(r, "Should be true because is should throw!");

}

}

// Proxy contract for testing throws
contract ThrowProxy {
  address public target;
  bytes data;

  function ThrowProxy(address _target) {
    target = _target;
  }

  //prime the data using the fallback function.
  function() {
    data = msg.data;
  }

  function execute() returns (bool) {
    return target.call(data);
  }
}

If i run the tests i get this error:

If i change the storeNum function to void from

 function storeNum(uint mynum)
        public
        returns (bool success)
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

to

 function storeNum(uint mynum)
        public
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

the tests works..

Any ideas?

Im using Truffle v4.1.11

EDIT:

I have submited an issue in truffle github, maybe the recent changes on solidity has this constraint or breaks the test using a proxy

https://github.com/trufflesuite/truffle/issues/1001


texts: I've only begun with blockchain(rinkeby-testnet) and IOT. I use nodemcu (ARDUINO IDE) and mist. What should the rpc-ip address be? Do I have to establish an ethereum node in order to do that ?


texts: Truffle js test. Test not really testing

texts:
I have this tests that supposedly pass (in the terminal, I can see the checks). But they never actually run the code:

it("should add an exam to the exams list", () => {
        let hash_test = "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08";
        Exam.deployed()
            .then(instance => instance.addExam(hash_test, {from: accounts[0]}))
            .then(hash => {
                assert.equal(hash.valueOf(), hash_test, "Not returning the correct address");
                console.log("THIS");
            })
            .then(instance => instance.isOwner(hash_test, {from: accounts[0]}))
            .then(isOwner => {
                assert.equal(isOwner, "true", "Not recognizing hash correctly");
                assert.equal("true", "false", "NOT WORKING AT ALL");
            })
            .then(instance => instance.isOwner("THISISWRONG", {from: accounts[0]}))
            .then(isOwner => {
                assert.equal(isOwner, "false", "Not recognizing hash correctly")
            });
    });

As you can see, there is an assert.equal("true", "false" . But I still get the checks as if it passed:

  Compiling your contracts...

    Compiling ./contracts/Exams.sol

  Contract: Exams
      ✓ should pass this test
      ✓ should add an exam to the exams list
      ✓ Should add an student address to the people that passed the exam

  3 passing (68ms)

I don't know what could be wrong, my code is almost the same as the one in the official site.


texts: web3: Do I need to `get` past events and `watch` future events separately?

texts:
As discussed before I managed to get past events via

myContract.myEvent({}, { fromBlock: 0, toBlock: 'latest' }).get((error, results) => {

But it seems that for future events I need to watch for them via

myContract.myEvent().watch((error, result) => {

That is real odd in that I need to implement two event handlers - one for past and one for future events. Is there currently a cleaner way of handling this?


texts: require(msg.sender.call("")): No matching declaration found after argument-dependent lookup

texts:
I am trying to compile the following Solidity program:
pragma solidity ^0.5.9;

contract Mutex {
bool locked;

modifier noReentrancy() {
      require(!locked);
      locked = true;
      _;
      locked = false;

}

function f() noReentrancy public returns (uint) {

        require(msg.sender.call(""));
        return 1;

}

}

I am getting the following error message:
solc Mutex.sol Mutex.sol:13:7: Error: No matching declaration found after argument-dependent lookup.
       require(msg.sender.call(""));
       ^-----^

Somebody, please guide me.


texts: Giving me error while trying to pass the string in constructor of a smartcontract

texts:
This is my Election smart contract.
pragma solidity ^0.4.17;
contract Election{
    struct candidate{
        string name;
        uint votecount;
    }
    struct voter{
        bool authorized;
        bool voted;
        uint vote;
    }
    address public owner;
    string public electionName;
    mapping(address=>voter) voters;
    candidate[] public candidates;
    uint public totalVotes;
    function Election(string _name) public{
        owner = msg.sender;
        electionName = _name;
    }

    modifier ownerOnly(){
        require(msg.sender==owner);
        _;
    }
    function addCandidate(string _name) ownerOnly public{
        candidates.push(candidate(_name,0));
    }
    function getNumcandidate() public view returns(uint){
        return candidates.length;
    }
    function authorize(address _person) ownerOnly public{
        voters[_person].authorized=true;
    }
    function vote(uint _voteIndex) public{
        require(!voters[msg.sender].voted);
        require(voters[msg.sender].authorized);

        voters[msg.sender].vote =_voteIndex;
        voters[msg.sender].voted = true;
        candidates[_voteIndex].votecount +=1;
        totalVotes+=1;
    }
    function whoWon() ownerOnly public view returns(string){
        uint maxi=0;
        string memory winner;
        for(uint i=0;i<getNumcandidate();i++)
        {
            if(candidates[i].votecount>maxi)
            {
                maxi=candidates[i].votecount;
                winner=candidates[i].name;
            }
        }
        return winner;
    }
    function end() ownerOnly public returns(uint){
        selfdestruct(owner);
    }
}

This is the react code where i'm trying to pass the string value in election function after submitting the form.
import React, {Component} from 'react';
import web3 from './web3';
import Election from './election';

class Conduct extends Component{
    constructor(props){
        super(props);
        this.state={
            owner:'',
            elename:''
        }
    }
    async componentDidMount(){
        window.ethereum.enable();
        const owner = await Election.methods.owner().call();
        const elename = await Election.methods.electionName().call();
        this.setState({owner,elename});
    }
    election = async event=>{
        event.preventDefault();
        const accounts = await web3.eth.getAccounts();

 wait for your transaction

        await Election.methods.Election(this.state.elename).send({
            from:accounts[0]
        });

Yout transaction is successful

    }
    render(){
        return(

                <form onSubmit={this.election}>

Enter the election name

                    <input type="text"
                    value={this.state.elename}
                    onChange={event=>this.setState({elename:event.target.value})}
                    />
                    <button>Held election</button>
                </form>

The current name of election is {this.state.elename}

        );
    }
}

export default Conduct;

Error:-Unhandled Rejection (TypeError): election__WEBPACK_IMPORTED_MODULE_3_.default.methods.Election is not a function


texts: I've been reading a lot about how smart contracts work, and I'm a little new to the area, but why do we need decentralized oracles? It feels like I can just make an API call from wherever and it's OK?


texts: What is the work of self destruct in a contract?

texts: How it can be used for handling force sending of ether to a contract without triggering fallback function ?


texts: What is use of HDWalletProvider in Truffle config?

texts:
The sample code here for deploying to Ropsten used HDWalletProvider and a mnemonic in the config, but I am not sure I understand its purpose. Is this just telling it the account that will become the contract owner when you deploy?

var HDWalletProvider = require("truffle-hdwallet-provider");

// 12-word mnemonic
var mnemonic = process.env.NMEMONIC;

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },
    ropsten: {
      provider: new HDWalletProvider(mnemonic, "https://ropsten.infura.io/"),
      network_id: 3 // official id of the ropsten network
    }
  }
};


texts: how are conditional JUMPI opcodes valid?


texts: I have been unsuccessful in trying to sync a new wallet or mist. I deleted the blockchain data and started over and it seemed to be syncing quite fast again, was more than halfway done in a few hours. I left it overnight and in the morning it was starting over again, was only at block 4000. I'm wondering if I should just wait for the next hardfork? Isn't it supposed to address some of these syncing issues?


texts: Where / How to host several connected smart contracts?

texts:
I recently played a bit with solidity, creating some tokens, working with functions and so on.

Until now i only published the contracts via https://ethereum.github.io/browser-solidity/.

But how does it work if i want to add more contracts, related to a token? Specific functions, sales, etc.

Is there a function within the compiler where i can connect contracts - or do i have to host them somewhere together in a folder?

Thank yaa


texts: Is it feasible to implement a functional smart contract language for Ethereum?

texts:
Would it be feasible to implement Clojure (and persistent data structures) on EVM?
Or another functional language?


texts: "Callback contain no result" and "Bad jump destination" errors

texts:
When calling testnet contract ( https://testnet.etherscan.io/address/0xc03db39c18b6056f8c3a3a5495a1e11f3ff8885a ) method sendFundsToFriend:

/* Faucet: Send funds, 1 Ether, to a new contact/friend */
function sendFundsToFriend(address to) {
    if (to.balance > 1000000000000000000) {
        faucetResult(msg.sender, to, 'Friends balance higher than 1 Ether'); // Event Log
        throw; // If friend has enough funds (> 1 Ether), do not send anymore
    }
    if (this.balance < 1000000000000000000) {
        faucetResult(msg.sender, to, 'Faucets balance lower than 1 Ether'); // Event Log
        throw; // If SC funds are not enough(< 1 Ether), do not send funds
    }
    bool dummy = to.send(1000000000000000000);
    faucetResult(msg.sender, to, 'Sent 1 Ether to friends account'); // Event Log
}

it throws the following errors:

"Callback contain no result" => when calling contract method through solidity-browser and Metamask.

"Bad jump destination" => when calling contract method through geth node.
    Trace => https://testnet.etherscan.io/vmtrace?txhash=0xa3b522fe104ad9b34cbae4235b59296e624c42665f5e2d6d5b509f4f02c52904

According to Problem setting uint value to zero and https://www.reddit.com/r/ethdev/comments/5m6j1q/heres_an_interesting_solidity_problem_ese_problem/ it looks like a bug in Solidity, (Metamask case) due to Browser Solidity interacting with geth.

And "Bad jump destination" sometimes it is due to an invalid array index or the lack of "memory" keyword on local variable declarations, but none of those cases is present at sendFundsToFriend method, I think.

When runnig on local Javascript VM (no node connection) it throws this error:

VM Exception: invalid JUMP at ac4467b97a805884f19a44b98da45c3fe7c604bc2ce1eaabf19fd83a1126f253/692a70d2e424a56d2c6c27aa97d1a86395877b3a:7906

I have found out error throws when executing this condition:

if (this.balance < 1000000000000000000) {
    throw;
}

So, any idea what is wrong with this code? Any way to debug the code or find out more information about the errors? Thx!

Refs:

Error encountered during contract execution [Bad jump destination]

How to debug Bad jump destination error

Bad Jump Destination error


texts: brownie steps to compile, deploy and interact on ropsten

texts:
I have created a smart contract and deployed it on ropsten with brownie framework.
Here are the steps I've done:

Run the command:
$ brownie init projet1

I have created my contract in contracts/Contrat1.vy file

I have run:
$ brownie compile

I have created an Ethereum account and I've sent some ether on it:
$ brownie accounts generate mon_account2

I have created this file for deployment: scripts/deploiement.py:
  from brownie import Contrat1, accounts

  def main():
    compte = accounts.load('mon_account2')
    t = Contrat1.deploy({'from': compte})

I have created a project on infura and I've got a project id

I have created an account and an API TOKEN KEY on etherscan

I have run:
$ export WEB3_INFURA_PROJECT_ID=<my_infura_projectid>
$ export ETHERSCAN_TOKEN=<my_etherscan_api_token_key>

I have run:
$ brownie run deploiement --network ropsten

At this step, my contract is deployed on ropsten. Its deployment address is displayed on screen.

Now I want to interact with this contract. So I have run:
$ brownie console --network ropsten
provider = Contract.from_explorer('<my_contract's_deployment_address>')

I suppose I can now send transactions through provider variable.

Here are my questions:

My infura secret was not asked. So I suppose anyone can call my infura project url ?
Is there a way to avoid to work with Etherscan ? I have worked previously with truffle and it was not necessary to get an Etherscan account for deploying contract.
Is there a way to avoid to export WEB3_INFURA_PROJECT_ID and ETHERSCAN_TOKEN ? Is there a way to put these values in a project configuration file ?
When launching Contract.from_explorer, I get this error:

ValueError: Failed to retrieve data from API: Contract source code not
verified

How should I fix that?
Thanks a lot


texts: I am purchasing cvc through shapeshift. where is my ethe return address

texts: I am purchasing cvc through shapeshift. Shapeshift is asking me my ethe refund address. do have to create one? or.....


texts:
For example, we have a contract:

contract A {

    modifier checkCaller() {
        require(msg.sender == 0x123);
        _;
    }

    function doSmth() checkCaller {}
}

We make child contract and override function:

contract B is A {
    function doSmth() {
        super.doSmth();
        // ... do more
    }
}

Do I need to explicitly use modifier checkCaller in the child contract B? As I understand super.doSmth() will throw properly. Correct?


texts: Casper FFG slashed deposits distribution?

texts: How is the slashed funds distributed upon failing to follow the requirements as a validator?


texts: Does this architecture violate a Dapp-philosophy?

texts:
Sorry for my English, again...
First I wanted to place this post on Etherium Reddit. If it needs to be there, just close this question...

I need to implement this logic:

From Wallet 1 user sends Smart Contract 1000 Ether by calling a function in Smart Contract.
Smart Contract holds 1000 Ether until some external event occurs. Smart Contract checks this by polling information from external API. If this event does not occur after two days Smart Contract reverts Ether.
Smart Contract sends 1000 Ether to Wallet 2 (if the external condition of the previous step does occur).

But I need do this for users who can`t have blockchain ("Etherium Wallet" app e.g.) on own computers.

And here's the next image...

Standart authentication - Login/Pass, OAuth, not important...
We identified the user credentials and associate it with a particular Wallet Account (0x123...).
Now we send commands to Geth using the Wallet Account of the previous paragraph.
Finally, end-user has a limited set of possibilities by using the UI in the end-user app.

Is it okay to do this server-side layer, and do some authentication?


texts: I have a Client who wants to buy ethers, and my client wants to buy in big volume $500k. How do facilitate this transaction from euros to ethers?


texts: modify truffle console command to execute function on ropsten deployed contract thru geth

texts:
There are a couple of commands, reproduced below, which I've used successfully in the truffle console, executing on testrpc, which work and elicit the responses that I expect.

How can I change them to make them applicable to ropsten? How can I send them through the geth console?

The contract I'm trying to interact with was deployed to the ropsten testnet in this transaction.

The code of the contract can be found on my GitHub.

The first command I want to use is to increase the iteration variable:

Incrementer.deployed().then(function(instance) {
      meta = instance;
      return meta.increment(1);
})

The next thing I want to do is verify the result:

Incrementer.deployed().then(function(instance) {
    meta = instance;
    return meta.getIteration();
})

At this point I've figured out that I have to use the ABI, but that's as far as I got.

How can I transmogrify those commands into something that I can send through the geth console into the ropsten testnet?


texts: How to create random number in solidity except sha3?

texts:
I am using sha3 to create 3 unique id in a same function. But results are same for all of them because it is using timestamp like this
"uint256 random = uint256(sha3(block.timestamp)) +1;".

So, I want to know how to create random or unique id which will be not dependent on timestamp?


texts: Is it okay to store your private key on Ubuntu server in .env?

texts: Lets say you have to sign transactions / messages real-time. It seems I must store the private key in the server. What if the address stores millions of dollars of value? Is simple LEMP server enough with storing private key in .env file?