texts: can't find contracts on the BSC via fully synchronized local node

texts:
I am trying to find a deployed contract via my fully synchronized local node, but I can't find it. it turns out that I can't find any contract in fact. I tried running eth.getcode("0x0eD7e52944161450477ee417DE9Cd3a859b14fD0") and it returns "0x" which means that there is no contract attached to that address.
that example is easily found on the BSC eth scanner
my eth.syncing result cleary show that the node is practically synchronized :
{
  currentBlock: 7465077,
  highestBlock: 7465150,
  knownStates: 168515734,
  pulledStates: 168475588,
  startingBlock: 7463977
}

what could be the problem ?
i am running the official config from the bsc tutorial


texts:
Why are these variables confounding? The returned result shows that both loops are effecting both bytes variables (second returns the same result).

function mix() public returns (bytes) {

    bytes first;
    for (uint8 cnt = 0; cnt<8; cnt++) {
        first.push(9)
    }

    bytes second;
    for (uint8 cnt2 = 0; cnt2<8; cnt2++) {
        second.push(8);
    }

    return first;
}

Returned result:
'0x09090909090909090808080808080808'


texts: Where does etherscan gets contracts code?

texts:
On etherscan.io there is a contract`s source code tab, where does Etherscan get this code? If developers make it available for Etherscan then is it necessary for them to public it or specifically make it available on Etherscan?

For example this code of cryptokittes can be found on Etherscan along with several other dapps.


texts: In solidity use of require and assert is recommended than using if else conditions but in every solidity example where modifiers are used instead of require if else is used. So is it Okay to use if else in modifiers.


texts: Parity light node does not broadcast transactions for 4 hours

texts:
I have been running parity light node for a while. And recently, when I send ETH or any token using rpc method sendTransaction, my parity node does not broadcast those transactions over the network. Etherscan shows that transaction is not found for 4-5 hours.
What could be possible solutions to the problem? Should try to connect to some custom nodes, should I use a full node (not the light one). Or maybe there is some better technologies than parity (like infura, geth)?
Thanks in advance!


texts:
I'm looking at KittyBreeding.sol and see

 /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex.
    ///  Also increments the cooldownIndex (unless it has hit the cap).
    /// @param _kitten A reference to the Kitty in storage which needs its timer started.
    function _triggerCooldown(Kitty storage _kitten) internal {
        // Compute the end of the cooldown time (based on current cooldownIndex)
        _kitten.cooldownEndTime = uint64(now + cooldowns[_kitten.cooldownIndex]);

but I don't see where "now" is defined, except in their kitty-core.test.js

How does this DAPP track time, which lets the website show timers?


texts: What decides on the need to use uint8 or uint256 instead of just uint

texts: Why is there a need to specify uint8 or uint256, why isn't uint enough? isn't this all about optimizing gas costs, and I assume the solidity optimizer will do this.


texts: Transaction fail (Tx is Successful in Remix)

texts:
I get a transaction failed when trying to execute the following contract:

pragma solidity ^0.4.23;
  pragma experimental ABIEncoderV2;
  contract state {
      uint256 contract_version = 1;
      function set_version(uint256 cv_n) public {
                contract_version = cv_n;
      }
      function get_version() public view returns (uint256) {
                return contract_version;
      }
  }
  contract complicated {
     state st;
     constructor() public {
            address st_address = new state();
            st = state(st_address);
     }
     function set_version(uint256 cv_n) public {
            st.set_version(cv_n);
     }
     function get_version() public view returns (uint256) {
            return st.get_version();
     }
  }

And to execute the contract using solidity I use the following code derived from the example:

compiled_sol = compile_source(contract_source_code) # Compiled source code
contract_interface = compiled_sol['<stdin>:complicated']

w3 = Web3(Web3.TestRPCProvider())

w3.eth.defaultAccount = w3.eth.accounts[0]

Greeter = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])

tx_hash = Greeter.constructor().transact()

tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

greeter = w3.eth.contract(
    address=tx_receipt.contractAddress,
    abi=contract_interface['abi']
)

tx_hash = greeter.functions.set_version(10).transact()

w3.eth.waitForTransactionReceipt(tx_hash)

print('Updated contract greeting: {}'.format(
    greeter.functions.get_version().call()
))

Using Web3py I get the following error message:

  ValueError: {'code': -32000, 'message': 'Server error', 'data':
  {'type': 'TransactionFailed', 'args': [], 'message': ''}}

When I import the contact to remix the contract works perfectly


texts: How can I interaction to a contract by address from another contract?

texts:
I have to access methods of one contract from another contract body. How can I realize that using just a address of first contract?

contract KittyShelter{
    address KittenRegistry;   //Here, KittenRegistry - is another contract

    constructor(address _KittenRegistry) public{
        KittenRegistry = _KittenRegistry;
    }

    function storeKitty(uint256 catId, uint256 time) public{
        KittenRegistry;
    }
    function retrieveKitty(uint256 catId) public{

    }

}

Using address is a requirement


texts: Adding a binance smart chain on metamask results in same address for Eth and BNB, how does it work?

texts: Creating a trust wallet account gives different addresses for different currencies


texts: Which ethereum framework to choose Traffle vs Brownie?

texts:
I know that the most used frmaework for smart contract testing deployment etc is Traffle. But, since I am not very good at javascript (i am mainly coding in python)- I saw there is an option to use Brownie (or Populus).
How do these 2 frameworks differ, will there be any drawbacks if choosing Brownie over Traffle? Any differences at all?
Any recommendations?


texts: Having issues using the Drizzle library in React

texts:
Using Ubuntu 16.04

Greetings, all
I was following the tutorial for getting Drizzle up and running located here. I advanced to this step when I attempted to run the app using the "npm start" command from the terminal. I was then greeted with an error reading "TypeError: drizzle is undefined." I tried again after updating packages via npm, but the error continued. I've reproduced the code I'm using below:

app.js:

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './App.css';

    class App extends Component {
      state = { loading: true, drizzleState: null };

      componentDidMount() {
        const { drizzle } = this.props;

        // subscribe to changes in the store
        this.unsubscribe = drizzle.store.subscribe(() => {

          // every time the store updates, grab the state from drizzle
          const drizzleState = drizzle.store.getState();

          // check to see if it's ready, if so, update local component state
          if (drizzleState.drizzleStatus.initialized) {
            this.setState({ loading: false, drizzleState });
          }
        });
      }

      compomentWillUnmount() {
        this.unsubscribe();
      }

      render() {
        if (this.state.loading) return "Loading Drizzle...";
        return
Drizzle is ready
;
      }
    }

    export default App;

index.js

            import React from 'react';
            import ReactDOM from 'react-dom';
            import './index.css';
            import App from './App';
            import registerServiceWorker from './registerServiceWorker';
            // import drizzle functions and contract artifact
            import { Drizzle, generateStore } from "drizzle";
            import 'contract_name' from "./contracts/'contract_name'.json";

            ReactDOM.render(<App />, document.getElementById('root'));
            registerServiceWorker();

            // let drizzle know what contracts we want
            const options = { contracts: ['contract_name'] };

            // setup the drizzle store and drizzle
            const drizzleStore = generateStore(this.props.options);
            const drizzle = new Drizzle(this.props.options, drizzleStore);

I replaced the actual name of the contract I'm using with 'contract_name' for privacy reasons.
Is there anything obvious that I'm doing wrong?


texts: Major conceptual misunderstandings about genesis.json

texts:
I am having a hugely difficult time understanding the genesis.json file.

Assumption: it seems to me that it serves to both initialize the first block, and also set configuration parameters for the rest of the chain. True or false?

Questions:

Is the first block on the Ethereum mainnet blockchain always the same regardless of what else is in the genesis.json file? How specifically does the genesis.json file affect it?
If a new EIP is accepted, then the genesis.json file might change. Specifically, how would this make the first block look different? Would it?
Why are things like nonce, mixHash, and coinbase options to put in the genesis.json file? What purpose do they serve if the first block can't be mined?
Why do I need a genesis.json file if I end up "syncing" with peers and downloading their entire blockchain anyway? Am I actually creating the first block myself through genesis.json, and then syncing the rest with my peers?
On the Ethereum mainnet, the genesis block allocates ether to certain accounts. Is there a corresponding genesis.json file that has those accounts in the alloc {} section? Or was that first block somehow created without this file?


texts: Is there a decentralized exchange that handles buying Ether (and other cryptocurrencies) for fiat money as well as other cryptocurrency?

texts:
I was looking at dapps a few days back (maybe on https://www.dapp.com ?) and remember encountering a decentralized exchange that allowed users to buy Ether with fiat currency (I specifically remember PayPal for some reason) as well as exchange cryptocurrencies.
This seemed awesome but I forgot to save the URL. I scoured the internet looking for this exchange but no dice.
Is this real or am I slowly descending into madness? (or both?)


texts: How To Transfer Tokens Out Of Metamask Wallet

texts:
I have some tokens in my Metamask wallet and want to transfer them to an exchange to trade but I don't know how to do.  Metamask now allows you to see the tokens as per the recent upgrade but I don't see any way to send tokens.

Would appreciate your advise.

Best regards,


texts: Is there a way to call a Solidity function by its string name?

texts:
Since functions are not first-class objects in Solidity, is there any way to invoke a dynamically-determined function at runtime? e.g.

string fname = "Bar";

function Foo() {
  InvokeByName(fname);
}

function Bar() {
  // do something
}

Please respond regarding the feasibility and disregard security for the purpose of this question.


texts: constructor followed by three modifier / instantiation?

texts:
I saw this code snippet on openzeppelin,

contract DoggoToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable {

constructor(
    string name,
    string symbol,
    uint8 decimals,
    address[] minters
)
    ERC20Burnable()
    ERC20Mintable(minters)
    ERC20Detailed(name, symbol, decimals)
    ERC20()
    public
{}

and I can't figure out what ERC20Burnable(), ERC20Mintable(minters), ERC20Detailed(name, symbol, decimals), and ERC20() behind constructor stands for.

Is it representing modifier, or contract instantiation?

And is there any using guide for this syntax?

Thanks.


texts: are deployed address of an ERC20 smart contract and its token coinbase address the same?

texts: When an ERC20 smart contract (for example, @openZeppelin ERC20 contract) is deployed to ethereum network, there will be a deployedAddress of contract returned.  Meanwhile the token is minted after deployment with a coinbaseAddress. Are the deployedAddress of the contract and coinbaseAddress of token the same?


texts:
Is there any stable coin, which can already be used with smart contracts?

If not, is there a possibility to exchange a stable coin in real time into a smart contract feasible coin like ETH by help with a smart contract? E.g.:

Tether -> ETH

and back

ETH -> Tether

Many thanks in advance!


texts:
I just upgraded my code to Solidity 0.5 and am trying to use the truffle framework with it. I did update my code in Remix and it does seem to work.

The problem I have is that I am unable to compile my code with truffle. I get this error message:

  SyntaxError: Source file requires different compiler version (current
  compiler is 0.4.24+commit.e67f0147.Emscripten.clang - note that
  nightly builds are considered to be strictly less than the released
  version pragma solidity ^0.5.0;

I have reinstalled truffle, tried it with the beta version (by first running npm -g uninstall truffle and then running npm -g install truffle@beta, reinstalled solc, but nothing seems to work so far. Does anybody have any idea about what the problem could be?


texts: How to convert my custom ERC20 token to BEP20?

texts:
I have my custom token on the Ethereum network and I want to send part of the tokens to the binance smart chain. That is, issue a wrapped token.For example:
https://etherscan.io/token/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984
https://bscscan.com/token/0xbf5140a22578168fd562dccf235e5d43a02ce9b1
or
https://etherscan.io/token/0xa31b1767e09f842ecfd4bc471fe44f830e3891aa
https://bscscan.com/token/0xe64f5cb844946c1f102bd25bbd87a5ab4ae89fbe
Perhaps burgerswap will help me, but I tried to create a cross-chain asset and the transaction was canceled


texts: How many  contract can be stored in One block in blockchain ? What happen if sub class call the super class , if super class is already deployed and sub class contract is just deployed ?


texts: Quorum Private Transactions and zk-SNARKS

texts:
In Quorum, understand that zk-Snarks is the technology behind Zero Security Layer (ZSL).

How does the ZSL relate to Quorum Private Transactions? Does ZSL enable private transactions or are they separate things?


texts:
When I call web3.eth.blockNumber from a specific full-node, where does it getting the last block?

I know that the full-block holds part of the chain which he gets from gossiping with other full-nodes.

My guess the node consistently holds a version of the blockchain and just checks the blocks head/last block, is that right?

How's that process works with light-client?


texts: How does Ethereum enable self sovereign identity?

texts:
If everything on the Ethereum blockchain is public, then why is it apparently so useful for managing identity?

From what I gather this has something to do with IPFS, but how does it all work? How do smart contracts enable effective identity management?


texts: How to compile Solidity contracts with Geth v1.6?

texts:
I tried to compile the following contract within geth:

pragma solidity ^0.4.8;

contract Test {
    uint256 public value;

    function Test() {
        value = 123;
    }
}

using the following commands on the flattened source:

> var testSource = "pragma solidity ^0.4.8; contract Test { uint256 public value; function Test() { value = 123; } }";
undefined
> var testCompiled = web3.eth.compile.solidity(testSource);
Error: The method eth_compileSolidity does not exist/is not available
    at web3.js:3104:20
    at web3.js:6191:15
    at web3.js:5004:36
    at <anonymous>:1:20

As described in eth_compilers, eth_compileSolidity are gone in go-ethereum 1.6.0 #3793, the ability to compile Solidity source has been removed from within geth.

How can I compile my Solidity source code?


texts: solc 0.7.0 --allow-paths --base-path woes on (Version: 0.7.0+commit.9e61f92b.Linux.g++)

texts:
I have a library Foo.sol in /logicalroot/src/main/sol/lib/Foo.sol
I have a contract MyContract in /logicalroot/src/main/sol/contracts/MyContract.sol
That contract sources this:
import {Foo} from "Foo.sol";

Executing from /logicalroot
solc-static-linux-0.7.0 --abi --bin --overwrite -o build/main src/main/sol/contracts/MyContract.sol

I cannot get solc to find the import despite many permutations of command line args and import decs, e.g.:
import {Foo} from "Foo.sol";
import {Foo} from "./Foo.sol";
import {Foo} from "/Foo.sol";
import {Foo} from "../lib/Foo.sol";

and all manner of --allow-paths and --base-path setups.  The only way I can get it to run is with Foo.sol copied into the same dir as MyControl.sol and no command line --allow-paths or --base-path args and the import being:
import {Foo} from "./Foo.sol";  // NOTICE the dot slash path!

Then it works perfectly fine!  But not even a symlink works, e.g.
$ cd contracts
$ ln -s ../lib/Foo.sol .

Is this a solc 0.7.0 issue perhaps?  Any clues for an old-time C #include "file.h" guy would be much appreciated.


texts:
I defined my method as: (for simplicity)

function exampleOfPassingWeiAsArgument(uint amount) public returns (uint roundId) {
    // More than 0.01 ETH
    require(amount > 10000000000000000);
}

But when I pass the following value using remix UI: "11000000000000000",

I get the following error:

  Error encoding arguments: Error: Assertion failed

When I pass one zero less: "1100000000000000" it gets through but I crash obviously due to the "require" check as I am sending too few amount in Wei:

  The transaction has been reverted to the initial state.

BTW: I am not trying to perform a transfer just pass Wei amount of ether as a function argument.

Any idea why I can't pass uint 11000000000000000 ?


texts: Can we always statically determine which functions will be invoked at compile time(not at runtime)?

texts:
A question in one sentence:

Regarding function call expressions in Solidity, can we always statically determine which functions will be invoked at compile time(not at runtime)?

Example Code:

contract A {
    uint256 public n;
    function set () public {
        n = 50;
    }
}

contract B is A {
    function set () public {
        n = 40;
    }
}

contract C is A,B {
    function test (uint n) public {
        A a;
        if (n==1){
            a = new A();
        }
        else{
            a = B(new B());
        }
        a.set(); // member of A or B?
    }
}

Considering Java programs, it seems that, at compile time, we cannot determine whether the “set” function, invoked in the "test" function in contract C, is a member function of A contract or B contract. However, inspecting AST generated by a Solidity compiler (with an option solc --ast-compact-json), the invoked “set” function is referred as a member of A contract, not B contract. Is it an intentional feature of Solidity?


texts: Previously i was to start my geth network but suddenly i m getting  error="chain reorged during section processing".


texts:
I am attempting to evaluate the exact implementation of the MIX block of the hashing mining. There is much information (may be too much) but could not locate any that describes the detailed implementation of the MIX function.

Here is a diagram that explains what exactly I am looking for:

I am interested in the EXACT steps for implementing a "Mixing Function" block.


texts:
Hi guys i have one really big problem.
I have this pice of code

function showInfo(uint _pesel) public onlyMainPerson(msg.sender) returns (string memory, string memory) {
    string memory x = showName(_pesel);
    string memory y = showDate(_pesel);
    return(x,y);
}

function showName(uint _pesel) private view returns( string memory) {
    return(wills[_pesel].name);
}
function showDate(uint _pesel) private view returns( string memory) {
    return(wills[_pesel].date);
}

And i want to use it in my web app, i'm doing it by

 const names = await this.state.contract.methods.showInfo(123).send({from: this.state.account}, (e) => {
        console.log("done")
        console.log(names);
    })
    console.log(names);

But it is not working! It only shows "undefinded". How to solve it?
Thanks in advance!


texts: Create-React from truffle: "return this.setState({ storageValue: result.c[0] })"

texts: In the Create-React box from Truffle, why do we retrieve a uint value from a function call with "result.c[0]" instead of "result"? What's the c[0]?


texts: Strange result for w3.eth.filter({'fromBlock': 2500000, 'toBlock': 'latest'})?


texts:
I have a particular function in solidity which basically adds a Certificate in a mapping when called. However for the certificate to be actually added on the blockchain, it needs to have been signed by both parties before adding it. What is the best way to do this please? At the moment I have it implemented without getting confirmation from the second party. I have read about web3 signatures but don't know if i should use those in this case. Upon the first party generating the transaction I will send a message via socket.io to the party which the transaction is aimed to. This party can then either sign it or not. If it is signed then I want to add the certificate to the blockchain.

Thanks in advanced


texts: Hashes of all previous blocks are known but why the hash of block.number-1 is vulnerable and not the remaining 255 blocks?

texts:
I have read at different places that blackhash(block.number-1) is vulnerable (to miner's blockhash(block.number-1) vulnerability) because the hash is available but what about the other previous 255 hashes? For instance why blockhash(block.number-2) is not vulnerable even though it is also available. Somebody please guide me.
Zulfi.


texts: Understanding what events are doing in Solidity

texts:
CONTEXT OF THE QUESTION:

The references at the end of this post gave me the following understanding of events:

  Whenever a transaction takes place that is meant to alter information
  in the blockchain, an event is the tool used to do the logging of that
  information.

Since I am coding my first ERC-20 Standard compatible Token, here is an example of the usage of events:

mapping (address => uint256) public balances;
event Transfer(address indexed from, address indexed to, uint tokens);

function transfer(address to, uint tokens) public returns (bool success)
{
    balances[msg.sender] = balances[msg.sender].sub(tokens);
    balances[to] = balances[to].add(tokens);
    Transfer(msg.sender, to, tokens);
    return true;
}

source: https://theethereum.wiki/w/index.php/ERC20_Token_Standard

The second line declares an event that has 3 input variables, who is sending (from), who is receiving (to), and the amount being sent (tokens). And when the function transfer is involved we see the usage of the event. It makes sense to me that this is where it should be involved, but what I don't understand is how Solidity ties this code:

event Transfer(address indexed from, address indexed to, uint tokens);

with making sure that the balances of users are not faked. The event in my mind must be linking the 3 parameters together into the blockchain, but how does that linking happen? and how does the blockchain then prevent balances from being faked.

DETAILED QUESTIONS:

What happens behind the scenes that links the Transfer event with the verification of what the balances are? Please feel free to go into depths
If I had used another word, like Foobar and replaced the word Transfer with it, would the code still work? The reason I ask is because it seems like I am defining what Transfer is doing by declaring it (so by default it not being a predefined event of solidity), but I don't seem to be coding in much else.

References:

What is an Event?
http://solidity.readthedocs.io/en/v0.4.21/contracts.html#events


texts: Least Technical description of an ICO and how it is useful(monetarily)

texts:
I need to convince my boss ( completely not technical, I don't know how that happened ) that an ICO is a good way of generating revenue.

I've been trying to compare it to an IPO but I know too little about this to make any sort of authoritative comment about which is better.

Ignore the possibility of it being treated as a security.


texts:
node version v12.8.0,npm version 6.10.2

I followed the below steps to install the ganache GUI but I got the error

$mkdir ~/ganache
$git clone https://github.com/trufflesuite/ganache.git
$npm install
$npm start

error:

  ganache@2.1.1-beta.0 start /home/nithin/ganache
  electron-forge start

✔ Checking your system
✔ Locating Application

An unhandled rejection has occurred inside Forge:
Could not determine Electron version. Make sure that 'npm install' (or 'yarn') has been run before invoking electron-forge.
Error: Could not determine Electron version. Make sure that 'npm install' (or 'yarn') has been run before invoking electron-forge.
at /usr/lib/node_modules/electron-forge/dist/util/rebuild.js:26:13
at Generator.next (<anonymous>)
at Generator.tryCatcher (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/util.js:16:23)
at PromiseSpawn._promiseFulfilled (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/generators.js:97:49)
at /usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/generators.js:201:15
at /usr/lib/node_modules/electron-forge/dist/util/rebuild.js:63:17
at /usr/lib/node_modules/electron-forge/dist/api/start.js:105:33
at Generator.next (<anonymous>)
at Generator.tryCatcher (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/util.js:16:23)
at PromiseSpawn._promiseFulfilled (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/generators.js:97:49)
at Promise._settlePromise (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/promise.js:579:26)
at Promise._settlePromise0 (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/promise.js:619:10)
at Promise._settlePromises (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/promise.js:699:18)
at _drainQueueStep (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/usr/lib/node_modules/electron-forge/node_modules/bluebird/js/release/async.js:147:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ganache@2.1.1-beta.0 start: `electron-forge start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ganache@2.1.1-beta.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/nithin/.npm/_logs/2019-08-14T11_24_08_546


