texts: How to sign and verify data with ethereumjs-utils?

texts:
In my contract I'm verifying if some data was correctly signed by the owner. It looks like this:
require(
    owner() ==
        ecrecover(keccak256(abi.encodePacked(this, aCustomId)), v, r, s),
        "owner should sign aCustomId"
    );

Which means i should be retrieving v, r, s from a backend, which I currently do like this:
import * as ethUtil from 'ethereumjs-util';

const hash = soliditySha3(
  'myContractAddress',
  '11111',
);
const signature = ethUtil.ecsign(
    ethUtil.toBuffer(hash),
    wallet.getPrivateKey(),
);

return {
      r: ethUtil.bufferToHex(signature.r),
      s: ethUtil.bufferToHex(signature.s),
      v: signature.v,
      aCustomId: 11111,
};
// return the v, r, s

however, it seems like it's not correct as I keep getting "owner should sign aCustomId".
How can i create the correct hash so my v,r,s parameters are correct for recovering later ?
I'm using solidity version 0.6.12
The contract is called something like this:
myContract.methods
    .someMethod(
        11111,
        vValueAsInt,
        "sValue",
        "rValue",
    )
    .send({ from: account }, function(
        error: any,
        transactionHash: any
    ) {
        console.log(transactionHash);
        console.log(error);
    });


texts: Contract storage not changing on calling function

texts:
contract SimpleStorage {
    mapping(bytes32 => string) storedData;

    function set(bytes32 key, string value) {
        storedData[key] = value;
    }

    function get(bytes32 key) constant returns (string retVal) {
        return storedData[key];
    }
}

On the geth console:

mySource = 'contract SimpleStorage { mapping(bytes32 => string) storedData; function set(bytes32 key, string value) { storedData[key] = value;} function get(bytes32 key) constant returns (string retVal) { return storedData[key];}}'
myCompiled = web3.eth.compile.solidity(mySource)
myContract = web3.eth.contract(myCompiled.SimpleStorage.info.abiDefinition);
SimpleStorage = myContract.new({from:web3.eth.accounts[0], data: myCompiled.SimpleStorage.code, gas: 10000000})
miner.start()
SimpleStorage.address (I get "0x03b6676ec81168749af1a92783e67bf3b065add3")
SimpleStorage.set.sendTransaction("hash", "value", {from: eth.accounts[0]})
miner.start()
miner.stop()
eth.getStorageAt("0x03b6676ec81168749af1a92783e67bf3b065add3")

I get:

  0x0000000000000000000000000000000000000000000000000000000000000000

Why has the contract storage not changed?


texts: hdwallet-provider set multiple account addresses when deploy contract

texts:
I'm using for deploying contracts hdwallet-provider, but I have issue on client side to get multiple accounts using web3.eth.getAccounts() call.

I know this is like duplicate question and truffle already has solution for this, but I have issue getting more than one account address.

On metamask I have three accounts, but only the default one is showing on the client side.
From the first snippet u can see that I'm setting 3 as fourth parametar

Deploy code

const provider = new HDWalletProvider(
  'mnemonic....',
  'https://rinkeby.infura.io/v3/bba91a6c349c44afbde264a1bda1af75', 0, 3
);

How I import web3 in client code

import Web3 from 'web3';

if (window.ethereum) {
  window.web3 = new Web3(window.ethereum);

  (async () => {
    await window.ethereum.enable();
  })();
}
// Legacy dapp browsers...
else if (window.web3) {
  window.web3 = new Web3(window.web3.currentProvider);
}
// Non-dapp browsers...
else {
  console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}

export default window.web3;

Client code

web3.eth.getAccounts().then(console.log);

BR, Igor


texts: Is there a way to get public key using web3.js?

texts:
I know there are ways to get public key from private key using other then web3js tools (EthereumJS: How to get public key from private key and https://kobl.one/blog/create-full-ethereum-keypair-and-address/)
Also, there is a way to get public key from address having a transaction sent from that address – Get public key of any ethereum account

I am looking for a way to get public key using web3js. Is there a way to do it?


texts:
I experience unexpected revert in the line where I invoke bidEnd.

  it("should create second contract and remove it", function(done) {
    BiddingsFactory.deployed().then(async function (biddings_factory) {
      await biddings_factory.create("Second", "Second bidding", 2, 20, {from: accounts[2]});
      var biddings = await biddings_factory.getAllBiddings();
      assert.equal(biddings.length, 2, "There are two biddings.");
      var biddingAddress = await biddings_factory.getLastBidding.call();
      var bidding = await Bidding.at(biddingAddress);
      setTimeout(async function () {
        await biddings_factory.remove(biddings.length - 1);
        await bidding.bidEnd({from: accounts[2]});
        var biddingsNumber = await biddings_factory.getNumberOfBiddings.call();
        assert.equal(biddingsNumber, 1, "There is only one bidding.");
        done();
      }, 1000 * 2);
    });

Sometimes my test passes but when I rerun, it always fails. The bidEnd function body:

selfdestruct(owner);

It contains modifiers but I remove them for the testing to be clear. What might be the reason?


texts: ICO: how to accept bitcoins, credit cards and fiat?

texts:
A customer wants to launch an ICO which should accept contributions in Ethers, Bitcoins, and fiat via credit cards and wire transfer.
Anyone was able to solve this? I know that this isn't an Ethereum problem but it seems to be an issue for ICOs since most accept only Ethers.


texts: How to upgrade solidity compiler solc to version 0.5.x?

texts: I am using solidity 0.4.24. The latest version has been updated. How to upgrade my solidity version? Is there any commands for it?


texts: API to enumerate the blocks from a specific day

texts:
I'm trying to find an API that lists all the blocks from a specific day, as we can do with bitcoin:

https://blockchain.info/pt/blocks/1515628800000?format=json

I've searched etherscan.io and blockcypher.com APIs, as well as other ones and found nothing. Some APIs can list the latest blocks, but that's not what I need.

Is there any ethereum API similar to the blockchain.info API that can show all the blocks from a specific day?


texts: Should correct transaction nonce be one less than account transaction count?

texts:
I am trying to solve the 'Why am i getting “removed tx from pool: low tx nonce or out of funds”?' problem on my private test net.

I seem to have enough funds however the rejected transaction nonce is always one less than the transaction count of the sending address:

I0427 16:02:49.456986   84576 tx_pool.go:492] removed tx (
    TX(cf149f29fdb9ee3fe4f6b3907d396e8fd5abc832e21ee5453c9702003b5fd62a)
    Contract: false
    From:     db575481f1d1b626b9a0ee2f2c6946b3f6526cd4
    To:       [contract creation]
    Nonce:    6
    GasPrice: 20000000000
    GasLimit  1062420143
    Value:    0
    Data:     0x
    V:        0x1c
    R:        0x7832879e31c8c679779c34f0004a38e3e64848ce9a92757cebb11d792ccb1435
    S:        0x28d0b672e4b904d972d221df2c53250a9884b13142a63c9be193537557b241ea
    Hex:      f852068504a817c800843f533eaf8080801ca07832879e31c8c679779c34f0004a38e3e64848ce9a92757cebb11d792ccb1435a028d0b672e4b904d972d221df2c53250a9884b13142a63c9be193537557b241ea
) from pool: low tx nonce or out of funds

> eth.getTransactionCount("db575481f1d1b626b9a0ee2f2c6946b3f6526cd4")
7
> eth.getBalance("db575481f1d1b626b9a0ee2f2c6946b3f6526cd4");
7.4699999999999996e+21

Is the tx nonce and transaction count consistent here?

If the nonce is zero indexed then I guess that they are. If that is the case I have no idea why I am getting this error message. This is driving me crazy. Can anyone help?


texts: Return value conversion from external Call

texts:
i have an external call inside a Contract function to another function.

Here is my code: Contract 1

function getContractForAddr(address ethAddress_) public payable returns (address){
   return adresses[ethAddress_].contractAddr;
}

Contract 2:

function testFunc(address to_){
   (bool success, bytes memory data) = mainContract.call(abi.encodeWithSignature("getContractForAddr(address)", to_));
}

I get a value inside the data field back and success is true but it is supposed to be a address.
How can i convert it to address? I already tried the Seriality function.
I use Solidity > v0.5 !
Thank you


texts: JS Testing: A contract calling a function in another contract which creates a contract

texts:
I want to test three contracts in total: Main.sol, Factory.sol, PCE.sol
Here's the flow I want:

accounts[0] calls factoryStart in Main.sol
Main.sol should call a function in Factory.sol, passing the address of accounts[0]
Factory.sol should create/deploy a new PCE.sol, passing the args

Below is the half-working code. Parts of code are omitted for readability:
Main.sol
import '../factory/Factory.sol';

pragma solidity ^0.7.0;

contract Main:
{

    Factory factory;
    uint256 factoryStartCount;

    constructor(address _factory)
    {
        factory = Factory(_factory);
    }

    function factoryStart(uint256 attr1, uint256 attr2) public payable
    {

        AM_ADDRESS = msg.sender;

        factory.newPCE( attr1, attr2, AM_ADDRESS);

        factoryStartCount++;

    }

    function getFactoryStartCount() public view returns(uint256)
    {
        return factoryStartCount;
    }

}

Factory.sol:
import '../PCE/PCE.sol';

pragma solidity ^0.7.0;

contract Factory
{

  uint256 numPCE;

  function newPCE(uint256 attr1, uint256 attr2, address payable AM_ADDRESS) public payable
  returns(PCE)
   {

    address payable VAULT  = 0x1B2F262A2320939001a0276FB335EAf7b6185e38;

    PCE cookie =  new PCE( attr1, attr2, AM_ADDRESS, VAULT) ;

    numPCE++;
    return cookie;
   }

    function getNumPCE() public view returns(uint256)
     {
      return numPCE;
     }
}

PCE.sol:
pragma solidity ^0.7.0;

contract PCE{

  constructor (uint256 attr1, uint256 attr2, address payable AM_ADDRESS, address payable VAULT)
  {
   // do stuff
  }
  // do other stuff
}

2_deploy_contracts.js :
const PCE_Factory     = artifacts.require("./Factory")
const Main            = artifacts.require("./Main");

module.exports = async function(deployer)
{

  await deployer.deploy(PCE_Factory);

  const Factory = await PCE_Factory.deployed();

  await deployer.deploy(Main, Factory.address);

};

test.js:
const Main          = artifacts.require("Main");
const Factory       = artifacts.require("Factory");

contract('Main', async (accounts) =>
{
    before( async() => {

        instance_factory = await Factory.new()
        instance_main    = await Main.new(Factory.address);

    });

   it('PCE can be created upon request: TEST.A', async() => {

        try{

        await instance_main.factoryStart.call( 2 , 5
            {from: accounts[0] } );
        }

        catch(error){

        console.log(error);
        };

    });

    it('should increment factoryStartCount: TEST.B ', async() => {

        let factoryCount        = await instance_main.getFactoryStartCount.call();
        let int_factoryCount    = new BigNumber(factoryCount)

        console.log('       The factory has been initiated ' +int_factoryCount.toString() + ' times');
        assert.equal(1,int_factoryCount.toString());

    });

    it('should increment numPCE: TEST.C', async() => {

        let currentPCE    = await instance_factory.getNumPCE.call();
        let int_CurrentPCE = new BigNumber(currentPCE);

        console.log('       There are ' + int_CurrentPCE.toString() + 'PCE.' );
        assert.equal(1,int_CurrentPCE.toString());

    });
})

The interesting part is TEST.A passes, but TEST.B and TEST.C fail. I don't understand how TEST.A can pass without incrementing factoryStartCount and/or numPCE. Where am I mistaken ?
TEST.B and TEST.C outputs are both zero.
Any and all help is appreciated.
node: v12.18.4
ganache-cli: v6.12.1
Truffle v5.1.49


texts: I am following a tutorial to build smart contract. And when I do the truffle migrate, there is en error shows can not find module truffle/db


texts:
Currently, DAPP is under development.
Is it possible for us to handle the GAS payment and approval process on behalf of the user who created the token using DAPP when trying to list the token in Uniswap?

User pays for DAPP.
Uer list tokens in Uniswap with the user's address.
We will perform the approval process and GAS payment on User behalf


texts:
I am trying to test my quorum setup by load testing it.

Are there any JSON RPC Load Testing / Stress Testing Tools? Does Postman or SOAP UI supports JSON/RPC calls?


texts: Why does proof of work targeted zeros always comes at the start of hash? why is it not in the middle or the end of hash?

texts:
My question is why always targeted zeros come at the start of hash of the block? I have never seen more than 2 zeros in middle or somewhere else in the hash of mined block... What's the reason?....

My second question is.... as we know that hash of block is not calculated according to our desired target then why NONCE is always used as a digit? not as alphabetic


texts:
Here is code snippet,

 function transfer(address _to, uint _value, bytes memory _data, string memory _custom_fallback) public returns (bool success) {

   if(isContract(_to)) {
       if (balanceOf(msg.sender) < _value) revert();
       balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
       balances[_to] = safeAdd(balanceOf(_to), _value);
       assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
       emit Transfer(msg.sender, _to, _value, _data);
    return true;
   }
   else {
       return transferToAddress(_to, _value, _data);
   }
}

I am currently working with Solidity Version ^0.5.1. What is the alternative and upgraded method to execute this assert function given below. And what is the main working of this assert() and their arguments?

  assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));