texts: ERC20 - Approve & TransferFrom not working

texts:
The getTokenBalance function seems to retrieve data from the ERC20 contract just fine so I don't think there is an issue with how I'm using the interface. Additionally, I also tested out separating the Approve and TransferFrom calls into two separate functions. The approve function worked, however, the TransferFrom function did not.

The Error that is given is "Gas estimation errored with the following message (see below). The transaction execution will likely fail."

pragma solidity >=0.4.22 <0.6.0;

contract ERC20 {
    function totalSupply() public view returns (uint);
    function balanceOf(address tokenOwner) public view returns (uint balance);
    function allowance(address tokenOwner, address spender) public view returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);
    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

contract Escrow {

    address token;

    constructor(address tokenAddress) public {
        token = tokenAddress;
    }

    function getTokenBalance(address user) public view returns (uint) {
        return ERC20(token).balanceOf(user);
    }

    function deposit(uint amnt) public {
        // transfer the tokens from the sender to this contract
        ERC20(token).approve(address(this), amnt);
        ERC20(token).transferFrom(msg.sender, address(this), amnt);
    }

}


texts:
When I use contractInstance.getDrawStats or any other method it returns error method is not a function because of contractInstance doesn't contain any contract methods. However, they are definitely in ABI.

I'm using Metamask as web3 provider

There is my contract api

const factoryAddress = "0x36a3ce90ba3e96859eca2e77af280fe2fdbd4765";

const factoryABI = require("./api/Factory.json");

let factory;

let factoryContract;

window.App = {
    init: function() {
        web3 = new Web3(web3.currentProvider);
        factory = web3.eth.contract(factoryABI).at(factoryAddress);
        console.log('Complete');
    },

    createLottery: function(drawsAmount) {
        factory.createLottery(drawsAmount, (error, result) => {console.log(result)});
    }
};

window.addEventListener('load', function() {
    if (typeof web3 !== 'undefined') {
        console.log("MetaMask detected")
        web3 = new Web3(web3.currentProvider);
        App.init();
    } else {
        console.warn("MetaMask not found")
    }
});

Thanks


texts: Ethereum code to split money in half and store half in the contract and send the other half to an address

texts:
I am trying to create a ethereum smart contract that splits the money in half and send half the money to a contract and sends the other half to a address. Below is the code I have. I would much appreciate your help!

pragma solidity ^0.4.24;

contract Forwarder {
  address admin;
  uint fee = 10;

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

  function splitFunds(address _b) public payable {
    admin.transfer(msg.value * fee / 100);
    _b.transfer(msg.value - (msg.value * fee / 100));
  }
}


texts: What does the Web3 "BigNumber not a base 16 number Error" mean

texts:
Is there a known problem with parsing events containing strings in Truffle/Web3?

I'm using truffle with the following simple contract

contract Board
{
    string  foo;
    event Shout();
    event TextEvent(
        string  indexed text,
        uint timestamp
    );

    function shout(string _text)
    {
        foo=_text;
        Shout();
        TextEvent(_text,now);
    }

    function getFoo() returns(string){
        return foo;
    }
}

When I call shout(_) foo is set correctly and a Shout event is triggered and I can listen to this without any problems.

  var board = Board.deployed();
  var shouts=board.Shout();
  shouts.watch(function(error, result){
    if (!error)
      console.log("shout",result);
  });

However when I watch for TextEvents with the following code

    var board = Board.deployed();
    var textEvent=board.TextEvent();
    textEvent.watch(function(error, result){
        console.log("callback");
        if (!error) console.log("shout",result);
    });

I get the following error which seems to be related to converting bytes32 into a string:

Uncaught BigNumber Error: new BigNumber() not a base 16 number:

So the question is how can you listen to events containing strings in Web3 without running into this error?


texts: delegatecall on library always run out of gas

texts:
I'm trying to replicate the Dynamic Library attack of this paper under a recent version of solidity and the EVM.

Streamlining down the code, I've created this very simple contract (which is, in essence, an address container for a library:

contract DynamicContract {
    address dynLib;

    function updateLib(address _lib) public {
        dynLib = _lib;
    }

    function getLibAddress() public view returns(address) {
        return dynLib;
    }
}

Now, the attacker deploys DynamicContract and update the library address with an instante of the following MaliciousLibrary:

library MaliciousLibrary {
    function version() public returns(uint256) {
        address attacker = address(0x72...);

        attacker.transfer(0.1 ether);

        return 1;
    }
}

Now, the victim deploys the 'Bob' contract, equipping it with some ether:

contract Bob {
    event Result(bool res);

    function queryVersion(address dynCAddr) public payable returns(bool) {
        DynamicContract dC = DynamicContract(dynCAddr);

        bool res = dC.getLibAddress()
                     .delegatecall
                     .gas(30000000)(bytes4(keccak256("version()")));

        return res;
    }
}

Now, if the victims calls queryVersion(), the malicious version() method should transfer 0.1 to the attacker. However, this doesn't happen and the transaction runs out of gas.

Any ideas?


texts:
Trying to match "golang.org/x/crypto/sha3" lib
with solidity sha3() is giving me a hard time.
Its been discussed in here, but I somehow cant apply it in go.
How do I handle a big.Int type s.t i get   solidity.sha3(uint256(1))==golang.sha3.Sum256(convertMyBigInt(myBigInt)) ?

I turn the bigInt into a hex byte array, then fill up the left site with zeros, hash and then output.

//create a big int for test and set to 1
b1 := new(big.Int)
b1.SetInt64(1)
//create empty array with 32 bytes for padding
empty := make([]byte,32)
//turn the big int into a hex string (let me know if there is a more
      //elegant way^^)
String := bytes.NewBufferString(b1.Text(16))
copy(empty[len(empty)-len(String.Bytes()):],String.Bytes())
//output of empty : [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49]
res:= new(big.Int)
temp:=sha3.Sum256(empty)
res.SetBytes(temp[:])
fmt.Println("\nresult ",res.Text(16))

output: 26502030f0954243c70cb7fa68e0752ce2bf99aabfc0219d5184635d4c61dbd8

solidity gives me:

sha3(uint(1))
b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6

can someone give me a short example how to match solidity sha3 with golang sha3 in an elegant manner? I'd be very thankful!


texts: Chainlink node not initializing, failed to initialize ORM: initializeORM#NewORM: unable to init DB: unable to open postgresql

texts:
I am trying to setup a chainlink node on my machine. After setting all the .env variables, I am running the docker command to start the node,
cd ~/.chainlink-kovan && docker run -p 6688:6688 -v ~/.chainlink-kovan:/chainlink -it --env-file=.env smartcontract/chainlink:0.10.3 local n

but I am getting this error:
pam@g3:~/.chainlink-kovan$ cd ~/.chainlink-kovan && docker run -p 6688:6688 -v ~/.chainlink-kovan:/chainlink -it --env-file=.env smartcontract/chainlink:0.10.3 local n
2021-04-07T09:36:21Z [INFO]  Starting Chainlink Node 0.10.3 at commit 5dbbc21f13fa00ee724c439273156834c45ab93e cmd/local_client.go:56  InstanceUUID=f51952e7-d4c9-45f5-b0ae-6e1ed5617bbb SHA=5dbbc21f13fa00ee724c439273156834c45ab93e Version=0.10.3 id=boot
2021-04-07T09:36:21Z [ERROR] failed to initialize database, got error failed to connect to `host=localhost user=postgres database=postgres`: dial error (dial tcp [::1]:5432: connect: cannot assign requested address) orm/orm.go:82           stacktrace=github.com/smartcontractkit/chainlink/core/store/orm.NewORM
        /chainlink/core/store/orm/orm.go:82
github.com/smartcontractkit/chainlink/core/store.initializeORM
        /chainlink/core/store/store.go:250
github.com/smartcontractkit/chainlink/core/store.newStoreWithKeyStore
        /chainlink/core/store/store.go:87
github.com/smartcontractkit/chainlink/core/store.NewStore
        /chainlink/core/store/store.go:66
github.com/smartcontractkit/chainlink/core/services/chainlink.NewApplication
        /chainlink/core/services/chainlink/application.go:135
github.com/smartcontractkit/chainlink/core/cmd.ChainlinkAppFactory.NewApplication
        /chainlink/core/cmd/client.go:85
github.com/smartcontractkit/chainlink/core/cmd.(*Client).RunNode
        /chainlink/core/cmd/local_client.go:58
github.com/urfave/cli.HandleAction
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/app.go:524
github.com/urfave/cli.Command.Run
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/command.go:173
github.com/urfave/cli.(*App).RunAsSubcommand
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/app.go:405
github.com/urfave/cli.Command.startApp
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/command.go:372
github.com/urfave/cli.Command.Run
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/command.go:102
github.com/urfave/cli.(*App).Run
        /go/pkg/mod/github.com/urfave/cli@v1.22.5/app.go:277
main.Run
        /chainlink/core/main.go:20
main.main
        /chainlink/core/main.go:14
runtime.main
        /usr/local/go/src/runtime/proc.go:204