texts: How to use parity 1.4.2 with light-client mode?

texts:
I've tried to use the latest geth with --light mode. It gets new blocks not very fast, but I could send transactions successfully. So I think it's useful!

What command should run parity in this mode?


texts: It has the opportunity to see the balance of token?

texts: It has the opportunity to see the balance of tokens? I have adress token and adress account.


texts:
I have very simple solidity code as below -

pragma solidity ^0.5.6;

contract SaveData {
  uint public salary;

  function setSalary(uint input) public {
        salary=input;
  }

  function getSalary() public view returns(uint) {
        return salary;
  }

}

I am calling savedata.setSalary(5000) from eth console. It generates a transaction. However after mining the transaction when I ran savedata.getSalary() it always return me 0. I tried allocating a lot of GAS as well.


texts:
I am trying to understand web3 better and tried out the following snipped:

<script type="text/javascript">
    if (typeof web3 !== 'undefined') {
        web3Provider = web3.currentProvider;
    } else {
        // If no injected web3 instance is detected, fall back to Ganache
        web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
    }
    web3 = new Web3(web3Provider);

    web3.eth.defaulAccount = web3.eth.accounts[0]

    console.log("getBalance:")
    const accounts = web3.eth.accounts
    console.log("accounts", accounts)

    const balance = web3.eth.getBalance(web3.eth.accounts[1])
    console.log("balance", web3.fromWei(balance, "ether"))
</script>

I am running ganache-cli in the background and was expecting to get back a list of accounts and the balance of the account[0].

However, I get back:

As you can see above my accounts object is empty and therefore I get an error.
Basically I just want to load one account address from the ganache-cli and display its balance.

Any suggestions what is wrong with my code?

I appreciate your replies!


texts:
This code works - taken from Wiki -

pragma solidity ^0.4.18;

contract ERC20Interface {
    function transfer(address to, uint tokens) public returns (bool success);

}

contract FixedSupplyToken is ERC20Interface {

    function transferAnyERC20Token(address tokenAddress, uint tokens) public  returns (bool success) {
        return ERC20Interface(tokenAddress).transfer(tokenAddress, tokens);
    }
}

This code does not - fails on the deploy -

pragma solidity ^0.4.18;

contract d8 {
    function myBalance() public  returns (uint myNumber);

}

contract d15 is d8  {
    function getBalance(address addr)  public returns (uint myNumber) {
    return d8(addr).myBalance();
    }
}

Can anyone see why the first one works and the second does not?

>   Replacing Migrations...   ...
> 0x43d0c7631ba73dfe0066f6d7101f5b1bce97d0af35f6c8b19f53c49991b3ae31
> Migrations: 0x1fdad1a831e98a507541c3a3c12f0e5b5487e144 Saving
> successful migration to network...   ...
> 0xad2d902e40c3cdc80e84d08e6cf3af4529cd26a787e8d5b79157236ba1c6236e
> Saving artifacts... Running migration: 2_deploy_contracts.js
> Deploying d15...   ...
> 0x555a8028d89388bd18d83af0ccefe5f6c88e375f0bbf1b4a43b370457f00cb93
> Error encountered, bailing. Network state unknown. Review successful
> transactions manually.

For x1 (first one) -

> Running migration: 1_initial_migration.js   Replacing Migrations...
> ... 0xdc004595e2c2c566b1e10f5ff6a630cffdcf7d64a66a35e1c6f3173dd7143710
> Migrations: 0x20a04f7f8b64ecd154987cb47e10315f8309fb86 Saving
> successful migration to network...   ...
> 0xd105819a9c182415155e2e7999868eb0919fea3ea4bd8096a21d59a1aab9baf9
> Saving artifacts... Running migration: 2_deploy_contracts.js
> Replacing x1...   ...
> 0x90b6d94d4013b69d7b2fbb25bc195ef5b1ca56ca7969ed33e3e20a8e0451a600
> x1: 0xe2a7bacc61fc1cf994e1d5cc148cb95830ff843c Saving successful
> migration to network...   ...
> 0x7a6737f653ff9a82c5d28472d5a79764683c216bb31a395bbcc51102770b2f2e
> Saving artifacts...


texts: Does geth --syncmode light download the State Trie?

texts:
I'd like to download some recent version of the Ethereum State Trie. I read here that geth --syncmode light downloads the current state. But does that only encompass the most recent blocks or also a recent version of the State Trie?

When I started my node, geth said it added a trusted checkpoint for block 5734399. So I figured, it downloaded the state trie from a peer for that block. So I tried to access the leveldb files directly using the state root of block 5734399 following this tutorial. However, there was no trie data available for the state root of that block in the leveldb. Does geth maybe download the State Trie of some other block? Or does it not download any State Trie at all?

Here is my nodejs code for reading the leveldb:

var level = require('level');
var rlp = require('rlp');
var Trie = require('merkle-patricia-tree/secure');

var root = "0x35cabdf547eeddccbc9d2df11e3c8b3e0254144b57ec33560c446d8dccfbdf78"; // block 5734399

var db = level('/media/sdc1/.ethereum_light/geth/lightchaindata');
var trie = new Trie(db, root);

var stream = trie.createReadStream();

stream.on('data', function (data){
        console.log(data.key);
});


texts: How can I build a smart Oracle of my own for a smart contract?

texts: I need my smart contract to access data from some source. I want to build a smart Oracle in order to achieve this.


texts: How to use the address.transfer(amount)?

texts:
Using this smart contract, I want to transfer from one account to another.

Here is my simple smart contract :

pragma solidity ^0.5.0;
contract Subtract {
  address payable public minter;
  uint public balance;
  event Transfer(address payable indexed _from, address payable indexed _to, uint256 _value);
  mapping (address => uint) public balances;
  constructor() public {
    minter = msg.sender;
  }
  function showSender() public view returns (address)
  {
    return (msg.sender);
  }
  function sendcoin(address payable receiver, uint amount) public {
    receiver.transfer(amount);
  }
}

I got 10 new accounts(each having 100 ethers) from the command:

ganache-cli

Then, in another terminal, in truffle console, I created an account using:

web3.eth.personal.newAccount()

The address of new account was:

'0x4FcE397EFfd8a68f033407769f9f444652534Bb7'

Now to send amount, I used the following command:

Subtract.deployed().then(function(instance) { return instance.sendcoin("0x4FcE397EFfd8a68f033407769f9f444652534Bb7",1e+5)});

Then  I got the following error:

Error: Returned error: VM Exception while processing transaction: revert
at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request.js:318:1)
at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request.js:208:1)
at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request-event-target.js:34:1)
at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/~/web3-providers-http/src/index.js:96:1)
at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:112:1
at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth/~/web3-core-requestmanager/src/index.js:140:1
at Object.ErrorResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth/~/web3-core-helpers/src/errors.js:29:1)

I could not understand the error. Can someone please explain what is happening? Please give a possible solution.

Thank you.


texts: creating account in my privateTestNet instead of a Local account in web3.py

texts:
I have created a private test net in geth and trying to create a an account in my private net in python
from web3 import Web3, IPCProvider
web3 = Web3(IPCProvider("../Blockchain/PrivateNet/geth.ipc"))
web3.eth.accounts[0]
web3.eth.account.create('Pass')

web3.eth.accounts[0] is returning correct result ie. the first account in my private-net

but

web3.eth.account.create('Pass') doesnt create any account in the privte-net, it  create a local account  it returns :
eth_account.local.LocalAccount object at 0x7fe748076588


texts: How to calculate the right amount of a token to use in 0x quote endpoint

texts:
I'm trying to use 0x to buy tokens with ETH. I'm following the sample at https://0x.org/docs/guides/swap-tokens-with-0x-api#swap-eth-for-1-dai.
I got the token address, and the decimals. let's say USDC and 6. And let's say I want to buy 1 USDC. How do I calculate the value I need to pass to buyAmount? I tried several things: passing '1', passing '1000000' (1 and 6 0s). I tried 5 0s. When it hits MetaMask it's always the wrong amount: 10 or 100 etc. And the fee is crazy ($39 in gas to buy 10 USDC?).
It's even worse with other tokens and amounts. Can anyone clue me into how to use the decimals to translate the amount I want to buy to the amount I need to send to the quote endpoint?


texts: How to convert uint95 to bytes32 in solidity > 5.0?

texts:
contract TypeConversion{

    uint96 data = 5;
    bytes32 b = bytes32(data);

}

It gives error:
Explicit type conversion not allowed from "uint96" to "bytes32".