creating application: failed to initialize ORM: initializeORM#NewORM: unable to init DB: unable to open postgresql://postgres:12345678@localhost:5432/postgres?application_name=Chainlink+0.10.3+%7C+ORM+%7C+f51952e7-d4c9-45f5-b0ae-6e1ed5617bbb for gorm DB: failed to connect to `host=localhost user=postgres database=postgres`: dial error (dial tcp [::1]:5432: connect: cannot assign requested address)

I thought this error is coming from postgres, so I tried to connect to postgres through nodejs, which worked.
const { Client } = require("pg");

const client = new Client({
  user: "postgres",
  host: "localhost",
  database: "postgres",
  password: "12345678",
  port: 5432,
});

async function main() {
  await client.connect();
  console.log("Connection Successful.");

  return process.exit(0);
}
main();


texts: TruffleConsole: Not able to send Ether to an account using Smart Contract’s method

texts:
I have got a smart contract (SC) which is using transfer to send Ether. The transaction is happening but the balance of the account is not increasing.
pragma solidity ^0.5.1;
   contract TransferTest{
      uint8  public testVal =97;
      function testFunc(address payable addr) public returns (uint8){
         addr.transfer(testVal);
         return testVal;
      }
}

I am using accounts[2]. Truffle console is showing the transaction of calling the testFunc() but the balance of SC and the accounts[2] i.e. acc2 is not changing:
truffle(development)>TC = await TransferTest.at(addr)
truffle(development)> balance = await web3.eth.getBalance(TC.address)
undefined
truffle(development)> web3.utils.fromWei(balance, "ether")
'193.999999999999999903'
truffle(development)> acc2 = accounts[2]
'0x20642D4d868da20f5268b0Be7d52fD26FcD9940d'
truffle(development)> b2 = await web3.eth.getBalance(acc2)
undefined
truffle(development)> web3.utils.fromWei(b2, "ether")
'100.000000000000000097'
truffle(development)> await TC.testFunc(acc2)
{ tx:
   '0xb751de0c31147d2baf2330c50c62c70facacf3e35e201061c12260bda601e4df',
  receipt:
truffle(development)> b2 = await web3.eth.getBalance(acc2)
undefined
truffle(development)> web3.utils.fromWei(b2, "ether")
'100.000000000000000194'

Somebody please guide me.
Zulfi.


texts:
have a standard factory pattern for my contract and I am trying to get it up and running using Truffle Migrations.
In my factory truffle migration script I have
await deployer.deploy(ContractFactory);

This deploys the factory contract just fine but I am a bit unsure what the standard way of migrating the child contract is.
Do I also need to have a migration file for the child and run the child's own deployment?
Or am I just supposed to deploy the factory on its own and then the factory's createNewChildContract function handle the migration for me?
function createNewChildContract() public {
    ChildContract childContract = new ChildContract(uint256 _amount);
    childContracts.push(childContract);
}

Thank You


texts: Using uint for bitwise flags in Solidity

texts:
I want to set up 64 boolean flags in a contract.  What's the better option here?

a) bool[64]

b) uint64

And is there way to name each flag in Solidity like:

#define BIT_0 0


texts: How to use enums for conditions on constructor?

texts:
I am learning to code with solidity. need help to solve this

I have a membership system where users can have basic, gold, diamond membership types.
Users can use coupons every 5 minutes and for basic it is allowed once, for gold 2, for diamond 3.

But issue is this membership is attached to user token balance of some other contract.

For this I already have function to get balance like this

function getERC20Balance(address _address) view public returns (uint) {
    return ERC20Interface(tokenAddress).balanceOf(_address);
}

Now balance is in getERC20Balance()

In constructor I have made this which is definitely for basic membership

constructor { allowedNumberOfTimes = 1; }

But what i want to do is make this dynamic, so if user has balace mroe than 500 then he is in second membership status, and if 1000 then in third, so contract should dynamically set allowedNumberOfTimes = 1 or 2 or 3 depending on membership type

Made this enum also

 enum types["basic","gold","diamond"];
 types type;
 typess constant defaulttype = types.basic;

Now stuck here and need help to make either loop in constructor or some better way to check balance on contract start and assign the appropriate membership automatically in form of allowedNumberOfTimes.


texts: Testrpc transactions are failing. How do I perform a transaction when Mist cannot estimate gas?

texts:
I am attempting to perform transactions and create contracts using EthereumJS Testrpc. I set it up by running the following:

Terminal 1: testrpc

Terminal 2: mist --rpc localhost:8545

Running both of these seem to work, and Mist opens. Everything appears like it is working, but when I go to send a transaction, I get the following:

Mist connects to no peers when I open it this way. Does this have something to do with it?


texts: moving data from a smart contract to a local drive

texts:
is it possible to copy data from smart contract to a local drive??
 ie, suppose I created a smart contract and i wish to copy the available data at the storage to my local drive... Is there any possible way to accomplish this?


texts: How do you compile a contract that uses Open Zeppelin's Standard Token in Truffle?

texts:
Compiling is failing.

vi contracts/MyCoin.sol:

pragma solidity ^0.4.18;

import 'zeppelin-solidity/contracts/token/ERC20/StandardToken.sol';

contract MyCoin is StandardToken {
  string public name = "MyCoin";
  string public symbol = "MC";
  uint public decimals = 2;
  uint public INITIAL_SUPPLY = 10000 * (10 ** decimals);

  function MyCoin() public {
    totalSupply = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
  }
}

When I run truffle compile:

➜  my-coin truffle compile
Compiling ./contracts/MyCoin.sol...
Compiling zeppelin-solidity/contracts/math/SafeMath.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/BasicToken.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/ERC20.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol...
Compiling zeppelin-solidity/contracts/token/ERC20/StandardToken.sol...

/Users/pedro/src/my-coin/contracts/MyCoin.sol:13:5: TypeError: No matching declaration found after variable lookup.
    totalSupply = INITIAL_SUPPLY;
    ^---------^
Compilation failed. See above.


texts: Why does geth -light start importing block headers from 3297471

texts:
I've been using geth to download the blockchain (on full) and one of the requirements for my research involves the use of light clients. I used 2 computers to download the blockchain on the -light argument and both computers (one clean and another with an existing chain) start downloading headers from block 3297471.

Is there any explanation on why geth downloads from this block and not from 0? (screenshot of geth -light running attached)


texts: What is delegated proof of stake and why is it not suitable for Ethereum?

texts:
Ethereum will switch to Proof Of Stake in some future hard fork called Serenity. For this putpose a new Proof Of Stake protocol called Casper is being developed.[1]

However, there are quite a few cryptocurrencies out there that already use proof of stake, most of them a version called Delegated Proof Of Stake, some of them even adding a version to show how progressive they are (DPOS 2.0, DPOS 3.0).

What are key features of this Delegated Proof Of Stake as compared to current state of Casper and why is it not sufficient for Ethereum according to the Ethereum Foundation guys? Is it even secure enough in existing implementations?


texts: How to access web3Instance when using Truffle's Drizzle

texts:
I'm working on a dapp with the boilerplate created by running truffle unbox drizzle and need to call functions provided by the web3 instance.

Is there a way to access the web3 instance object? All we get from drizzle's store is the state.web3.status string.

Failed Attempt

There is /src/util/web3/web3Reducer.js and /src/util/web3/getWeb3.js but they both appear not to be in use. I tried adding web3Reducer to combineReducers but always get null for the web3Instance.

import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import { drizzleReducers } from 'drizzle'
import web3Reducer from './util/web3/web3Reducer'

const reducer = combineReducers({
  routing: routerReducer,
  web3Instance: web3Reducer,
  ...drizzleReducers,
})

export default reducer


texts:
contract Example {
  address[] addresses;

  function getAddress(uint index) external view returns (address){
      return addresses[index];
  }

  function getAddress1(uint index) external view returns (address) {
      require(index < addresses.length);
      return addresses[index];
  }
 }

Both the function will fail if I will try accessing an element which doesn't exist.

Is there a difference in the 2 functions?
In general should I prefer require to verify all the conditions or let the function fail like getAddress?


texts: How secured are private data stored on blockchain?

texts:
I'm quite new in Ethereum world and I'm still little bit confused about this:
If I store any data on blockchain, is it readable from anyone? Let's say I have this is Solidity:

...
string private myVerySecretText;

function getText() external returns(string){
 require(msg.sender == something);
 return myVerySecretText;
}
...

If I'm the user that match the require statement, I can access the data, but is there some possiblity to read this data from anyone else? I know that the whole blockchain is public, so is there possible to read somehow even the private data? And can anyone read the code from my smartcontract when is deployed on a blockchain?


texts: How to check the latest possible state number of Geth

texts:
Good day for everyone.
We are using geth with fast synch for own node on AWS t2.large with
ssd volume.
And it synching continuously, having 100 blocks behind current
and states growing.
I know this is old question and geth will not be in synch untill all
states loaded.
For now eth.syncing outputs:
{
 currentBlock: 12476357,
 highestBlock: 12476443,
 knownStates: 808119241,
 pulledStates: 808061533,
 startingBlock: 12451471
}

And we would like to know what time it needs to be in synch.
Does anybody know what is approximate number of Ethereum states for
nowadays?


texts: How to use a date time from an API to prevent contract interactions if the date is a string?

texts:
I want an to use an oracle to prevent contract interaction after certain time cutoffs

This is the APIs format:

"event":"event2","timezone":"UTC+1","datetime":"2018-06-07 01:00:00"

I think doing all of the calculation in the contract would be very expensive to convert to unix time/bytes and is seems complicated with timezones.

I cannot change the API (not my API), I would prefer to not build my own API.

Does anyone have any thoughts on how to handle this?


texts: Web3: How do I get just the first account on testrpc using web3.eth.getAccounts()?

texts:
When I run this code in web3

web3.eth.getAccounts().then(e => console.log(e));

The console returns this:

 [ '0x772f437b0f15e1F205C8BD923b5C8357e9c0c429',
    '0x5738d9100A6CB64FB78730746ab61472c7808fD9',
    '0x7086D052EAaD359c7aCD9B993c6169aE0dEC0725',
    '0x9fA18751b024FDC55cC85A484fF4261351Dd4666',
    '0x95a29de4A8cc4697E627922d270Aa74C2bd7494a',
    '0x332c22e9c7F02e092b18C6cc4D9Bfd46d36Dd7D9',
    '0xaED2F48c0d06a13D1FE2853E7Ee3B7d0aA328d3B',
    '0x88A0941f0dcb501C20b7BaE5a41608EB981f1209',
    '0xad5d1cB78e80518b596A814340826F36B89660Fc',
    '0x67E23e936C9d22eDCf9ebC9A989911b313c24BC1' ]

But what if I only want the first account in the array and assign it to a variable?

In this case, it's 0x772f437b0f15e1F205C8BD923b5C8357e9c0c429

EDIT:

I have got the correct output after following the instruction of István András Seres, below is my code:

var firstAccount;

web3.eth.getAccounts().then(e => {
 firstAccount = e[0];
 console.log("A: " + firstAccount);
})

console.log("B: " + firstAccount);

Strangely, the output is:

A: [correct testrpc account]

B: undefined

It seems that a variable is not allowed to carry the same value once it exits getAccounts() function.


texts: Nested Mapping not returning correct results

texts:
I was trying to build a nested map of structs in SmartContract. With a single level, after inserting data(insertData) the validate method is returning correct results with the below code containing few commented lines. But when i uncomment the childMap related things -the childMap in the ParentStruct, the parameters in insertData method and initialising the childMap then its returning wrong result. Please find the smart contract code below.

pragma solidity ^0.4.13;

contract SampleContract {
struct ChildStruct {
    bool isPresent;
    bytes32 name;
}

struct ParentStruct {
    bool isPresent;
    bytes32 name;
    //mapping (bytes32 => ChildStruct) childMap;
}

mapping(bytes32 => ParentStruct) sampleStructs;

function insertData(bytes32 parentAddress, bytes32 parentName
                       //,bytes32 childAddress, bytes32 childName
                       )
public returns(bool success)
{
    ParentStruct storage c = sampleStructs[parentAddress];
    c.isPresent = true;
    c.name = parentName;
    //c.childMap[childAddress] = ChildStruct(true, childName);
    return true;
}

function validate(bytes32 parentAddress)
public returns(bool isPresent, string name)
{
    return
    (sampleStructs[parentAddress].isPresent,
    bytes32ToString(sampleStructs[parentAddress].name)
    );
}

function bytes32ToString(bytes32 x) constant returns (string)
{
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
        byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
        if (char != 0) {
            bytesString[charCount] = char;
            charCount++;
        }
    }
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
        bytesStringTrimmed[j] = bytesString[j];
    }
    return string(bytesStringTrimmed);
}
}

Could you please help me if i'm missing anything ?


texts: I see many warnings against the use of now (block.timestamp) in solidity code but no one mentions any alternative of getting the time. What is the alternative of using now?


texts:
I am facing some issue in the installation of truffle. I used the command

 sudo npm install -g truffle
 /Users/vikas/.nvm/versions/node/v9.11.2/bin/truffle ->
 /Users/vikas/.nvm/versions/node/v9.11.2/lib/node_modules/truffle/build/cli.bundled.js
 truffle@4.1.13 added 81 packages in 14.406

Successfully added the packages but when I run command truffle version

or any another truffle command it gives

 -bash: /usr/local/bin/truffle: No such file or directory.

I am using macOS please someone help me out.


texts: Solidity/Truffle - Suddenly getting TypeError on Migration file

texts:
Suddenly getting an error when doing a truffle compile --reset - even though I didn't make any code changes on my Migrations.sol file.

TypeError: Name has to refer to a struct, enum or contract.
    Migrations upgraded = Migrations(new_address);

I mean I get that the contract's name is Migrations, but this was always the case. Why is this suddenly happening now is what I'd like to know. And how do you fix it?

Its especially weird given that this Migrations.sol file wasn't even written by me, as its automatically provided when you create a new project.

(Would this have anything to do with the new version of Truffle - meaning 5.0.2?)


texts: Is a smart contract analogous to an OOP class?

texts:
Can I think of a smart contract as being analogous to a Class in an object-oriented programming language (e.g., Java)?

Each transaction that uses the contract essentially instantiates an object of the contract (or class), and then that object (i.e., transaction) maintains its own properties like private and public variables, as well as inherits properties from other locations.

Is this analogy correct?


texts: I want to create a Dapp, but I'm not a programmer

texts:
I'm 52 and used to program in 'Basic' growing up. That and basic html is pretty much all the experience that I have. I have a few questions and would immensely appreciate your advice.

What do I need to learn and in what order?
If I build a Dapp, I understand that I do not need a website, but than how would my Dapp be found?
How does the blokchain know that I own the Dapp and how does making changes to it work if the Dapp is already on the blockchain?
Would it be easier to build a website and then convert it?

These are just a few of the questions I have, but I'm certain that if can get some answers to the above, a lot of other questions would be answered.

Thank you again for your time.


texts: What is so innovative about smart contracts?

texts: I still don't quite understand what is so innovative about smart contracts because it sounds like a general conditional statement to me.  Is it merely about automating contracts with computer programs or am I missing something?


texts: How to add original account (address) to new mining rig

texts:
I think I have some basic misunderstanding of how this all works.

I setup a mining rig on one pc, and created an address.

Say I get another mining rig. I do not want to create a new address, I want to use the old one.

So then I will have two systems mining into one account.

How do I attach the original address to a new pc?

Thanks!


texts:
Question: Is it possible to upload tokens on a contract and then distribute it to whoever sends ETH to that contract (not create a token as if it is an ICO, but preload already existing one). For e.g. 10 token x for 1eth?

Also is this the way decentralised exchanges works?

Thanks


texts: geth in private network throws Out of memory even after using 8 GB RAM + 100 GB swapfile

texts:
I am testing a private network for last few weeks. The block height has reached around 2,81,000 and now suddenly the memory usage of my server instance has shooted up TOO High and the geth process gets killed immediately after the 8GB memory is exhausted.

To resolve this I created a 100GB swapfile on the server and all the memory was exhausted and then again the process was killed, saying "out of memory".

Once I start geth (private chain with network id xxxxx), even when mining is stopped the memory usage starts to grow at 100mb/sec eating up all the RAM and the Swapfile

UPDATE

After researching for around 12 hours, An important thing is detected that  it occurs only when I open the rpc port 8546, If start geth on any other rpc port, geth is satisfied with approx 550 MB RAM.

IS IT A DoS Attack?


texts:
So commonly used snippet for safeMath in solidity is the following:
https://github.com/OpenZeppelin/openzeppelin-solidity/blob/64c324e37c17c5e0501bb746975040d1ae020806/contracts/math/SafeMath.sol

pragma solidity ^0.4.24;

/**
 * @title SafeMath
 * @dev Math operations with safety checks that revert on error
 */
library SafeMath {

  /**
  * @dev Multiplies two numbers, reverts on overflow.
  */
  function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
    // benefit is lost if 'b' is also tested.
    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
    if (_a == 0) {
      return 0;
    }

    uint256 c = _a * _b;
    require(c / _a == _b);

    return c;
  }

  /**
  * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
  */
  function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
    require(_b > 0); // Solidity only automatically asserts when dividing by 0
    uint256 c = _a / _b;
    // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold

    return c;
  }

  /**
  * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
  */
  function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
    require(_b <= _a);
    uint256 c = _a - _b;

    return c;
  }

  /**
  * @dev Adds two numbers, reverts on overflow.
  */
  function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
    uint256 c = _a + _b;
    require(c >= _a);

    return c;
  }

  /**
  * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
  * reverts when dividing by zero.
  */
  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
    require(b != 0);
    return a % b;
  }
}

If I want to use the same approach for uint64, can I just find & replace uint256 with uint64?


texts: Populus cannot deploy contract related to estimated gas is not enough error

texts:
I am using populus.

Platform darwin -- Python 2.7.12, pytest-3.0.2, py-1.4.31,
pluggy-0.3.1
Plugins: populus-1.1.0
OS: Mac OS X

I do face with following error: for the following line on my test.py file.

my_contract       = unmigrated_chain.get_contract('Array');

In order to deploy my contract there is not enough gas.

    def test_token_contract_1(web3, accounts, unmigrated_chain):
>   my_contract       = unmigrated_chain.get_contract('Array');

    tests/test.py:7:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python2.7/site-packages/populus/chain.py:614: in get_contract
    kwargs=deploy_kwargs,
/usr/local/lib/python2.7/site-packages/web3/contract.py:194: in deploy
    txn_hash = cls.web3.eth.sendTransaction(deploy_transaction)
/usr/local/lib/python2.7/site-packages/web3/eth.py:216: in sendTransaction
    transaction=formatted_transaction,
/usr/local/lib/python2.7/site-packages/web3/utils/transactions.py:25: in get_buffered_gas_estimate
    gas_estimate = web3.eth.estimateGas(gas_estimate_transaction)
/usr/local/lib/python2.7/site-packages/web3/utils/functional.py:22: in inner
    value = fn(*args, **kwargs)
/usr/local/lib/python2.7/site-packages/web3/eth.py:247: in estimateGas
    return self.request_manager.request_blocking("eth_estimateGas", [transaction])

For example when I remove a line from my contract my code works perfectly fine. But when I add a new line that does some computation, which leads my contract to exceed the estimated gas and gives the error I mentioned.

[Q] Due to out of gas problem I can't deploy my contract inside Populus. How can I over come this problem?

Please note that I was not able to do import my library .sol file in my contract file so one library and additional three contract is embedded into the same Array.sol file.

Thank you for your valuable time and help.


texts: How to calculate the amount to transfer to completely empty an account?

texts:
So let's say my wallet is 1 eth, I need to completely empty it and I'm going to do it this way

Var value = web3.toWei(1) - gas

Is that right?


texts: It is secure do accounts just with web3.eth.accounts.create() ? (entropy)

texts:
const Web3 = require('web3');

let url = 'infuralink';
let web3 = new Web3(url);
console.log(web3.eth.accounts.create());

This is the code of many tutorials for do a key pair.
it is completely secure or do I need to pass a parameter to have enough entropy?


texts: How can we convert a dynamic value stored in uint to wei in the contract?

texts:
I have to perform something like this:

uint r = a wei;

Which displays an error, however:

uint r = 1 wei;

Doesn't throw an error.

How can I dynamically change the value of uint to wei in the contract itself?


texts: Can block.timestamp value change during execution?

texts:
I'm facing a doubt while developing an Smart Contract.
I was getting current date from block.timestamp several times inside a function.
Could this value change during an Smart Contract execution?
Or the Smart Contracts are executed in the same block, so block.timestamp, block.number... have always the same value, during the execution?
Obviously, if not, solution is simple. Getting block.timestamp in a variable value on init, and use the variable value during the execution.
uint foo = block.timestamp;


texts: Size of Ethereum transaction and its signature component?

texts:
A couple of questions:

What is the average size of an Ethereum transaction in bytes (considering say a basic value transfer case).

Also, what is the size in bytes of the signature component of the transaction?


texts: How can the transaction status from a thrown error be detected when gas can be exactly the same as the gasUsed for a successful transaction?