What will be the better way to convert integers to a string in solidity?


texts:
I want to use web3.py to send some EOS.
Here is my code:

from ethtoken.abi import EIP20_ABI
from web3 import Web3, HTTPProvider

infura_provider = HTTPProvider('https://mainnet.infura.io/CMI5Z7n7hAy8CP7nx95s')
w3 = Web3(infura_provider)
w3.eth.enable_unaudited_features()

contract_Address = w3.toChecksumAddress("0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0")
unicorns = w3.eth.contract(contract_Address, abi=EIP20_ABI)

nonce = w3.eth.getTransactionCount('0x030eC1E9E2AfA4A59a7C56F2B761505E1a414b45')

unicorn_txn = unicorns.functions.transfer(
    '0xFe0196504dF34c4Bf30D3089EfFf86cFe3B34617',
    1,
).buildTransaction({
    'chainId': 1,
    'gas': 200000,
    'value': int(0.1 * (10 ** 18)),  # EOS:18 decimals
    'gasPrice': w3.toWei('4', 'gwei'),
    'nonce': nonce,
})

private_key = 'my private key'
signed_txn = w3.eth.account.signTransaction(unicorn_txn, private_key=private_key)

TxHash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
print(TxHash.hex())

The code runs without error and print out the TxHash,but the transaction failed,the specific reason can be found here:transaction information

I don't know how to fix this,can anyone help me?Thanks!


texts: How can I check if an Contract variable is undefined in Solidity?


texts: Ethers.js invalid number value while deploying contract

texts:
I'm deploying a contract usign ethers.js
I do it as follows:

const tokenWeiPrice = (answers.priceEur / ethEur) * Math.pow(10, 18);

const contract = await factory.deploy(
   answers.maxSupply,
   answers.eventName,
   answers.symbol,
   0,
   expireAfter,
   tokenWeiPrice
);

While deploying it throws an error

(node:11654) UnhandledPromiseRejectionWarning: Error: invalid constructor argument (arg="_ticketPrice", reason="invalid number value", value=43478260869565220, version=4.0.20)

the problem stays in tokenWeiPrice I would like to know why, in my contract this is a uint256 constructor's parameter.


texts:
Im using the Web3j library to make transactions with my blockchain (Ganache).

I have a method that instantiate a Web3j object and im trying to generate a new account with the given