texts:
This question arose from answering Transaction Status.

In the following example, I am sending gas of 21,000 (the amount required for a regular transaction). In this situation gas == gasUsed, and so cannot be used to determine if the contract has thrown an exception?

> eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(1.2345, "ether"), gas: 21000})
"0xc7c63b67747c0c825229ce3d36d226423adb8cab6bebe12b6d5001e0dc3f79b3"
> eth.getTransaction("0xc7c63b67747c0c825229ce3d36d226423adb8cab6bebe12b6d5001e0dc3f79b3")
{
  blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  blockNumber: null,
  from: "0xa7857047907d53a2e494d5f311b4b586dc6a96d2",
  gas: 21000,
  gasPrice: 20000000000,
  hash: "0xc7c63b67747c0c825229ce3d36d226423adb8cab6bebe12b6d5001e0dc3f79b3",
  input: "0x",
  nonce: 55,
  to: "0x4d5bbe7fbc80933ffa90ece988a764e41ee6d018",
  transactionIndex: null,
  value: 1234500000000000000
}
> eth.getTransactionReceipt("0xc7c63b67747c0c825229ce3d36d226423adb8cab6bebe12b6d5001e0dc3f79b3")
{
  blockHash: "0xf0af8236ceec7ad1839d67c9934ab062a8d95fa1f88b06139f97dbdfbd1cd842",
  blockNumber: 2234,
  contractAddress: null,
  cumulativeGasUsed: 21000,
  from: "0xa7857047907d53a2e494d5f311b4b586dc6a96d2",
  gasUsed: 21000,
  logs: [],
  root: "3280f47a0de1149ad5c5fda421faaf95f303da8a77e83c8ec6ac2b3d8ca27abc",
  to: "0x4d5bbe7fbc80933ffa90ece988a764e41ee6d018",
  transactionHash: "0xc7c63b67747c0c825229ce3d36d226423adb8cab6bebe12b6d5001e0dc3f79b3",
  transactionIndex: 0
}

A transaction can be set with the gas being exactly the same as the gas that will be used, using web3.eth.estimateGas function to firstly estimate the required gas.

So, how can the transaction status from a thrown error be detected when gas can be exactly the same as the gasUsed for a successful transaction?

EDIT 15/06/2016 - Explaining differences from How do I know when I've run out of gas programmatically?

In this question, we already KNOW how to detect that we have run out of gas programmatically. And we already know that this method to detect an error transaction is not reliable, as gas == gasUsed is a valid condition for a non-error transaction.

What this question is asking is what reliable alternatives are there to detect an error transaction when the "run out of gas" situation is not reliable?


texts: What layers of a Dapp can be written in a regular high level language vs a niche one like Solidity?

texts:
I just saw that the Minds social network (a ethereum dapp I believe) is written in PHP.  Their codebase is huge and I'm having trouble finding where their Smart contracts are written/how they are actually storing information in the Blockchain.

I also always see stuff on the web saying you build dapps in Solidity.

What layers of a dapp can be written in a regular high level language vs a niche Smart contract language like Solidity?


texts:
I've created a BEP20 token and I can't figure out some steps, I've created for about 21000000 total supply of token and why should I mint token after creating it?

How much should I mint? How minted tokens are different from not minted ones?


texts: Geth JSON-RPC only returns 0, null or error

texts:
I've set up a docker env based upon Ubuntu for working with Geth (for now on Testnet) and Geth's JSON-RPC, however every call I make to the JSON-RPC fails in either 0, null or an error because the method would not exist. Some calls (accounts, gas price) do work on the 'regular' net.

I've set up Geth on the Rinkeby Testnet with the following line:
geth --rinkeby --rpc --rpcaddr "127.0.0.1" --rpcport "8000"

Here are some examples of what I'm getting back; tried it with both localhost and 127.0.0.1. All in curl, put into the container's own CLI.

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id":1}' http://localhost:8000
{"jsonrpc":"2.0","id":1,"result":null}

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getCompilers","params":[],"id":1}' http://localhost:8000
{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"The method eth_getCompilers does not exist/is not available"}}

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":2}' http://localhost:8000
{"jsonrpc":"2.0","id":2,"result":[]}

For the last example, to prove there are accounts:

 geth account list
 Account #0: {678decf23eb929b88d7a55c272b73aa6e1d0d4bc} keystore:///root/.ethereum/keystore/UTC--2017-10-03T12-56-37.565267100Z--678decf23eb929b88d7a55c272b73aa6e1d0d4bc

If someone could help me out, and tell me what the cause could be that'd be great.


texts:
Recently I've setup a private chain on cloud (to be more accurate, it is a separate public chain), after a few days, I found that there are some strange transactions sending ether to the same account every second. I've re-setup the instance several times, but it keeps occur.

Is it under attack? How can I secure the chain? Would it related to the RPC setting?


texts: Does Etherwallet sends transactions without a sync blockchain

texts: So Etherwallet (https://github.com/kvhnuke/etherwallet) is a wallet which runs on the browser, how is it possible to send transactions without download the entire copy of the blockchain ? or Etherwallet have some background service to validate the transactions ?


texts:
According to this post, every Ethereum wallet has a number called network id.

Does every transaction have this network id?

If not, then it should be possible to replay transaction on multiple networks, isn't it?


texts: Which is the best (most H/s) open source NVidia driver for Linux (any distro)

texts:
I have tested my GTX 860M on Arch Linux with two diffrent drivers, but the diffrence is insignifiant (<0.3 MH/s). Is there a specific combo of NVidia driver + Linux Distro that gets most out of a video card?

Using ethminer, with CUDA, getting ~4.x MH/s.


texts: Is it possible to deploy smart contract source code using remix?

texts:
I use remix ide.

I want the source code of my contact to be published and visible in Etherscan.
I do next things:

Write some sample Smart Contract
Open "Compile" tab, check that there are no errors
Open "Run" tab -> Press Create Button, confirm metamask transaction
Wait for contract to be deployed copy address of just created contract
Open this contract in Etherscan

At the last step, I faced the problem I can see only "Transaction" and "Contract Code" tabs. Like here.

But I want to see "Contract Source" Tab, like here.

Is that possible with the remix? how to achieve that?


texts: Get history of transactions to specific account (EthereumJ)

texts: How to get all the transactions which were received by some specific account (not necessary owned by me)? I need something like the list provided by the Etherscan.


texts: Different gas usage of trivial reverting contract function

texts:
We are currently testing functions on Ropsten test network and have an issue regarding the gas usage. Our functions sometimes use 12 gas more and we can not fathom why that would be the case. To test this we defined a function

    function refund (bytes32 sessionId) public {
            require (false);
            ...
}

It fails after the first line and reverts the transaction.
We called it 30 times with different byte32 values approx. every 3min.
Here are two transactions to this function with different gas usage:

https://ropsten.etherscan.io/tx/0xa48c4f09da3a8d57fc4061ecad27a3097c225ad3e524e81948e6d38461e41b1f
https://ropsten.etherscan.io/tx/0x3126bdcdb6c5fd569a85a9c95928b1fd8c856ded7047670064f0d4e965199fe8

The only difference there seems to be the nonce(duh), the block index position and a different 32 bytes long input (that is not used). Is there some calculation for the used gas that we are missing?

EDIT:

Tested with an even simpler contract on goerli.

pragma solidity ^0.5;

contract FairDataExchange {
    function refund(bytes32 t) public{
    }
}

Issue is the same here. Without parameter t this issue does not seem to come up (n=45).

Transactions on goerli:

1.
https://goerli.etherscan.io/tx/0xd48b8ad613145af060489082507253786e6211fd34dfbe641c10f5e03b82f3d8

2.
https://goerli.etherscan.io/tx/0x434a546e43f2e2bfc5bf509f67fd8543506e9223b0d52fa41213063ca90595b7


texts: Rookie: How do I list accounts I've created

texts:
I am new to Etherium, using Ubuntu CLI ,I was wondering how to properly manage accounts. I am trying to simply list the accounts I've created using the following syntax:

  geth account list

Found at the following resource:
https://github.com/ethereum/go-ethereum/wiki/Managing-your-accounts
But the CLI returns the following info:

  INFO [03-28|08:58:21] Maximum peer count                       ETH=25 LES=0 total=25

How do I return a list of accounts I've created? Better yet, a list of accounts and status (locked or unlocked)?
Thank you for your help!


texts: Ethereum noob. Internal TX not reflecting in balance on metamask. "bad jump destination" error. Going crazy

texts:
New to the Ethereum environment. Using metamask, I initiated three transfers of STA for ETH. The STA was deduced from my wallet, however the ETH I was to get in return is not showing. The only new deposits of ETH that I see is one that I sent myself from another wallet, which is clearly the only balance showing.

I see that all three of these transactions are under the internal tx tab, and that at first glance it looks like the ETH was sent. When I contacted the dev of Statera, he suggested I try recovering my wallet on enjin wallet. Once I did, I see that all three of these tx have a "bad jump destination" error.

Here's my public wallet adddress. Here's ethplorer

The contract address, with my wallet filtered.

Finally the address the transfer of ETH originated from, filtered with my address. Looking at this page, I see nothing that correlates with the time, or amount of ETH I should have received.

I understand (slightly. this is all new, and I've been trying to research on my own with due dilligence) that internal tx are off chain. All of the other tx I have made with this account have been either from another wallet I control, or from trading STA token. They all show up properly. Why would my transfer of STA, or for that matter ETH in the first place show up when using this contract, but only my half appearing when initiating STA to ETH from the same address???

Please help me understand what is going on here, and how to resolve it. Thank you.


texts: Moved presale ether after the fork how do I split?

texts:
I bought ether at the presale and moved it to another address after the fork. I still have the original wallet backup, but I'm uncertian on the process to claim ETC. When I scan my Address on Ethereum Classic Block Explorer I have a ETC Balance. But I have moved almost all my ETH out of the same address with a balance of just 0.02 ETH. Can I claim ETC? If so How?

Thanx


texts: Contract has no network id set, cannot lookup artifact data

texts:
I am using web3 v1.0.0-beta.37 and truffle contract for server.js configuration. I have defined two contracts FlightSuretyData.sol and FlightSuretyApp.sol FlightSuretyApp contract access functions from FlightSuretyData without importing the contract but through the FlightSuretyData deployed address. I have tried producing many steps through online research but I am not able to figure out the solution to this:

Here's my deploy_migrations:

const FlightSuretyApp = artifacts.require("../contracts/FlightSuretyApp.sol");
const FlightSuretyData = artifacts.require("../contracts/FlightSuretyData.sol");
const fs = require('fs');

module.exports = function(deployer) {

    let firstAirline = '0x55690752ed06B1d37510D20B3516b2D12F007f6d';

    deployer.deploy(FlightSuretyData, firstAirline)
    .then(() => {
        return deployer.deploy(FlightSuretyApp, FlightSuretyData.address)
                .then(() => {
                    let config = {
                        localhost: {
                            url: 'http://127.0.0.1:7545',
                            dataAddress: FlightSuretyData.address,
                            appAddress: FlightSuretyApp.address,
                            numOracles: 50,
                        }
                    }
                    fs.writeFileSync(__dirname + '/../src/dapp/config.json',JSON.stringify(config, null, '\t'), 'utf-8');
                    fs.writeFileSync(__dirname + '/../src/server/config.json',JSON.stringify(config, null, '\t'), 'utf-8');
                });
    });

Here's my server.js configuration:

import FlightSuretyApp from '../../build/contracts/FlightSuretyApp.json';
import FlightSuretyData from '../../build/contracts/FlightSuretyData.json';
import contract from 'truffle-contract';
import Web3 from 'web3';
import express from 'express';
const bodyParser = require("body-parser");
const cors = require("cors");

let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
const accounts = web3.eth.getAccounts();
web3.eth.defaultAccount = "0x55690752ed06B1d37510D20B3516b2D12F007f6d";
let flightSuretyApp = contract(FlightSuretyApp, FlightSuretyApp.address);
let flightSuretyData = contract(FlightSuretyData, FlightSuretyData.address);

class ContractServer {

  constructor() {
    this.flightsForPurchase = [];
    this.flightsLanded = [];
    this.oracles = [];
    this.status = [20, 30, 40, 50, 0];
  }

  init = async () => {

    flightSuretyApp.setProvider(new Web3.providers.HttpProvider('http://localhost:7545'));
    flightSuretyData.setProvider(new Web3.providers.HttpProvider('http://localhost:7545'));

    try {
      const address = await flightSuretyApp.address;
      const accs = await accounts;
      await flightSuretyData.methods.authorizeCaller(address).send({from: accs[0]});
    } catch (error) {
      console.log(error.toString());
      console.error('Check if Ganache is running and contracts deployed properly!');
      process.exit();
    }

I have tried truffle migrate --reset --development

Here's the error produced:

  Error: FlightSuretyApp has no network id set, cannot lookup artifact
  data. Either set the network manually using
  FlightSuretyApp.setNetwork(), run FlightSuretyApp.detectNetwork(), or
  use new(), at() or deployed() as a thenable which will detect the
  network automatically. Check if Ganache is running and contracts
  deployed properly!


texts: How to use truffle-assertions to verify parameters of an emit?

texts:
I have not been able to find any resources with usage instruction besides github and blog post by the author

On github an example is show as such:

truffleAssert.eventEmitted(result, 'TestEvent', (ev) => {
    return ev.param1 === 10 && ev.param2 === ev.param3;
});

And on the blogpost the syntax is like this:

truffleAssert.eventEmitted(tx, 'Play', (ev) => {
    return ev.player === bettingAccount && !ev.betNumber.eq(ev.winningNumber);
});

Both of these are rather similar.

This is the emit I am trying to test:

event Emittest(uint date, address indexed from, address indexed to, uint256 value);

My issues is that if I try to run the same format:

let emittest = await contract.function(accounts[1], 66500000,{from: accounts[0]});

truffleAssert.eventEmitted(emittest, 'Emittest', (ev) => {
        return ev.value == set_value;
});

It fails with the error AssertionError: Event filter for Transfer returned no results. I can extract the correct value by changing the code to:

truffleAssert.eventEmitted(emittest, 'Emittest', (ev) => {
        return ev.value.words[0] == set_value;
});

As the tokens is of the following structure:

value ==== BN {
  negative: 0,
  words: [ 60475904, 14, <1 empty item> ],
  length: 2,
  red: null
}

Accessing .words[0] doesn't seem like the correct way as it makes it much more difficult to check BigNumbers which are split across multiple indices of the array words: without writing a helper function. Addresses extracted from the emit appear and can be accessed as expected.
Splitting between multiple words happens much sooner than the 2^53 limit of javascript at around 66 million. I am new to javascript, and might be doing multiple things wrong. Thanks for help.


texts: Information Regarding LASER and Ethereum

texts:
I was reading this article

https://diligence.consensys.net/files/D1T2%20-%20Bernhard%20Mueller%20-%20Smashing%20Ethereum%20Smart%20Contracts%20for%20Fun%20and%20ACTUAL%20Profit.pdf

and came across a line on page 10

Using LASER, we can represent smart contract execution as a space of states and path formulas in propositional logic. Obviously, this   in itself is a mind-blowing achievement, but how is it useful for security analysis?

I would like to know what is this correlation between LASER and Smart Contracts or in general with Ethereum?

Also if anyone can point me in the direction of how this is useful and further reading would be helpful

Possible clues I had are it has something to do with Mythril


texts: Contract Not sending ether to other account

texts:
I have created a contract which store the address of the users and i want to send 1 ether all the users stored in array.

Here is my code

contract project{

    address public user;
    bytes32[10] name;
    address[10] customer;
    uint public i=0;
    function project(){
        user=msg.sender;
    }

    function add(bytes32 _name){
        name[i]=_name;
        customer[i]=msg.sender;
        i++;
    }

    function get_address() constant returns(address[10]){
        return customer;
    }

    function reward() {
        for(uint i=0;i<10;i++)
        {
            customer[i].send(1);
        }

    }

}

When i call the method reward metamask executed the transaction but ether is not transferred.

Please help me.


texts: Why would I use Metamask instead of only using Web3.js in the browser?

texts:
It is my understanding that Metamask brings a convenient way for the user to interact with DApps by storing their wallets and by providing an interface that gives the user control of what the DApp is doing. Is this correct?

If the user does not mind at all inserting the wallet address and password, and they fully trust the app, is there any reason to use Metamask? Web3.js allows doing everything that Metamask does in the browser as well, right?


texts:
Sometimes my node just stop sending transactions, I can use most of the commands, but sendTransaction just timeout.
eth.syncing return false
eth.blockNumber return the latest block
htop shows my server is not overloaded (8cores 20gb ram)
It works sometimes, but then it stops and keep bugged for some hours, it was working perfectly about a week ago, no modifications have been made on the server and no updates on the node.
I'm trying to send the transaction from command line for test purposes, like:
eth.sendTransaction({from: "0x46da24dbb9a19dafaf620a363396cecf20c95fed",to: "0x46da24dbb9a19dafaf620a363396cecf20c95fed", value: "0"})
bsc.log don't show anything anormal.
Anyone experienced this issue?
Version: Geth v1.0.7


texts:
I'm getting the following:

➜  voting_truffle geth console
WARN [11-29|22:53:43] No etherbase set and no accounts found as default
Fatal: Error starting protocol stack: datadir already used by another process

But it seems like I could get into the console using geth attach:

➜  voting_truffle geth attach
Welcome to the Geth JavaScript console!

instance: Geth/v1.7.3-stable/darwin-amd64/go1.9.2
 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> eth.syncing
{
  currentBlock: 64827,
  highestBlock: 4644478,
  knownStates: 43977,
  pulledStates: 41202,
  startingBlock: 0
}
>

What's the difference?


texts:
I'm basing this question on information from the whitepaper.

The Slock.it DAO is meant to decentralize a trust. In their system, proposals are smart contracts DAO participants vote on. My issue is with the fundamental logic:

Why do potential investors need to go through the DAO to invest in these proposals, when they could directly access the proposal smart contracts (that can manage budgeting etc.) instead?

What added benefit does the DAO really have?


texts: Can you update contract token decimals and token name?

texts: So I'd like to change token decimals and token name in a specific contract. Is it possible?


texts: Balance of an address depending on a time variable

texts:
is there a way to compare the balance of an address at two different times or in general check the balance of an address at a specific time?

I would like to do something like...

uint256 public startTime
address public exampleAddress

function exampleFunction () public constant returns (uint value) {
    if (balanceOf(exampleAddress) < balanceOf_atStartTime(exampleAddress)) {
        returns X;
    }
}

My preferred input would be a variable like defined above, but an Unix Timestamp or an event would be suitable as well.

Does anyone know a way to do this kind of operation?

Thank you very much in advance


texts: ERC721 Token Transfer Outside Smart Contract

texts: I am using OpenZeppelin ERC721 implementation for my non fungible tokens. Basically I have a smart contract which inherits from the OZ ERC721.sol. I am just wondering is the tokens only transferable between addresses through the smart contract functions such as safeTransferFrom (and other relevant functions)? For example, could I transfer the NFT through an external provider like in the Metamask UI?


texts: How costly is leaving a gap in an array?

texts:
I want just delete the element in the array but not reformat the array to close the gap

delete array[index];

How costly is this assuming bytes32 as the arrays type? Will it call STORAGEKILL and free ether?


texts: "fatal: failed to open database" error when starting Geth

texts:
I am trying to create private block chain. When I am trying to run this command:

geth init ./customgenesis.json

...it is showing an error:

fatal: failed to open database: The process cannot access the file because it is being used by another process

I am unable to proceed with the other steps. May I know how to overcome this?


texts: Exception:Reverted when swap by smart contrat with uniswap

texts:
Here is my code
pragma solidity ^0.8.2;
import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";

contract Test_Swap{

  address owner = msg.sender;

  IUniswapV2Router02 uniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

  address private token_address = 0x514910771AF9Ca656af840dff83E8264EcF986CA; //chainlink
  address private usdc = 0x0D9C8723B343A8368BebE0B5E89273fF8D712e3C;

  function getPathForETHtoToken() private view returns (address[] memory) {
     address[] memory path = new address[](2);
     path[0] = uniswap.WETH();
     path[1] = usdc;
   return path;
   }

  function swapContractEthToLink() external payable {
  uniswap.swapExactETHForTokens{value: msg.value}(0,getPathForETHtoToken(), owner, block.timestamp + 15);
  }
}

I'm trying to trade for my ethers for usdc, but I'm getting an error
I'm using a remix, deploying my contract on kovan
I apologize for my english (google translator) and maybe a stupid question, I'm a beginner, I will be grateful for your help


texts: Truffle migrate shows an error on open zeppelin ERC721

texts:
I'm very new to truffle and solidity it might be a rookie mistake.
When typing truffle migrate --reset, I've got the follow errors :
    @openzeppelin/contracts/introspection/ERC165.sol:24:5: Warning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient.
    constructor () internal {
    ^ (Relevant source part starts here and spans across multiple lines).
,@openzeppelin/contracts/token/ERC721/ERC721.sol:93:5: Warning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient.
    constructor (string memory name_, string memory symbol_) public {
    ^ (Relevant source part starts here and spans across multiple lines)

> Artifacts written to C:\Users\greathawkeye\blockchain\abis
> Compiled successfully using:
   - solc: 0.7.6+commit.7338295f.Emscripten.clang

It looks like this warning prevents me for compiling. Here are my token and my migration contracts :
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;

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

contract MyToken is ERC721 {
    constructor() ERC721('MyToken', 'MYT') {}
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.8.0;

contract Migrations {
    address public owner;
    uint256 public last_completed_migration;

    modifier restricted() {
        if (msg.sender == owner) _;
    }

    constructor() {
        owner = msg.sender;
    }

    function setCompleted(uint256 completed) public restricted {
        last_completed_migration = completed;
    }

    function upgrade(address new_address) public restricted {
        Migrations upgraded = Migrations(new_address);
        upgraded.setCompleted(last_completed_migration);
    }
}

truffle version gives me this :
Truffle v5.1.62 (core: 5.1.62)
Solidity - >=0.6.0 <0.8.0 (solc-js)
Node v15.5.0
Web3.js v1.2.9

Here is my truffle-config.js
module.exports = {
  compilers: {
    solc: {
      version: ">=0.6.0 <0.8.0",
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  },
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    }
  }
};


texts: How are Go-ethereum and Parity maintained and who maintains them?

texts:
How are Go-ethereum and Parity maintained, who maintains them and where is the recommended point of access?

I have had problems finding the latest versions of Geth and Parity:

First, the link behind "latest stable binary" (pointing to https://build.ethdev.com/builds/Windows%20Go%20master%20branch/) in page https://www.ethereum.org/cli#windows seems invalid. Browser responded with "The site can't be reached".

~~Then, I went to Installation Instructions for Windows in github. First line says "All versions of Geth are built and available for download at https://geth.ethereum.org/download/". But, oops https://geth.ethereum.org/download/ was 404.~~

eth has similar results too. http://www.ethdocs.org/en/latest/ethereum-clients/cpp-ethereum/installing-binaries/windows-installer.html is the link given at https://www.ethereum.org/cli but it returns 404 too.

Note: Installation Instructions for Windows was fixed to point to valid url.


texts: Can "ERC721 protocol" be used for supply chain traceability and integrity?

texts:
As I understand it, ERC721's, also known as NFTs (Non-fungible token) are tokens where each one is unique. The individual tokens often come with metadata.

They're usually indivisible (ERC20s you can usually have as little as 1*10-18 of it, but ERC721 you can have multiples of 1).
An example: a game where you have an inventory. All the different items in the inventory could be considered NFTs, where you have 5 arrows, a sword, a fish, etc.

Another example is of course CryptoKitties. A kitty is an NFT with metadata that isn't divisible (you can't sell someone half your cat...) ELI5: Tradeable assets that are unique from each other. Houses, cars, rare/unique collectibles.
Baseballs could be traded as NFTs where a baseball has metadata related to all the players who pitched it, who it's signed by, etc.

The fact that each token can have metadata attached to it, means we can store specific data relative to the factory, supply chain, production chain, producer etc etc in the metadata as a proof of integrity, right?

Suppose we are talking about a production line of pils or vaccine or meat or anything produced in mass, we can insure the integrity of the product by storing specific data (producer, date time of production, unique identifier) in the metadata that we can send in the transaction in our blockchain and then verify at any moment the metadata via our blockchain explorer.

is all that scenario possible with the ERC721 or am I just imagining thing?


texts: Can read from smart contract but can't write

texts:
I have a app.js script that I am trying to use to interact with a smart contract. I can read from the contract however, I cannot write to it. The called method countMessages() returns the correct values, however, setMachineInfo() seems to do nothing and produces no error. Both functions work with other scripts.

    var Tx     = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('http://localhost:8043')

const account1 = ''
const account2 = ''

const privateKey1 = Buffer.from('', 'hex')
const privateKey2 = Buffer.from('', 'hex')

const contractAddress = '0xc14aC2e543Cc3fB33B53b163311d10F5Dd4337e1'
const abi = []
const contract = new web3.eth.Contract(abi, contractAddress)

var name = web3.utils.toHex("Name")
var message = web3.utils.toHex("Message")
var sendingData = contract.methods.setMachineInfo(account2,name,message).encodeABI()

contract.methods.countMessages().call((err, result) => { console.log("Messages: "+result) })

web3.eth.getTransactionCount(account1, (err, txCount) => {
  // Build the transaction
  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(33000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('50', 'gwei')),
    to:       contractAddress,
    data: contract.methods.setMachineInfo(account1,name,message).encodeABI()
  }
  console.log("txCount: "+txCount)
  // Sign the transaction
  const tx = new Tx(txObject)
  tx.sign(privateKey1)

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

  // Broadcast the transaction
  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    console.log('txHash:', txHash)
    // Now go check etherscan to see the transaction!
  })

       console.log("Err: "+err)
})

function countMessages() view public returns(uint){
    return machineAccounts.length;
}

function getMachineMessage(uint k) view public returns(address, bytes32, bytes32, uint256){

    return(machines[k].delegate,machines[k].name, machines[k].message, machines[k].time);
}

I get a transaction hash which when I put into mycrypto shows the transaction and the block.


texts:
I have created a shell script on a ubuntu server X with geth Node installed,to insert data in a smart contract in testnet blockchain. Further I am executing the shell script from a PHP file insertscript.php created on the same server X by using shell_exec command. When I call the PHP script  from the command prompt , it gets successfully executed and data gets inserted in the blockchain . But when I call the php script from another server by using cURL or open it in the browser, I will see the error :

Fatal: Unable to attach to remote geth: dial unix ///home/ubuntu/.ethereum/testnet/geth.ipc: connect: permission denied

My shell script looks something like:-

#!/bin/sh
ATTACHPARAMETER="ipc:///home/ubuntu/.ethereum/testnet/geth.ipc"
INCIDENTUUID=${1:-"photo-55697b7f4a550511448499999999"}
USERUUID=${2:-"null"}
TIMESTAMP=$3
STATUS=$4

echo $INCIDENTUUID
echo $USERUUID
echo $TIMESTAMP
echo $STATUS

geth attach $ATTACHPARAMETER << EOF

var abi = [abi definition];
var address = "addressofContract";
var mycontract = web3.eth.contract(abi).at(address);
eth.defaultAddress = eth.accounts[0];
personal.unlockAccount(eth.accounts[0],'test');

mycontract.createIncident('$INCIDENTUUID','$USERUUID',$TIMESTAMP,$STATUS,{from:eth.accounts[0],gas:1400000});
console.log("Inserted");

EOF

Could you help in finding the cause of this error and also in finding a solution to the same?


texts: Does each token created during an ICO have its unique ID?

texts:
Lets say there's a million utility token created during an ICO.
The users access to the utility is based on user owning at least one token.
Does each token have it's own unique ID, or do the tokens create just one big pool (balance) from which tokens are transferred to ICO subscribers as quantity, not as individual identifiable tokens? Should the token in this case have decimals set to zero?


texts: When I deploy smart contract on the Rinkeby network using Remix the ABI of smart contract does not contain its address, so how do I connect it with my frontend application.


texts: Transaction Failed when I try to swap BNB for CAKE using swapExactETHForTokensSupportingFeeOnTransferTokens

texts:
I'm trying to swap on Pancakeswap for BNB for CAKE, but I've been running into an error. The error reason says, "transaction failed" code: "CALL_EXCEPTION".  Been at it for a couple of days, but I can't figure it out. May I ask for your help, please?
It eats up my gas, but the transaction fails:
https://testnet.bscscan.com/tx/0x85be92c54e6a9e7267ca62ae7d149115dfebe0ae9a6cee3a709797710a70847a
Here is my code:
async function swapOnPancake(account) {
  const router = new Contract(
    testAddresses.router,
    [
      'function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external',
      'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
      'function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)'
    ],
    account
    );

    path = [WETH_TOKEN_ADDRESS, tokenAddress];
    to = recipient;
    const amountIn = utils.parseEther("0.001");
    // const amounts = await router.getAmountsOut(amountIn, path);
    // const amountOutMin = amounts[1].sub(amounts[1].div(10));

    try{
      const tx = await router.swapExactETHForTokensSupportingFeeOnTransferTokens(
        amountIn,
        0,
        path,
        to,
        Date.now() + 1000 * 60 * 10,
        {
          'gasLimit': 2140790,
          'gasPrice': utils.parseUnits('10', 'gwei')
        }
      );
      // console.log(tx);
      const receipt = await tx.wait();
      console.log(receipt);
    }
    catch(err) {
      console.log(err);
    }
}


texts: Geth: how to unlock an account via json rpc

texts: I am running geth and have my api calls all setup but some are useless as I can't  sendtransaction without first unlocking the related account. The unlock needs to be over the wire as the caller is not on the same machine and may call to different instances of geth on different machines (backups).


texts: Is that the gas price actually affects the transaction time on the Ropsten testnet

texts:
I know that If the gas price is high enough, the transaction will be executed sooner since miners will execute transactions with the highest gas price first.

does this rule really apply in the Ropsten testnet, do miners take a fee to mine blocks in such testnet?

In fact, I made the same transaction using a gas price = 0.000000001 (1 Gwei)and gas price = 0.00000002(20 Gwei) and I did not notice a difference in the execution time. In the opposite, sometimes the transaction with 20Gwei take much more time to be executed


texts: What is the recommended procedure to report potential vulnerabilities in a smart contract?

texts:
I was browsing etherscan's verified smart contracts (i.e. the ones with the source code attached), and I saw that one of the smart contracts contain (or at least I think it contains) a potential vulnerability, in particular it may burn some money. It is sufficient to leave a comment in the comment section?

In this case may be sufficient, but if the vulnerability was even worse? Is there the possibility to contact the developers?


texts: Confusion over sendTransaction vs contract methods

texts:
I'm building a UI that talks to a smart contract and I'm using contract methods.
const data = await contract.methods.buyCredits().send({
        from: account,
        gas: 233000,
        value: choice.value,
      });

But noticed in several questions, the usage of sendTransaction.
Is the difference that sendTransaction is just a raw wallet to contract, wallet to wallet sending of Ether — not a contract method call?
web3.eth.sendTransaction or contract methods
What is the difference?


texts: How does Polkadot enable the integration of different blockchains? What are the core components of that process?. I would like to understand the difference between two way pegging and the Polkadot technology.