String url = "http://localhost:7545/";
        Web3j web3j = Web3j.build(new HttpService(url));

        //System.out.println(web3j.ethAccounts().send().getAccounts());

        try {
            ECKeyPair keyPair = Keys.createEcKeyPair();
            WalletFile wallet = Wallet.createStandard(key, keyPair);

            System.out.println("Private key: " + keyPair.getPrivateKey().toString(16));
            System.out.println("Account: " + wallet.getAddress());

But when in the power shell console I connect to ganache using Geth I dont have the new address in the eth.accounts().

What i have to make??


texts:
I am trying to get some logs from ropsten and here is my code:

web3.eth.getPastLogs(
  {
    address: '0x3b873a919aa0512d5a0f09e6dcceaa4a6727fafe',
    fromBlock: 3292448,
    toBlock: 3292448,
  },
).then(console.log).catch(e => console.log(e));

which results in error:

Error: Returned error: invalid argument 0: hex string without 0x prefix

what am I doing wrong?


texts: Problem with truffle deployment in ropsten

texts:
I followed tutorial and add result this tutorial on git

When I trying deploy my contract via command:  truffle migrate --network ropsten

I have error:

How fix this gub?


texts: Why am I getting "Trying to create an instance of an abstract contract." error when I use factory contract pattern?

texts:
I have 2 contracts : Registry, Factory.
Registry contract is compatible with ERC721 contract like this:

pragma solidity ^0.4.24;

import "../openzeppelin-solidity/contracts/token/ERC721/ERC721MetadataMintable.sol";

contract Registry is ERC721MetadataMintable {
    string public name;
    string public symbol;

    constructor(
        string _name,
        string _symbol
    ) ERC721MetadataMintable() public payable {
        name = _name;
        symbol = _symbol;
    }
}

Factory contract is like this below:

pragma solidity ^0.4.24;

import "./Registry.sol";

contract Factory {

    function _createRegistry (
        string _name,
        string _symbol
    ) internal returns (address) {
        return new Registry(_name, _symbol);
    }
}

However I get error just like this below:

browser/Factory.sol:15:16: TypeError: Trying to create an instance of an abstract contract.
    return new Registry(_name, _symbol);
           ^----------^
browser/ERC721Metadata.sol:28:5: Missing implementation:
constructor (string name, string symbol) public {
^ (Relevant source part starts here and spans across multiple lines).


texts: Mining using Four computers.... what to do?

texts:
I've been reading through the page for ideas but thought I'd just ask.

I have 4 basic desktop computers that I are only used for a few hours a week.

The graphics is integrated with the CPU so I know I have to buy graphics cards which isn't a problem.
I have been reading about the Radeon RX480, but have also notice people using 2xRadeon RX260. I just wanted to get peoples opinions on whats best.

Thanks

Eddue


texts:
I have a library which I want to deploy followed by a number of differing contracts which link to it. However I seem to me missing some understanding about library deployment and utilisation.

The library contains structs and functional logic and the contract I want to deploy afterwards is a test harness consisting of a state variable of type struct defined in the library and public wrappers of the library functions.

The compilation output isn't what I expected though.  The library binary is very little (<80 bytes) while contract binary is very large (>5kb) and appears to contain the majority of the bytecode from the library.  Furthermore, the contract bytecode has no linker place holder for the library address as I've seen in other examples

The code otherwise compiles fine and runs in Mix.

So the crucial question is, How do I compile and deploy the stand alone library?


texts: How to send ERC20 without paying gas in Ether?

texts:
Is there any way to send ERC20 Dai without paying gas in Ether but paying in DAI instead?
I heard about some services which called relayers which presumably can help to send popular ERC20 token without you paying gas. It works like that: you sing tx for recipient and relayed address and send it to relayer. And relayer somehow is able to pay gas for you.
Is it true? If so, how does it work? Is there any other ways to send Dai by paying fee in Dai?


texts: Is it OK to use this in a contract? Resetting the admin of a contract

texts:
I'm developing a contract that has an admin.
That admin has some functions only he can call and I'm calling them from a server. Now my biggest fear is that the server is compromised and someone gets the private-key for said admin.

That's why I thought about putting a function that I can use to reset the admin.

The function looks like so:

    address private constant emergency_admin = 0x...;
    address private admin = 0x...;
      function emergency(address newa, bytes32 h, uint8 v, bytes32 r, bytes32 s,bytes32 h2, uint8 v2, bytes32 r2, bytes32 s2)
          public
        {
          //check if the signed messages match the new addres
          require(h==prefixedHash2(newa));
          require(h2==prefixedHash2(newa));
          //check if admin and emergency_admin signed the messages
          require(ecrecover(h, v, r, s)==admin);
          require(ecrecover(h2, v2, r2, s2)==emergency_admin);
          //set new admin
          admin = newa;
        }
        function prefixedHash2(address message)
          private
          pure
          returns (bytes32)
        {
            bytes32 h = keccak256(message);
            bytes memory prefix = "\x19Ethereum Signed Message:\n32";
            bytes32 prefixedHashe = keccak256(prefix, h);
            return prefixedHashe;
        }

The emergency_admin private-key would obviously not be saved on the server. More like on a piece of paper in a safe.

I'm wondering if this is acceptable or even makes any sense, or if there are way better solutions to this I haven't thought of?


texts:
I am creating a smart contract which simulates a lottery game: users purchase tickets from a fixed pool of tickets, and at the end, a random ticket number is drawn for the winner. I am now concerned with the process of selecting the random ticket number which is the winning ticket.

I was reading this post:
How can I securely generate a random number in my smart contract?

and I still do not understand why I can't simply generate a random number in the range 1 - amount of tickets and assign that to be the winning tickets, using the equivalent of:

randomNum = 1 + (int)(Math.random() * amount_of_tickets);

This sounds very trivial, but I do not see how it would be unfair or how it could be manipulated since every ticket would have an equal chance of being selected. It was also suggested that I should use the hash of the chain head in this computation, again I do not understand why this would be beneficial or necessary.


texts: Fast node can't cacth up, how to find whats slowing me down?

texts:
I'm running a geth fast node but I can't seem to catch up.
I did it using a ubuntu in wsl (windows) and everything is on a SSD.
However when I do eth.syncing.highestBlock - eth.syncing.currentBlock it's oscilating betwen 120 and 80.
How can I analyse what the source of the problem could be?
Thanks


texts: Unable to setup Ethereum Mining Software

texts:
I have followed the below steps:

downloaded geth, copied to C: drive.
executed geth acount new in command prompt.
downloaded the mist wallet and tried to install it, but it got stuck at:

  Ethereum node needs to sync, please wait... Looking for peers...

since the last 24 hours.

I do not know what to do. Can you please help me setting it up?


texts: Type struct Mycontract.User memory is not implicitly convertible to expected type struct Mycontract.User storage pointer

texts:
pragma solidity >=0.5.0 <0.7.0;
contract Mycontract{
    uint256 a;
    struct User
    {  string name; }
    User[] users;
    function foo() public{
      **User storage user=User("hey");**
     users.push(user);
    }
    function get() public view returns(string memory)
    {   return users[0].name; }
}

However when the above highlighted statement changed to the below statement will solve the error:
 User memory user=User("hey");

Can anyone explain the reason behind this changing from memory to storage?


texts:
In the Solidity documentation is stated that:

  The evaluation order of expressions is not specified (more formally, the order in which the children of one node in the expression tree are evaluated is not specified, but they are of course evaluated before the node itself). It is only guaranteed that statements are executed in order and short-circuiting for boolean expressions is done. See Order of Precedence of Operators for more information.

I want to better understand this point with the aid of an example.
Let's say I have a smart contract with  a function g that computes the sum of two inputs.

g(uint a, uint b) {
   return a + b;
}

...
uint res = g(x + 2, (x++) + 3);

Let us further suppose that x is equals to 5.
So, since the evaluation order is not guaranteed it is possible that the compiler will compile this instruction into two different piece of code:
either the actual parameter for a is evaluated before the one for b or the actual parameter for b before the one of a.
This will give raise to two different calls with different result:

g(7, 8)
g(8, 8)

Is this example correct? Why is this unsafe behavior kept in a language that is supposed to enable to write safe smart contracts?


texts: Ethereum block is active from 1 day and 15 hours

texts: my transacion status shown IN for to address. What does this mean? This transaction is in block for more than 1 day and 11 hours...Blok confirmation are increasing but i am not sure when it will credit to my account..


texts:
Can I put a lock on an already issued erc20 token?
I have issued a fixed erc20 and I want to know if it is possible to apply locku to smart contracts.


texts:
I have create a brownie project with automated tests according to this documentation:
https://vyper.readthedocs.io/en/stable/testing-contracts-brownie.html#writing-a-basic-test
Here is an example:
def test_set(storage_contract, accounts):
    storage_contract.set(10, {'from': accounts[0]})
    ...

As you can see, this line sends a transaction (calling set function). What i want to do is to limit gas units for this transaction.
Is there a way to do that just for this transaction ?
Thanks


texts: Is it possible to jump to an arbitrary location in a contract's bytecode?

texts:
The assembly for a smart contract looks like there is a single entry point and a series of if/thens or a switch to jump to the entry point of each function.

Is it possible to skip the lookup and jump straight to the function's code if you already know its offset?


texts: What is the exploit behind Parity's multisig wallet from 2017-07-19

texts:
Right now (2017-07-19, 10pm CEST), there is an alert from Parity that there is an ongoing exploit on their multisig wallet.

What is the cause and mechanism of this exploit?


texts: drizzle.contracts is empty object after creating new instance of Drizzle

texts:
After creating a new istance of Dirzzle and passing the needed options:

const drizzle = new Drizzle(options);

The object drizzle.contracts is an empty object instead of being an array of the contracts specified inside the options.
Because of that, trying to access the events of a contract by calling:

drizzle.contracts.MyContract.events

Will cause the error:

  TypeError: Cannot read property 'events' of undefined

This is because drizzle.contracts.MyContract is undefined. Since, drizzle.contracts is an empty object


texts: How can I select a single account in Ganache?

texts:
Ganache (v1.2.3) provides a list of 10 accounts.

They can be easily selected by selecting web3.eth.getAccounts();.

However web3.eth.accounts[0] returns undefined as shown below. Not sure how to
select just one account here.


texts: For sending a transaction to Ethereum, we need to be a "full node"?

texts:
If we only intend to send a transaction to Ethereum blockchain, do we need to be "full node" to have the entire blockchain? meaning that do we need to be "sync" with the blockchain to have the latest block?

Apparently when I send a transaction using Parity my transaction in not mined till I become "sync". I'm wrong? Or maybe just I need to be connected to some node whether I'm sync or not.


texts:
I have a doubt about the gas refund concept.
Imagine that I created a smart contract 1 month ago and now I want to call the SELFDESTRUCT
because I want to send the current balance to an address and stop using that smart contract. So far I understood that the gas refund will be deducted from the total gas cost of the transaction that is calling the SELFDESTRUCT, am I right? If not, how is the gas refund "payed"?


texts: Error: Transaction not confirmed for sendTransaction at rpc connection through http

texts:
I am trying to send a transaction to a contract deployed on the testnet.

I run the geth  HTTP JSON-RPC, with unlock option and the necessary apis accessible.

When I exec the web3.eth.sendTransaction from the console it seems to work fine.

However, that is not the case with the browser (using web3_extended library with chrome), nor with an http client I am using to debug. I get true when executing the web3.personal.unlockAccount in the browser (or send the json for the personal_unlockAccount in the http client).

But when I send the actual sendTransaction as:

 web3.eth.sendTransaction({from: accounts[0], to: contractAddress, data: methodData, gas: 2500000, gasPrice: web3.toWei(0.00001, "ether")}

I always get a 200OK response with:

{"id":1,"jsonrpc":"2.0","error":{"code":-32603,"message":"Transaction not confirmed"}}

Does anybody know what can be the actual problem?


texts: (UPDATED) Send signed transaction interacting with a contract

texts:
I have a local blockchain where I have deployed a contract. I want to interact with it sending multiple responses at the same time. For this propose, I cannot use Metamask to confirm each transaction. I need to create my own wallet and send the tx signed. I do not want to send a normal tx, I want to send a tx by calling a function in the contract.

For example:

pet-shop-tutorial. When you want to adopt a pet, you send a transaction from the .js file calling the adopt function with the account:

App.contracts.Adoption.deployed().then(function(instance) {
    adoptionInstance = instance;
    return adoptionInstance.adopt(petId, {from: account});
  })

How could I sign this kind of tx? Could anyone help me with this code?

UPDATED: I am using the following code to send a signed tx:

        var privateKey = "0xXX";
        var getdata = adoptionInstance.adopt(petId);
        var rawtx = {from: account, to: App.contracts.Adoption.address,  gas:2000000, data: getdata}
        var tx = new EthJS.Tx(rawtx);
        tx.sign(privateKey);

        var serializedtx = tx.serialize();

        web3.eth.sendSignedTransaction('0x' + serializedtx.toString('hex')).on('receipt', console.log);

I dont get any code error, but I have two problem cases:

1- If I keep MetaMask activated. I need to accept to send my tx from it and the tx is sent but never is confirmed.

2- If I desactivate Metamask. I get the following error in console:

Could anyone help me with this?


texts: How to still get notified of transaction using web3 after user exits from the browser

texts:
If I do something like

web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
    value:50,
    to:'0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BA1'
}, function(error, hash){
    //API call to backend and save history
});

The callback would not be called if the user refreshes browser. How do I make sure that I still get notified of the transaction even when the user refreshes browser?


texts: Correct approach of replicating smart contract balances

texts:
We are storing user balances on smart contract and as well as on our local db, so that we dont always have to query blockchain for user balance.

For this we use contract events to update balances but we observed that listening contract events are a hit or miss. In our cases 3 out of 5 events were missed by our node js server and thus leading to discrepancy in balances.

What is the correct approach of syncing balances between local db and smart contract balances.

How does these exchange companies manage that?


texts: Truffle artifacts are not being generated when compiling

texts:
I am new to smart contract development and I am trying to deploy my first contract. When running the truffle compile for the first time I can see that a build folder was generated on my project however after running truffle migrate the artifacts are not being generated inside the build folder.
xxxs-iMac dApp % truffle compile

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Other threads suggest a problem with writing permission however since the folder build is being created I assume this is not the issue. This is the first time I am deploying a smart contract so I also think it maybe something on my dev setup although i have correctly installed truffle and ganache dependencies via npm.
Truffle config :
    module.exports = {
    networks: {
        development: {
            host: "127.0.0.1",
            port: 8545,
            network_id: "*", // Match any network id
        },
    },
    plugins: ["solidity-coverage"],
};

2_deploy_contracts.js file:
const Voting = artifacts.require("./Voting");

module.exports = function (deployer) {
    deployer.deploy(Voting);
};


texts: Possible problems concerning the update of token standards such as ERC20 token

texts:
I am new to crypto. I want to ask if in the future, ERC20 Tokens become outdated, will there be a recycle  (or some kinds of buyback or repurchase ?) of old tokens or an automatic update (perhaps done alongside with wallet software update, just guessing)? What if I hold a particular cryptocurrency long enough , say the crypto use ERC 20 tokens standard, will the market price of the cryptocurrency using old token standard drop to zero since the technology become outdated?
I know many crypto projects use ERC 20 TOKEN Standard,such as BNB , LINK. So how exactly do these crypto projects keep up with the updated standards or protocol while maintaining the market price and  how ethereum community and developers deal with these problems.
Any help to enlighten me is appreciated! thank you so much.
My later thought:
Is it right that what matters is the private key and "the public ledger". We don't have to worry about any software or hardware update?Is my thought correct?


texts: Do you need to publish the contract ABI and address for others to interact with the contract?

texts:
Suppose you write a contract that you want others to interact with.  My understanding is that if you want others to interact with your contract, you need to provide the contract's ABI and address.  Is this correct?

If so, would you then publish the contract's ABI and address at a specific place for people to use, so they can interact with it?  Would you publish the code so people could compile the contract and get the ABI?

OR, is it possible to interact with a contract by just knowing it's address/hash.


texts:
I am trying to read the token balance of a certain address as well as reading the amount of ETH that has been sent to a smart contract from that address.

Currently I have:

var web3 = new Web3(new
Web3.providers.HttpProvider('https://ropsten.infura.io/'));

abi = JSON.parse('[{"constant":true,"inputs":
[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]');
TokenContract = web3.eth.contract(abi);

contractInstance = TokenContract.at('[TOKEN CONTRACT ADDRESS]');
var balance = contractInstance.balanceOf(userAddress);

The abi is a standard ERC20 abi, but balanceOf returns an object (r {s: 1, e: 0, c: Array(1)}), shouldn't it return an integer? How should I get the token balance from this?


texts: Better open source blockchain explorer for Quorum blockchain

texts: I was looking for open source blockchain explorers for Quorum blockchain other than https://github.com/blk-io/blk-explorer-free, Thanks


texts:
I need help with adding a new wallet to a web3 instance.
e.g.:

web3 = new Web3(new Web3.providers.HttpProvider(connectionString));
const account = await web3.eth.accounts.privateKeyToAccount('0x'+pvKey);
await web3.eth.accounts.wallet.add(account);
console.log(await web3.eth.getAccounts()); // return []..

as you can see, there is no account added to the web3.eth.accounts instance.
I need to see the new address added to the accounts list.

web3@1.0.0-beta.36.
pow blockchain network.
Node v8.11.4

any clue?


texts:
Since a smart contract executes code, is it possible to execute malicious code, introduce bugs and generaly create problems for the platform?

If yes, how can this be avoided?


texts:
I have read https://swarm-guide.readthedocs.io/en/latest/up-and-download.html.
But it does not make sense. So I want to ask a few questions.

After syncing geth and swarm, I uploaded the data to swarm.
The data then exists as a chunk. Are these chunks stored in geth's block? Or where are they stored and provided to the nodes?

2.
Where can I find chunks?

3.
Where is my uploaded data stored on my computer?


texts: How to raise version of oraclize-api installed via Truffle

texts:
I'm using local instance of Oraclize API, to make truffle compile work. I've installed it by

truffle install oraclize-api

but for now, I'm getting following error

  if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1,
  sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
                                                ^--------------------------------------------^

Looks like I'm getting it because version of usingOraclize is ^0.4.18, and I use ^0.4.24 for my project. Does anyone know how to solve this issue?


texts: How to check for duplicate addresses in mapping

texts:
I want to have a mapping where it is only possible to add values when they are UNIQUE. It must not be possible to add duplicate keys, but I cannot get it working.

The code:

contract test {
    mapping(string => address) values;

    function AddValue(string randomValue) {
        require(values[randomValue] == 0x0);

        //execute transaction if randomValue doesn't exist
        //cancel transaction - payout if the randomValue exists
    }
}

In this example I am trying to check whether the values[randomValue] is empty - doesn't exist.
If it doesn't exist the code after may execute. If it DOES exist, the code must stop.
However, I am unable to find a solution.


texts:
I have a geth-based ethereum installation that started crashing with "Missing trie node" errors. In the chaindata folder I have hundreds of ldb files, nearly all of which are around 2.1Mb - but the most recent one, started yesterday, is 151Mb, suggesting something has gone astray in it. It then turns out that transactions were not syncing to other nodes in my network, so this is my only copy of the data. The corrupted file means that geth will not start, but that also means that the other (non-corrupted) transactions in older files are inaccessible.

How can I recover those transactions? Can I import individual ldb files directly into a new setup rather than the whole chain data folder? Can I remove the problem file without breaking things too much?


texts: Acquired Ether in the presale. Using Mist, how do I split into ETH and ETC?

texts: Acquired Ether in the presale. Using Mist, transferred ETH into an account. How do I split into ETH and ETC? Want to take the ETC to an exchange. Thx.


texts: How can I estimate the time remaining to complete a sync?

texts: I would like to know approximately how long it will take my geth node to complete syncing.  There was a previous question that was similar to mine, but less specific, and it was closed in favor of a question about how to get the highest block number.  Since it was not possible to add an answer to the closed question, and the other question does not answer my question, I am asking this version of the question.


texts:
I have posted a transaction with a very low gas fee (11 gwei) to the txn pool. Speed wasn't an issue and I can wait for the txn to post.
This was 24 hours ago, and the txn is still pending.
Currently, ethgasstation dot info states that 24% of the last 200 blocks have accepted txn's at 11 gwei and 20% of the last 200 blocks have accepted txns at 8 gwei.
Is ethgasstation accurate? If 8 gwei transactions have been added in the last 200 blocks, why is my 11 gwei transaction still pending?


texts: Card Game - Smart Contract (Public Cards)

texts:
We want to implement a card game with EVM and Smart Contracts. After defining all-important game information we asked ourselves how we can include the cards in the Smart Contract but don't make it public for all the Users interacting with the Contract.

The Game is based on betting per round, so the Users need to see their cards first to decide which amount of ether they want to invest.

So basically we want to include the dealt cards so that the Players can't change them.

Is it possible to decrypt the cards in the contract?


texts: Is it possible to convert Ethereum merkle patricia trie to [{address: balance}, {address: balance}, {address: balance}... ]?

texts: From Merkle Patiricia Trie, seems to be difficult to get all keys, so the only way to make [{address: balance}, {address: balance}, {address: balance}... ]  for all accounts (including contracts), need to watch when function put called ?


texts: decode a transaction receipt which does not have an event log


texts:
I have an ERC20 Token that i have deployed and now have transferred it to about 100 addresses. Now the price shown on my Etherscan for my token is $0.00. When i search through the top ERC20token like BNB and all. They have there worth written like $16 per token.

How does a token become worth something on the etherscan ? Who decides this price and how does it fluctuate in the market ?


texts: Possible to get event logs from a specific pending transaction?

texts: So I'm using web3 py filtering and it looks like I can listen for event logs using a filter, but I don't know which transactions in the pending pool produced the logs.  Similarly, I can use getTransactionReceipt to get the event logs from a completed transaction, but it doesn't seem I can combine the two and get event logs of a pending transaction (it says transaction not found when I try).  Is there any way to do this?


texts: How test POA consusus that only authorized sealer can seal the block. How to run test cases ?


texts:
I am currently taking a course in Solidity and we get presented with weekly challenges that we should try to solve.
This time the general topic is SafeMath and the challenge looks the following:

contract HopAndMaltOracle{
    // Contract oracle
    address public oracle;

   modifier onlyOracle(){
        require(msg.sender == oracle);
       _;
    }
    uint public maltMarketCap;
    uint public hopMarketCap;

    // Callback function
    event MaltMarketCapChanged();
    event HopMarketCapChanged();

    constructor(uint _maltCap, uint _hopCap) public payable {
        oracle = msg.sender;
        maltMarketCap = _maltCap;
        hopMarketCap = _hopCap;
        emit MaltMarketCapChanged();
        emit HopMarketCapChanged();
    }

    function updateMaltMarketCap(uint _cap) public onlyOracle {
        maltMarketCap = _cap;
        emit MaltMarketCapChanged();
    }

    function updateHopMarketCap(uint _cap) public onlyOracle {
        hopMarketCap = _cap;
        emit HopMarketCapChanged();
    }

    function IDidIt() public{
        require(address(this).balance % 2 == 1);
        msg.sender.transfer(address(this).balance);
    }
}

The goal is to reduce the balance of the contract to 0 (by somehow calling IDidIt()). Now looking at the contract it seems to me like none of the methods can be invoked since all of them are either using the onlyOracle modifier or are the constructor (except for IDidIt() ).

My idea would be to send Ether to the contract in order to increase the balance to something that would satisfy

require(address(this).balance % 2 == 1);

but I can't find a way to do so since the fallback function is not acceppting my payments (tried with:

eth.sendTransaction({from:myAddress,to:contractAddress,value:1});

The starting balance of the contract is 2 Ether.
I am not asking for a solution, but a nudge in the right direction would definitely help :)


texts:
I'm writing a Dapp, which connect the ether web3 provided by metamask.

How should I handle the response from contract method? I mean some methods that doesn't need to send a transaction.

for example, In my contract there's a public uint field and a public address field.

the code to get the uint field

contractIns.uintField(function(err, result){
     if(err){
         //error
     } else {
         //the data is in result.c[0];
     }
});

however, the code to get the address field

contractIns.addressField(function(err, result) {
     if(err){
         //error
     } else {
         //the result is the data itself
     }
});

I mean, is there any documentation about the format of return value format?


texts: How to approve user to spend all my ERC20 tokens?

texts: In ERC20 we approve a user to spend our token and then they can spend as much allowed using transferFrom, but if the allowance limit exceed then I have to approve again, is there any way to allow them to spend all tokens? I mean have to approve a account only once


texts: Error deploying Ethereum contract: The transaction from "Account Name" to undefined couldn't be successfully executed

texts:
I'm going through the tutorial in Ethereum website and trying to Deploy a contract to TESTNET, copied from the Ethereum page.

When I deploy it, it errors out:

"The transaction from Test Contract Account to undefined couldn't be successfully executed"

Same this happens when I transfer Ethers between my TESTNET accounts.

Here is the contract code:

pragma solidity ^0.4.2;

contract AramCoin {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
    string public name;
    string public symbol;
    uint8 public decimals;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function AramCoin(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) {
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
        name = tokenName;                                   // Set the name for display purposes
        symbol = tokenSymbol;                               // Set the symbol for display purposes
        decimals = decimalUnits;                            // Amount of decimals for display purposes
    }

    /* Send coins */
    function transfer(address _to, uint256 _value)
    {
        if (balanceOf[msg.sender] < _value)
            throw;           // Check if the sender has enough

        if (balanceOf[_to] + _value < balanceOf[_to])
            throw; // Check for overflows

        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient

        /* Notify anyone listening that this transfer took place */
        Transfer(msg.sender, _to, _value);

    }

    event Transfer(address indexed from, address indexed to, uint256 value);

}


texts: Implementation of Oraclize callback tests with Truffle/Mocha

texts:
I'm trying to write tests in Mocha/JS with Truffle for a Solidity function that uses Oraclize. I want to test if the result in the callback of my Oraclize query is correct. As Oraclize needs some time to process the query I need to wait for the response of the transaction. Right now I'm achieving this with a setTimeout function to wait for the callback transaction. Setting a timeout might require me to wait longer then necessary or even make the test fail if the timeout is set too low. Is there a better way to achieve this?

I am using Truffle 3.2.1 with TestRPC 3.0.5 and ethereum-bridge 0.4.21.

Here is the JS test code snippet:

it("Request computation and send results to Arbiter", function(done) {
  this.timeout(250000);
  var computation;
  var result;
  ComputationService.deployed().then(function(instance) {
    computation = instance;
    return computation.compute("43543", "423543543", 0, 56347573485346, {from:accounts[0], gas: 500000, value: web3.toWei(0.01, "ether")});
  }).then(function(){
    return new Promise(resolve => setTimeout(resolve, 240000));
  }).then(function(){
    return computation.getResult(56347573485346);
  }).then(function(value){
    result = value;
    assert.equal(result, "18442356492849", "The result is wrong (should be 18442356492849)");
    done();
  });
});

This is the Solidity callback function with a newResult event:

function __callback(bytes32 _oraclizeID, string _result) {
  if (msg.sender != oraclize_cbAddress()) throw;
  newResult(_result);
  requestOraclize[_oraclizeID].result = _result;
}


texts: Is there a Vyper equivalent to OpenZeppelin's SafeERC20.safeTransfer?

texts: OpenZeppelin provides the SafeERC20 Solidity library as a way to handle the possible variations of ERC20. Is there an equivalent way to do this using Vyper?


texts: Token totalsupply displaying zero at etherscan but displays correctly at remix

texts:
I verified and deployed a token contract using remix. The totalsupply displays correctly 80000000000 but at etherscan it displays the totalsupply as 0.0000000008.

Summary [ERC-20]
Total Supply:   0.00000011 WIMT ($0.00)
Price:  $0.0000 @ 0.000000 Eth

here is the link https://etherscan.io/token/0x258c6b5e54565a20d925c4b9cdbd97239e3ac3bf

but at etherscan here it displays correctly

We found a Contract With ERC-20 Token Transfer Events

Token 0x258c6b5e54565a20d925c4b9cdbd97239e3ac3bf
On-chain Token Attributes Check Result:
 Total Supply = 110000000000
 Name = WIMT
 Symbol = WIMT
 Decimals = 18
 ERC-165 Interface = {Not Available}
 Implements ERC-721 = No

here is the link https://etherscan.io/tokens?q=0x258c6b5e54565a20d925c4b9cdbd97239e3ac3bf

How do i correct this without redeploying the contract? Thank for your help.


texts: Trying to input big array (500+) of addresses as argument

texts:
I have an airdrop function that allow the owner input array of addresses and an amount to give. It work well with small number of addresses about (100) but bigger than that, gaz limit is reached.

I wonder, is it my code that block that or just the fact that it cost X amount to airdrop X token multiply by the array length so it's just costing a lot to send and the gaz limit really reached?

I tried to find answer here and over the web but I'm not sure how to format my question. Like, is there any limit of an address array as argument?

Here is my code :

function airDrop(address[] recipients,uint amount ) public {

      require(msg.sender == owner);
          require(amount > 0);

         uint256 supposedDropAmount = (recipients.length).mul(amount);
      //be sure it's not over the limit

      uint256 checkedSupply = dropAmount.add(supposedDropAmount);

      // return money if something goes wrong

     require(checkedSupply <= AirdropCap); // block airdrop

      //require date time
       require(now > airdropTime);

      for( uint256 i = 0 ; i < recipients.length ; i++ ) {

           assert(token.mint(recipients[i], amount));
          emit  TokenDrop( recipients[i], amount );
      }
    numDrops = numDrops.add(recipients.length);
    dropAmount = dropAmount.add(recipients.length.mul(amount));
}

Notice the token.mint is external in another contract, and that airdropTime is much in the past than now. As I said, it work with small array of address.


texts: Is there a PPA or Repository for Ethereum?

texts: Is there a PPA or Repository we can add to our system so that we receive automatic updates to our Ethereum software in GNU + Linux?


texts:
I wanted to know the integration state of ERP system (like SAP) and Ethereum.

Is there an API that allow a smart contract to fetch information from a ERP to store that data?

Thanks in advance

Best!


texts: How to infer token price from ethereum blockchain UniSwap data?

texts:
I would like (if possible) to infer a token price from the blockchain using UniSwap data.
After reading the following article, I understood that it is feasible:

https://blocklytics.org/blog/uniswap-api/

  “The price of a given token on a given exchange can be calculated as
  the exchange contract's token_balance divided by its ether_balance.”

My first attempt was to check some transaction data, for example this transaction:
https://etherscan.io/tx/0x10de93fd474b5c45035ea5d9ef42172ba6026e024cf77275a72c2b291b118a6d

This page explains in a more readable way (for me) the transaction:
https://etherscan.io/address/0x2bf5a5ba29e60682fc56b2fcf9ce07bef4f6196f#events

I understand we have:

uint256 tokens_sold
25661215840000000000
uint256 eth_bought
3014603688879169830

So this would mean a ratio of:
25661215840000000000 / 3014603688879169830 = 8.512302
For this token swap NMR / ETH.

This seems close to the current ration between these two tokens (prices from CoinMarketCap this morning):
203.64 / 23.77 = 8.567101

Is this approach correct?

Also, when I look at the same transaction data in BigQuery, I get:

Input = 0x95e3c50b000000000000000000000000000000000000000000000001641ef3d8f7d3c00000000000000000000000000000000000000000000000000029a07940a8276bdd000000000000000000000000000000000000000000000000000000005ecbd296

which I can decompose into:

0x95e3c50b = MethodID

000000000000000000000000000000000000000000000001641ef3d8f7d3c000
 = 25661215840000000000 in Decimal
This seems fine: I find the same tokens_sold as above.

00000000000000000000000000000000000000000000000029a07940a8276bdd
 = 2999530670434773981
What is this?

000000000000000000000000000000000000000000000000000000005ecbd296
 = 1590416022
What is this?

I am struggling to find the same eth_bought amount as above: 3014603688879169830.

Can someone help?


texts:
Wouldn't a dapp deployed on IPFS + "link" (the hash of the dapp) to the dapp on the blockchain act exactly like a smart contract?

I make this statement, because the app would be immutable due to IPFS and the "link" to the app would be also immutable too, due to how blockchains work. This is exactly like with a smart contract. The smart contract is also immutable. And this would remove the necessity to store the smart contract code on the blockchain.

Is this a fallacy?


texts:
I have tried to use ecrecover() to verify the signature of a message.

I have looked at lots of references here and elsewhere, like:

https://lab-blog.ey.com/2016/12/19/ecrecover/
How does one properly use ecrecover to verify Ethereum signatures?
Ethereum ecrecover signature verification and encryption

and others.

But I still cannot get ecrecover() to return the signing address. So I am hoping that someone can point out some stupid mistake I am making.

Here is my code:

pragma solidity ^0.4.0;

contract test {

  function test() {
  }

  function verify(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s) constant returns (address) {
   address signer = ecrecover(_message, _v, _r, _s);
   return signer;
  }
}

Then in geth, I do:

> var msg = web3.sha3("hello")
"0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"

> eth.accounts[0] -->
"0x7156526fbd7a3c72969b54f64e42c10fbb768c8a"

> var sig = eth.sign(eth.accounts[0], msg)
"0x9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada1c"

> var r = sig.substr(0,66)
"0x9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac8038825608"

> var s = "0x" + sig.substr(66,64)
"0x4f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada"

> var v = 28
28

> test.verify(msg,v,r,s)
"0x33692ee5cbf7ecdb8ca43ec9e815c47f3db8cd11"

...which of course, is NOT eth.accounts[0]

I am totally stumped. Is there anyone who can see what I am doing wrong?


texts: Error importing transaction: Transaction(InvalidChainId) in Private POA

texts:
Problem

I am trying to send some transactions to my private chain, and all transactions are getting failed. I am receiving this error:

Error importing transaction: Transaction(InvalidChainId)

Environment

I am starting a private chain and defined networkID in the genesis file inside params as:

"networkID" : "0xB8A081"

While starting the node, I am specifying the networkID in the toml file as

[network]
id = 12099713

After restarting everything, I reconnect metamask to my RPC and then send transaction using remix and metamask.


texts: How to prove that a user owns their public key for free?

texts:
If a user claims to own a public key is there a way that I can query metamask or a web3 object and say "hey this guy is telling me that he owns this public key is that true?"

I could ask the user to send me 0 eth as a proof, but then this requires them burning gas.

Thanks!


texts: Remix testing timeout with JavaScript VM when calling a large array

texts:
I'm trying to test a contract getter method that returns a large array. I am using Remix and deploying using JavaScript VM. My contract deploys alright, but trying to call the getArray() method causes Remix to freeze and show a timeout page.

pragma solidity ^0.4.24;
contract myContract{
        bytes32[7500] public array;
        function getArray() public view returns(bytes32[7500]){
            return array;
        }
}

I also have a similar problem when testing the web3 library in Mocha with ganache-cli provider.

However, When I deploy using Injected Web3 to Rinkeby, Remix returns the large array just fine. Is this timeout some sort of limitation of the JS VM? Thanks.


texts: Is it possible to transfer the balance of a contract from another contract?

texts:
contract A{

address public seller;

function A(){
    seller = 0xdd870fa1b7c4700f2bd7f44238821c26f7392148;
 }

function transfer_from_B(address b){

 seller.transfer(b.balance);//ERROR
}
}

 contract B{
   function deposit() payable{
 }

 }

I get an error when I try to transfer the balance of contract B from Contract A. Is it not possible to do that?


texts: Smart contracts calling each other, costs and atomicity doubt

texts:
According to what I know, If you invoke function F on Contract C, you pay the gas fees related to F's operations and if for some reason something goes wrong, all state changes performed by F until that point are revoked. F works in an atomic way and the human being account that invoked F pays for the gas fees (even if operations are rolled-back).
The doubt I have comes from a situation in which F invokes some other function F1 on Contract C1, which can invoke some other function F2 on Contract C2 and so on....
human -> (C) F -> (C1) F1 -> (C2) F2 -> ...
First of all, it is my understanding that the original account would only pay for the gas fees of operations performed by F, then it would by C who pays gas fees for operations performed by F1, C1 would pay for operations on F2 on so on....
But what if Fn fails? would all state modifications performed by F up to Fn-1 be rolled-back? would the original account as well as contracts from C up to Cn-1 waste their gas fees?


texts: How To Verify A Coin Without Original Contract Source Code?

texts:
We are new to crypto. A while ago we created a coin (3DOM coin) with 14,000,000,000 units and stored them in our wallet on myetherwallet.com. We would like to deploy the token now but we do not have the original source code for the contract we used. We have the address of the wallet where the tokens are held, the private key for the wallet as well the contract ID, but we are having trouble filling out the following screen to verify. We do not know the original compiler type, etc.  Can we verify the contract with any arbitrary compiler selection? Is it possible to redo the contract with the same parameters?
https://etherscan.io/verifyContract

Any help appreciated.
All the Best,
Dan


texts: Why there no Sender address mentioned in newTransaction() function?

texts:
I have doubt regarding the newTransaction() function in the transaction.go file in go-ethereum. Why there is no mention of sender's address in the newTransaction() function? From where does it get sender's address?

Here is the code:

func newTransaction(nonce uint64, to common.Address, amount, gasLimit,gasPrice big.Int, data []byte) *Transaction {
    if len(data) > 0 {
       data = common.CopyBytes(data)
    }
    d := txdata{
            AccountNonce: nonce,
            Recipient: to,
            Payload: data,
            Amount: new(big.Int),
            GasLimit: new(big.Int),
            Price: new(big.Int),
            V: new(big.Int),
            R: new(big.Int),
            S: new(big.Int),
    }
    if amount != nil {
        d.Amount.Set(amount)
    }
    if gasLimit != nil {
       d.GasLimit.Set(gasLimit)
    }
    if gasPrice != nil {
       d.Price.Set(gasPrice)
    }

return &Transaction{data: d}
}


texts: SPDX license when importing other people's contracts

texts:
Since Solidity 0.6.8, the compiler started throwing warnings if a contract isn't annotated with a SPDX license identifier:
// SPDX-License-Identifier: MIT

contract MyContract {
    ...
}

Suppose that I'm importing third-party contracts, like those from OpenZeppelin or the UnorderedKeySet library built by Rob Hitchens. I will eventually want to verify the source code of my contracts on Etherscan, and it's common to flatten the contracts before doing that. How should I handle the SPDX identifiers in this case?
It it ok for a flattened file to contain multiple SPDX identifiers?


texts: How do I send ether from user address to smart contract address using a function/method (without using msg.value)?

texts:
I am relatively new to programming in solidity and trying to build my own auction platform for demonstrational purposes. What I am trying to do is, to send ETH to a contract and whenever the auction ends, the funds will get re transferred to the auctioneer. I am trying to make a small test contract which only does the payment to the smart contract and allows refund to users. The process of making a payment to the smart contract using a function however, does not work. This is the code I am using:

    pragma solidity ^0.5.6;

contract testContract {

    constructor () public payable{
    }

    function transferFunds () external payable {
      // this method supposed to send ether to the contract address, however it doesnt
        address(this).transfer(1 ether);

    }
    function refund () external payable {
        msg.sender.transfer(address(this).balance);
    }

    function showBalance ()  public returns  (uint256){
        return  address(this).balance;
    }
    function returnContractAdress () public returns (address){
       return address(this);
    }
}

The error I get is that address(this) is not a payable address, however I read online that it supposed to be a payable address. Whenever I try to convert it to a payable address it doesnt work. I spend so much time reading post on stackexchange and overflow but cant seem to figure out a solution. Can someone help me out?

To clarify, this is what I am trying to build:


texts: Can't deploy contract, does not recognize my 1 ETH

texts:
The console says:

  We can't estimate your gas usage properly, because you need at least 1 ether in your account

Select fee is frozen. There is one ether listed at the top of the console.


texts: How do I get the return uint value of a method in Solidity contract from another contract

texts:
Trying to get the return function of a contract from another contract. Don't know what I am doing wrong.

I can see the return value when I call contract A directly but when I try calling the function from Contract A, it does not work.

contract A{
  function validateSchedule(uint scheduleId)
    public
    view
    returns(uint)
  {
    uint amount = schedules[scheduleId].amount;
    return amount;
  }
}

Here is the second contract

import "./A.sol";

Contract B is A{

  A Multisig;

  function verifySchedule(uint scheduleid)
        public
        view
        returns (uint)
        {
        uint amount = Multisig.validateSchedule(scheduleid);
        return amount;
         }
}


texts: How to disable deployment of smart contracts on besu private network?

texts:
Is there any way to disable creation of smart contracts on Hyperledger Besu Private Network for addresses except those that I specify? I want to create private network with zero gas fee, but no one can deploy smart contracts except me.
Or is there a way for besu to specify what opcodes costs gas, so i could set all opcodes to be zero gas, but CREATE opcode to cost gas?


texts: Insufficient funds for gas * price + value web3 sendSignedTransaction

texts:
My wallet balance is 3.994937 RIN and I have set value (to be sent) to 0.00005 RIN (50000000000000 Wei) and I have set both gasPrice to 5208 (21000)and gas Limit to 5208 (21000 Wei).

ChainId=4

However, I am getting the following error (as in the console):

insufficient funds for gas * price + value

Signed transaction I am trying to broadcast:

0xf86780825208825208948f87d70db715ae66bad98e6f36a06e4539450a3c862d79883d2000802ba057d0655b6cd90831248058c9bc9a92f10db321ee6f97fca3359f2c0f33e07005a06dd7c20022c11698a9be524845d8caac9944c833db27242470f15ccf9d4e5986


texts: Does solidity transfer command require fee

texts:
If I use the transfer command in solidity, for example:
redeemer.transfer(amount);

is there a fee involved?
That is, is a fee taken out from amount; or rather an extra fee taken from the contract invoking this command to cover the transfer?


texts: Smart contract to get around data manipulation?

texts: Please correct me if I'm wrong. I'm just curious as to how much smart contracts can do. I'm not too familiar with public key cryptography, but my current understanding is that it is possible for A to send encrypted messages to B using B's public key. (Whether this data be stored within a transaction or a smart contract.) If another individual C wants to pay B for this message, is it possible to write a smart contract which unlocks the same encrypted message but this time encrypted with C's public key upon C sending a transaction to B, without any manipulation by B? Or is it only possible to confirm that the message has not been manipulated by B if A is also privy to this smart contract?


texts:
I am trying to update geth. I have followed this guide: https://ethereum.stackexchange.com/a/2088/4575

When I do: git pull: I have face with following error.

From https://github.com/ethereum/go-ethereum
   dd06c8584..e7610eadf  master      -> origin/master
   021c3c281..ab5646c53  release/1.6 -> origin/release/1.6
 * [new branch]          release/1.7 -> origin/release/1.7
 * [new tag]             v1.6.7      -> v1.6.7
 * [new tag]             v1.7.3      -> v1.7.3
 * [new tag]             v1.6.2      -> v1.6.2
 * [new tag]             v1.6.3      -> v1.6.3
 * [new tag]             v1.6.4      -> v1.6.4
 * [new tag]             v1.6.5      -> v1.6.5
 * [new tag]             v1.6.6      -> v1.6.6
 * [new tag]             v1.7.0      -> v1.7.0
 * [new tag]             v1.7.1      -> v1.7.1
 * [new tag]             v1.7.2      -> v1.7.2
You are not currently on a branch.
Please specify which branch you want to merge with.

[Q] What should I do to overcome this error? Please note that I am not well experience on git, sorry about that.

Thank you for your valuable time and help.


texts: All geth nodes getting the same enode id

texts:
I have a script to setup a geth Ethereum node which has worked well for me most of the time. (been using it for the last 2-3 weeks). I have used it regularly to setup multiple geth instances on different docker instances.

However, today, when I created some nodes on different docker instances (all running on same box), I saw issues. For starters, the 2 nodes are unable to talk to each other when I use admin.addPeer(). Mining doesnt work either. On investigation, I figured out all the nodes created have the same enode id.

This is a bizzare issue - seeing it for the first time. I made no changes in my script or how I start the multiple geth instances. Anything I can do to prevent this? I tried using bootnode also as follows -

bootnode -genkey boot.key
bootnode -nodekey boot.key

INFO [10-11|08:51:32.325] UDP listener up                          self=enode://e3e9eec5fad93a169f7667905733d831f9e6c9ad233fcf2430dd65d8822c688310784f1b3c8bba38e1037bab1916b1e755124ff6973d752fed8912c6e2ba2569@[::]:30301

I expect to see the above id picked up when I do geth --bootnodes

However, I see something totally different.

Any suggestions.

Thanks!


texts:
I recently tried to get geth and solidity up and running on a virtual server I have some free time on.

I got stuck trying to build the Solidity compiler due to issues with the OpenGL library. I've been told this is due to the fact that most virtual servers don't have graphics cards, which makes sense. I know there are some workarounds for getting OpenGL running, but I feel perhaps I'm just missing something.

What is the standard for ethereum? What environments do most people use?


texts: Confused with how example contract successfully calls external contract

texts:
I'm trying to learn Solidity and I came across the following 2 contracts:

https://github.com/fivedogit/solidity-baby-steps/blob/master/contracts/45_pong.sol
https://github.com/fivedogit/solidity-baby-steps/blob/master/contracts/45_ping.sol

The contract pong holds some value, and the contract ping is supposed to be able to access this value via the getPongvalTransactional function.  I'm confused with how this function works (disclaimer: I have no background in object oriented programming).

If I understand correctly, in the ping contract, all contracts of type PongvalRetriever contain a function called getPongvalTransactional which returns -1.  The pong contract address is declared to be a contract of type PongvalRetriever.

However, the pong contract also contains a function called getPongvalTransactional which returns the actual value we want.  In following line of the ping contract

function getPongvalRemote()
{
    pongval = pvr.getPongvalTransactional();
}

why does pongval equal the actual pong value instead of -1?


texts: Can I make a token with a different transaction protocol?

texts: Is it possible to issue a token that can be sent only using a different protocol, say for example ring signature?


texts: Is it possible to make multiple function calls in a single transaction?

texts: Say I want to make a transaction that calls foo() and the calls bar() afterwards. I could make a contract that calls them both in sequence, but that's kind of a pain. Is there a way to just call both without prompting the user for multiple signatures? And if so will foo() revert if bar() reverts and vice versa?


texts:
The swarm roadmap suggests that the orange paper series and a landing page is released on swarm.

There is also an internet gateway for swarm: http://swarm-gateways.net/bzz:/theswarm.eth/

But how to access content hosted on swarm using the bzz:// protocol natively?


texts: Where can I find some Solidity / Smart Contract source code examples?

texts:
Is there an easy to access list of Solidity / Smart Contracts / Dapps source code examples?

Related information:

Is there a list of DAPPS that are already useable?
Where can I learn how to develop DApps using the solidity programming language?


texts:
I've done a lot of searching and found lots of information on how to create an Ethereum private testnet and etc, as well as connecting to the newly created Ethereum private testnet through geth in the terminal and etc, but this is not my question.

My mist app (OSX) already has/had a "solo network" option when I downloaded it, as well as the Main Network, Robsten, and Rinkeby, as you can see here. You will also see that I am currently connected to the solo network in Mist.

I do not know, nor can find any information on how to find the chaindata and private keys and etc for the solo network, because when I navigate to the location where the other private keys and etc are located for the other networks (/Users/username/Library/Ethereum/), the solo network is not there. (see here). So my question is, where is it located?? I can't seem to find it but I know its there because I have and am using it on Mist.

The reason I want to find the location is to connect to it with geth in terminal, and experiment with geth in the terminal and etc.

There might be an obvious answer I've somehow missed, please share!

Thanks.


texts: How to handle exceptions in ethreum private network using revert(),throw

texts:
I am running a private ethereum network using

 geth  --rpc  --rpccorsdomain "*" --datadir ./chaindata --port "30330" --nodiscover --rpcapi "db,th,net,web3" --networkid 2010 init genesis.json

and then

geth  --rpc  --rpccorsdomain "*" --datadir ./chaindata --port "30330" --gasprice 1 --nodiscover --rpcapi "db,eth,net,web3" --networkid 2010 console

when I calls a contract functions

 function checkValid( string Name)public returns(bool)
{
    if(isvaliduser[Name]==false)revert();
    Count[Name]+=1;
 }

Which is deployed in remix solidity IDE, in web3 provider environment, I have given wrong parameters in order to call revert .The functions does not get executed and stays in transaction pending.

But my problem is : Now after giving correct parameters also function do not execute, what can be the reason.

Any help will be highly appreciated.


texts: Calculate Private Proof-of-Authority TPS

texts: With a private Ethereum Proof-of-Authority network set up containing 3 sealer nodes, what can we do to estimate the TPS (Transactions per second) of the POA network?


texts:
I have write a small smart contract. however there is problem. please see below full code
pragma solidity ^0.5.16;

import "./x.sol";

contract xSale {
address admin;
x public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;

event Sell(address _buyer, uint256 _amount);

constructor (x _tokenContract, uint256 _tokenPrice) public {
    admin = msg.sender;
    tokenContract = _tokenContract;
    tokenPrice = _tokenPrice;
}

function multiply(uint x, uint y) internal pure returns (uint z) {
    require(y == 0 || (z = x * y) / y == x);
}

function buyTokens(uint256 _numberOfTokens) public payable {
    require(msg.value == multiply(_numberOfTokens, tokenPrice));
    require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
    require(tokenContract.transfer(msg.sender, _numberOfTokens));

    tokensSold += _numberOfTokens;

    emit Sell(msg.sender, _numberOfTokens);
}

function endSale() public {
    require(msg.sender == admin);
    require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

    // UPDATE: Let's not destroy the contract here
    // Just transfer the balance to the admin

    admin.transfer(address payable(this).balance);
    }
}

getting error
xSale.sol:40:32: ParserError: Expected ',' but got 'payable'
admin.transfer(address payable(this).balance);
^-----^


texts:
When I do geth attach I see the following:

$ ./geth attach
Welcome to the Geth JavaScript console!

instance: Geth/v1.7.1-stable-05101641/linux-amd64/go1.9
coinbase: 0xe26fxxxxxxxxxxxxxxxxxxdbe630202
at block: 0 (Wed, 31 Dec 1969 19:00:00 EST)
datadir: /home/test/.ethereum
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

And the coinbase value I see is not my Wallet account on coinbase. Why is there some different address here?


texts:
I installed Mist and synced the blockchain. When Mist opens,it connects to the main net by default. If I try to switch to the test network, I get an error shown on the picture below. Can anyone suggest how to get over this problem?

Thanks!


texts: What does “⑂ block became a side fork” mean in Geth?

texts:
Two Geth nodes were mining in the same private net, and one of them gave ⑂ block became a side fork. I don't get what it means.

I'm new in Ethereum. I'd appreciate it if you give me an explanation for newbies.


texts: Call geth functions through smart contracts

texts:
Is there any method in which I can call geth functions like personal.newAccount('abc') through a smart contract?

If yes, how?


texts: Watching for changes in web3.isConnected()

texts:
I am using Meteor & Web3 to talk to a Geth node, and would like to have an event fire in web3 when the Geth node goes down.

Web3 has the ability to add callbacks to web3.eth.isSyncing to detect changes, but web3.eth.isConnected does not.

How can I detect changes in web3.eth.isConnected without having to use continuous polling?


texts: Sent SALT tokens to Cindicator (CND) contract address by mistake

texts:
I sent SALT tokens to Cindicator (CND) contract address by mistake. Is it possible to recover the tokens. Below is the transaction hash
0xbfe1b24ddef1ac36b646c7e6bbd87f8fe9401dcd856b74691780b15865c10392

I see the following method in the CND contract source https://etherscan.io/address/0xd4c435f5b09f855c3317c8524cb1f586e42795fa#code

/// @notice This method can be used by the controller to extract mistakenly
///  sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
///  set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {

Does this mean the contract owner can return my SALT tokens?. Someone please help here.


texts: Possibility of detecting MAC address spoofing in Ethereum network?

texts:
The paper that has been published here: https://dl.acm.org/citation.cfm?id=3282283 proposes a consensus algorithm based on distributed voting process as an alternative to proof-of-work based blockchains, in which it claims that it would be possible to detect and recognize (and not prevent) MAC address change using Cisco Port Security in a crypto-currency network, because this proposed idea is based on one-machine-one-vote and so it is important to recognize MAC address change in the network.

Do you think it is practicable to recognize (and not prevent) MAC address change in a blockchain network ?

I mean assuming a node is connected to a blockchain network like Ethereum network, then if this node changes its MAC address, is it possible to notify the rest of Ethereum network, if Ethereum network uses Cisco Port Security configuration for detecting MAC address change?

Is "fingerprinting a node" can be considered as a solution to detect MAC address spoofing in Ethereum network without sacrificing "decentralization of Ethereum"? (https://www.npmjs.com/package/node-fingerprint) or (https://pdfs.semanticscholar.org/d5ef/30919b4f28b82d6fb637e17a5a992f82ecaa.pdf)

Thank you

P.S. MAC address change detection using Cisco Port Security is described here: https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst4000/8-2glx/configuration/guide/sec_port.pdf and here: https://www.cisco.com/c/en/us/td/docs/switches/datacenter/sw/4_1/nx-os/security/configuration/guide/sec_nx-os-cfg/sec_portsec.pdf


texts: Changing transaction validation process in Ethereum

texts:
I am doing a research about Ethereum smart contracts security. For this purpose I want to make some changes in Ethereum miner and transactions validation process (editing miner for automatically reverting malicious transactions).
I should choose a miner to change its source code. Please introduce me some good open source miners for this research.


texts: How do you track total supply of a currency (smart contract) on the Ethereum blockchain?

texts: For a newly created crypto currency based on the Ethereum blockchain, how can the creator and the public in general track the current total supply of the coin, provided he enables mining new coins on his currency, and how do you track the live market capitalization?


texts: How does Ethereum know that I have enough ETH to spend?

texts:
Ethereum uses account-based model. It means that if account A has 50 ETH and sends 10 ETH to account B, transaction will look like "send 10 ETH from A to B" (no inputs and outputs as in UTXO).

With this model, at some step Ethereum should check if account A really has 10 ETH to prevent double-spending.

My question is how, where (module/code/contract), and when Ethereum verifies that?


texts: Fetch the last state of particular asset for particular date

texts:
I have one smart contract, in which I am doing mapping of machine id and user id mentioned as below:

mapping(bytes32 => uint256) public machineAllocs;
machineAllocs[machineId] = userId;

Now, I am assigning a user id to a machine id and also user id can be change for same machine id.
So, if I want to know that on particular date what is last state(let's 11:59 pm) of particular machine id, means which last user id is mapped with that machine id.

So, how to fetch this details?


texts: Token swap amount difference between the amount from uniswap app and contract read

texts:
When I tried to swap 1BAT from DAI by using Uniswap App (https://app.uniswap.org/#/swap), I needed 0.325372DAI as this picture show.

However, when I tried to calculate how much DAI I need to get 1BAT by directory read contract function (getAmountsIn()), it shows 329322487172572064, which means I need '0.32932DAI' to swap 1BAT.

I thought that the amount from getAmountsIn() would be same as the amount from uniswap official app.
Why those two amounts are different, Did I called wrong function?
Could you give me any advise, please?


texts: How to check if a function has been assigned?

texts:
I want to check if the callback has been assigned to avoid the exception:

pragma solidity 0.4.20;

contract Test {

  function() external callback;

  function test() public  {
    if (/*check here that callback is assigned*/)  {
        callback();
    }
  }
}


texts:
I want to get the unconfirmed balance for an address. Presently, I do it in the following manner:

ethGetTxpool = async function(address){
    var self = this;
    return new Promise((resolve, reject) => {
        self.client.call(
          {"jsonrpc": "2.0", "method": "txpool_content", "params": [], "id": 1},
          function (err, res) {
            if( err ) resolve(null);
            else {
                resolve(res.result);
            }
          }
        );
    });
};

and then filtering in JS like so:

var unconfirmedBalance = 0;
    Object.keys(txpool.pending).forEach(( txid ) => {
        Object.keys(txpool.pending[txid]).forEach(( nonce ) => {
            var tx = txpool.pending[txid][nonce];
            if( tx != null && (tx.from === address || tx.to === address) ){
                var value = Number(parseInt(tx.value, 16));
                if( tx.from === address ) unconfirmedBalance -= value;
                if( tx.to === address ) unconfirmedBalance += value;
            }
        });
    });

This works, however the data received from txpool_content API is quite big (4MB). So, the API is slow and also fails sometimes.

I came across web3.eth.filter and tried to use it in the following manner:

web3.eth.filter({
        "address": <My address>>
    }).get((error, logs) => {
        if(error)
            console.log(error);
        console.log(logs);
        });

However, it always returns an empty array even when I can see a pending transaction on etherscan.

Is there a better way to do this, apart from modifying the geth source code?


texts: Script for opening a geth console for a node and running commands in it

texts:
I am trying to create a script running a couple of geth nodes, open a console for each of them and run a couple of commands such as admin.addPeer() and miner.start(). I read that i can use --exec to run javascript files in the console but it does not seem to work for some reason. Here is my code:

start cmd /k geth --targetgaslimit "10000000" --identity "node1"  --allow-insecure-unlock --ipcpath node1 --rpc --rpcport "8000" --rpccorsdomain "*" --datadir "D:\Alexy\Geth Ethereum\node1" --port "30303" --nodiscover --rpcapi "db,eth,net,web3,personal,miner,admin" --networkid 1900 --nat "any"

start cmd /k geth  --identity "node2"  --ipcpath node2   --allow-insecure-unlock --rpc --rpcport "8001" --rpccorsdomain "*" --datadir "D:\Alexy\Geth Ethereum\node2" --port "30304" --nodiscover --rpcapi "db,eth,net,web3,personal,miner,admin" --networkid 1900 --nat "any"

start cmd /k geth --identity "node3"  --ipcpath node3  --allow-insecure-unlock --rpc --rpcport "8002" --rpccorsdomain "*" --datadir "D:\Alexy\Geth Ethereum\node3" --port "30305" --nodiscover --rpcapi "db,eth,net,web3,personal,miner,admin" --networkid 1900 --nat "any"

start cmd /k geth  --exec 'loadScript("D:\Alexy\Geth Ethereum\Windows  Scripts\node1.js")' attach

start cmd /k geth attach ipc:\\.\pipe\node2

start cmd /k geth attach ipc:\\.\pipe\node3

I also tried geth attach ipc:\\.\pipe\node3 --exec "miner.start(1); personal.unlockAccount(eth.accounts[0],'pass')" which works, but then I would have to list all commands on 1 line which is not ideal.


texts: How and where is the value of msg.value assigned?

texts:
I'm aware that msg.value is the amount of "wei" sent to the contract according to this page. I think it's sent from a transaction so it should be defined there.

Question: How is the value of msg.value in a transaction is defined to have a structure like: msg.value in the contract?


texts:
I am creating a Dapp for ERC721 NFTs. To execute a sale of an NFT from one user to another on my smart contract, I am calling the _safeTransfer function of openzeppelin from within another external function (called from my front-end). In exchange of the NFT, Ethers will need to be transferred from the purchaser to the seller using seller.transfer(msg.value). Furthermore, a commission will need to be sent to the smart contract itself.
My question is, how should I execute these three transactions (_safeTransfer, seller.transfer(msg.value) and send Ether to the contract) on my smart contract? From my understanding, if I initiate a "send" call from my Dapp, all the funds would go to the smart contract? Is this correct? If this is correct, I assume that I should be sending the funds to the seller from the smart contract after executing the _safeTransfer function? Is this how it is typically done?
Also, how can I revert ALL the transactions if the NFT or Ether transfer to the seller fails?
Thank you. J


texts: How does one setup a color coin or issue a digital asset token using Ethereum?

texts:
Lets say I want to issue my own company shares using Ethereum. Currently Counterparty, Coloredcoins, and NXT can do this with their asset exchange.

But how can this be done in Ethereum?
And is there a a place I can browse these digital assets that others have setup? - Is there a tutorial on how to get my own digital token setup?


texts:
I am running test contracts on the Ethereum testnet using geth. I need to make a file similar to a batch script which can execute commands one by one all in one go hence I am using expect to do so.

I keep getting the error: "extra characters after close-brace while executing" whilst running the script which is strange as I have removed the inner "" and converted them into ''.

Below is my incomplete expect script, any suggestions for friendlier alternatives to do doing this would be great.

#!/usr/bin/expect
spawn /usr/bin/geth --testnet console
expect ">"
send     "personal.unlockAccount('0xdc85a8429998bd4eef79307e556f70bb70d8caf1','bitc    oin');\r"
expect "true"
expect ">"
send "var mortalContract = web3.eth.contract([{'constant':false,'inputs':[],'name':'kill','outputs':  [],'type':'function'},{'constant':false,'inputs':  [],'name':'cashOut','outputs':[],'type':'function'},{'inputs':[],'type':'constructor'}]);\r"
send "exit\r"
expect eof


texts: when call solidity token approve method via web3js, my metamask is locking

texts:
i have got code like following; when i call that code, my metamask is locking and didn't respond.
what can you suggest? thank you
 var MyContractToken = new web3.eth.Contract(abiToken,'0x76990B2c222ae4A80D98C6402406616DBFD306b9');
 var MyContractLock = new web3.eth.Contract(abiLock,'0xA21170e12c7BB98477a14bE0D0F607929609dcb0');

 var encodedToken = await MyContractToken.methods.approve("0xA21170e12c7BB98477a14bE0D0F607929609dcb0",9).encodeABI();
 let _paramsToken = {
  data: encodedToken,
  from:ethereum.selectedAddress
}

var encodedLock = await MyContractLock.methods.lock(9).encodeABI();
 let _paramsLock = {
  data: encodedLock,
  from:ethereum.selectedAddress
}

  await ethereum.request({
    method: 'eth_sendTransaction',
    params:[_paramsToken,_paramsLock]
  })
  .then(_result => {

    console.log("success",_result);
  })
  .catch((error) => {
    console.log("error",error);
  });


texts: time order when calling functions of smart contract

texts: How can I check that the miner actually execute the right order of smart contracts function calls, if there is a necessity of orders?