texts:
I'm using Truffle and Ganache for my development environment. Using the truffle console or truffle external scripts everything works fine, but truffle test does not seem to be connected to Ganache:
When performing truffle exec ./script.js --network ganache everything works as expected. It shows the right contract address (as visible in Ganache UI) and in Ganache I can see the transactions having been performed on the contract.
Using network 'ganache'.

Test contract fetched 0xee09Bb5C1B6703f03db3263de408200ee134324D
BN { negative: 0, words: [ 0, <1 empty item> ], length: 1, red: null }
BN { negative: 0, words: [ 11, <1 empty item> ], length: 1, red: null }

But when performing truffle test --network ganache a different contract address is shown which I can't finde in Ganache UI and no transactions are visible in Ganache. However, the transactions seem to have been executed somewhere, but apparently not in Ganache.
Using network 'ganache'.

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

  Contract: 1st Test
Test contract fetched 0xD8F3b0A6B0Db4325ea309C7ac8e5CE17AB22D322
BN { negative: 0, words: [ 0, <1 empty item> ], length: 1, red: null }
BN { negative: 0, words: [ 11, <1 empty item> ], length: 1, red: null }
    ✓ should have set correct id (173ms)

Any idea why truffle testdoes not connect to Ganache?
Below my configuration:
Versions
Truffle v5.3.0 (core: 5.3.0)
Solidity - 0.8.3 (solc-js)
Node v15.13.0
Web3.js v1.2.9

truffle-config.js
networks: {
  ganache: {
    host: "127.0.0.1",
    port: 7545,
    network_id: "*",
  }
}

Contract Test.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract Test {

    uint public id = 0;

    function setId(uint _id) public {
        id = _id;
    }

    function getId() public view returns (uint) {
        return id;
    }

}

script.js
module.exports = async function(callback) {
    const Test = artifacts.require("Test");
    try {
        // Init
        const instance = await Test.deployed();
        console.log('Test contract fetched', instance.address);

        // Get ID
        var id = await instance.getId();
        console.log(id);

        // Set ID
        await instance.setId(11);

        // Get ID
        id = await instance.getId();
        console.log(id);
    } catch (error) {
        console.error(error);
    }
    callback();
}

test.js
const Test = artifacts.require("Test");

contract("1st Test", async accounts => {

    it ("should have set correct id", async ()=> {
        const instance = await Test.deployed();
        console.log('Test contract fetched', instance.address);

        var id = await instance.getId();
        console.log(id);

        await instance.setId(11);

        var id = await instance.getId();
        console.log(id);

        assert.equal(id, 11);
    });

});


texts:
web3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/root@123", request_kwargs={'timeout': 60}))

when I used this then sendTransaction is not working . I have to use sendRawTransaction . I want to use this 2 addresses for sendRawTransaction 0x33e9d80d9209a00B3F953748Bd59D68b4c7c7B91 , 0x72f5445cd31D7B6dedBBCDD425A558aeEa4B3acE .

Now how could I use this ? Please help me out.


texts: Creating a new contract via sendRawTransaction() dropped

texts:
I have setup a private test network with geth 1.5.7 and am trying to create a new contract from my node.js app via sendRawTransaction().  I see the transaction created and txpool shows it as queued, but it never moves to pending list and silently disappears off of the queued list after a few blocks are processed.  The same contract can be created just fine when I create it via the contract.new RPC approach.

I am pretty sure I am creating and signing the raw transaction correctly - in fact I believe it even worked a few times for one account but not another.  Any ideas on how to debug this further?  Thanks


texts: Is there a curated list of known security vulnerabilities related to escrow?

texts:
In Factories Improve Smart Contract Security, Steve Marx says that:

  This bug was hand-picked to show the benefit, but this bug is representative of a large class of bugs around escrow. In my experience auditing smart contracts, this is one of the most common places to find critical vulnerabilities.

Is there a public repository for the "large class of bugs around escrow"?


texts: AttributeError: 'Web3' has no attribute 'shh'

texts:
Web3.py version: 4.2.1
Python: 3.5.2
OS: linux
geth version: 1.8.0-unstable

I am running geth with --shh flag and --rpcapi "admin,eth,net,web3,debug,shh"

from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('http://localhost:8545'))

print ("web3 =", web3.version.api) #4.2.1
print(web3.shh) #error occurs

When I try to run following code above, I am having following error:

Traceback (most recent call last):
  File "dd.py", line 11, in <module>
    print(web3.shh)
AttributeError: 'Web3' object has no attribute 'shh'


texts: Solidity solc compiler error on code Remix can compile

texts:
I am attempting to compile the following solidity code using solc in NodeJS.

pragma solidity ^0.4.11;

contract helloWorld {

  string public message;

  function constructor() public{
    message = "Hello World";
  }

  function sayHi() constant public returns (string){
    return message;
  }
}

The commands I've written in NodeJS to do this are:

var source = `source code above`
var compiled = solc.compile(source)

When I look at the 'compiled' object, I see the following errors:

formal:
   { errors:
      [ ':5:3: Error: Type "string" not supported for state variable.\n  string public message;\n  ^-------------------^\n' ] },
  sourceList: [ '' ],
  sources: { '': { AST: [Object] } } }

I have a working TestRPC instance open, and can run web3.eth.accounts from the node console to this TestRPC instance (over port 8485). The code compiles correctly in Remix. I'm following a guide on getting these libraries working on a windows computer, so I don't see why anything could be incompatible with one another.

The versions I am using are

solc - 0.4.11
web3 - 0.19.0


texts: This question should probably be put as on-hold or closed as off-topic since it tends to lead to spammy or self-promotional answers, or will need to be updated frequently with new implementations, but people can leave a comment.


texts:
I have to scan a large amounts of old block. I using subcribe newBlockHeaders so I have new_block.number (2s/block).
Then I find in db the latest block number (db_block.number).
I use

for(i=db_block.number ; i<db_block.number+200 ; i++){
    web3.eth.getBlock(i, true, function (error, result) {
        //do somethings
    })
}

then insert  blocknumber to db, db_block.number will increase every time for loop is finish and for loop run again until db_block.number == db_block.number.
But after some for loop, its return message 'out of memory'. I know this error because when the loop is finish, my 'do somethings' code is not finish yet. So how can I know when all for loop had finish to start a new one?


texts: Facing problem while deploying crowdsale smart contract,

texts:
this is my code:

pragma solidity 0.5.0;

import "token2.sol";

contract crowdsale{

     Token public mytoken; // token being sold

      address payable public wallet;  // whre funds are located;

      uint public rate; // how many token unit a buyer gets per wei
      uint public weiraised; // amount of weiraised

       event token_purchased(address indexed purchaser, address indexed benefeciary, uint value, uint amount);

       constructor(uint _rate, address payable _wallet, Token  _token) public{
         require(_rate > 0);
         require(_wallet != address(0));
       //  require(_token != address(0));
          rate = _rate;
          wallet = _wallet;
          mytoken = _token;

       }
       function buytokens(address _beneficiary) public payable{
            uint wei_amount = msg.value;
            _prevalidate_purchase(_beneficiary, wei_amount);

            // calculate Token amount to be created

            uint tokens = _gettokenamount(wei_amount);

            // update state;

            weiraised = weiraised + wei_amount;

            _processpurchase(_beneficiary, tokens);
            emit token_purchased(msg.sender, _beneficiary, wei_amount, tokens);
            _forwardfunds();

       }

       function () external payable{
           buytokens(msg.sender);
       }

       function _prevalidate_purchase(address _beneficiary, uint wei_amount) internal  {
           require(_beneficiary != address(0));
           require(wei_amount != 0);
       }

       function _delivertokens(address _beneficiary, uint _tokenamount) internal{
           mytoken.transfer(_beneficiary, _tokenamount);
       }

       function  _processpurchase(address _beneficiary, uint _tokenamount) internal{
           _delivertokens(_beneficiary, _tokenamount);
       }

       function _gettokenamount(uint wei_amount) internal view returns(uint){
           return wei_amount * rate;
       }

       function _forwardfunds() internal {

            wallet.transfer(msg.value);

       }

}

this is the error i get:

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


texts: Interact with a deployed contract from another contract

texts:
Say i have this contract which I have deployed

contract A {
        mapping (string => uint) public someMapping;
}

Now, can I interact with the data of the deployed contractA in some other contractB i.e in contractB can I get the value of someMapping["someString"]?

I am using Truffle along with Ganache and MetaMask.


texts:
I've tried several times to add a subNode to my ENS domain through MEW/Contracts.
Keep getting: Error encountered during contract execution [Bad jump destination]

When clicked on "Write" to make the it also starts with Gas Limit = -1.
When changed to different amounts on the several times I tried, it keep failing to create the subNode.

Also, it cost significant amount of Tx cost on gas by now, which has not been returned after the failed transaction.


texts: Best way to create identity contracts for organisations

texts: What is the best way to create identity contracts for organisations based on their information like name, address, organisation type(buyer/seller) etc. I have tried using factory pattern to create these identity contracts , i have also looked into ERC725 implementation.


texts:
I'm following this tutorial: link for building a private parity blockchain, for some reason I have to insert some binary data into smart contract. What do I have to do to let the smart contract store more than 1MB of data?

For Parity client I use web3j.

My code:

Contract contract = Contract.deploy(web3j, credentials, BigInteger.valueOf(5000L), BigInteger.valueOf(100_000_000L), bytes).send();

It always shows error:  "Transaction is too big, see chain specification for the limit.".

I tried to increase "gasLimit" in chain spec but it seems not working.

Any help would be appreciated.
Thanks.


texts:
I am working on the text, Mastering Ethereum and I deployed a contract and sent it test ether. However, for unrelated reasons I had to restart my browser, upon returning the only way I could continue was to launch a new contract cause I could see no way to continue or retrieve the last account in remix.
Hence my question, is there a way to "contniue" working on a contract? or I can search and bring it back with the same account number in Remix?

Regards


texts: does the gasleft function return the total gas left for the transaction or the gas left for the function call

texts: If a function is using the gasleft() function and is called by another smart contract, does it return the total gas left for the transaction or just the gas left passed to the function via the message call?


texts:
I'm reading about the hard fork EtherZero, in particular the section about how to get ETZ money.

Can someone explain me what does it means "Derive the private key from the private key-approving wallets, then import the private key account to the official EtherZero wallet to get EtherZero." and how to import this derived private key into EtherZero wallet?

Thank you.


texts: Is Ethereum 2.0 (Sharding Ethereum) only PoS based? Or a combination of PoW + PoS?

texts:
Does Ethereum 2.0 (Sharded Ethereum) only use PoS (Proof-of-stake) for consensus mechanism ?

Or

Does it use a combination of PoW + PoS ?


texts: How to detect ETH deposits into an Ether address?

texts:
I want to be be able to programmatically detect an ETH deposit in order to process it as a payment in my app.

I have been looking into an etherscan.io API and the only way i found to detect incoming transactions was by doing a cron job and constantly monitoring the list of transactions.

Is there a better way?


texts: Why drivers version influence hash rate?

texts:
It's well known now that the very same GPU with the 16.4.1 drivers has a lower hash rate than with the 15.12
I absolutely don't have the beginning of an idea to why. Anyone?


texts: How to add a contact to Ethereum Wallet?

texts:
I'd like to add the addresses of my contacts to Ethereum Wallet, so I could send them eth and Dentacoin tokens, easily. I could also check their balances and check if they got the money.
How to add a new "read-only" contact without private key?


texts: How to mine private node blocks on remote machine

texts:
In testing purposes I started private ethereum node on server and made it's api address public via nginx.

geth --networkid 4224 --datadir "" --nodiscover --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal,net,miner --ipcpath ""

I'm sure it must be possible to somehow mine it's blocks remotely from my pc. Is it?


texts:
I have a keystore file but I can't remember all the passwords.
Then I use Hashcat and I try to crack it with my list of words that I made but I don't know if I use the correct commands.
hashcat.exe -a0 -m 15700 --force -D1 hashcode.txt password.txt -w3

I just want to compare my password file with the hash.
Thanks in advance


texts: expectEvent with string returning a non-string value

texts:
I am using expectEvent from OpenZeppelin's Test Helpers, and when running a Truffle test to check the event, it's all fine for address and integer fields, but have an issue for  string type.
Given a smart contract with this event and function:
  event WithdrawERC20Token(
     string indexed tokenSymbol,
     address to,
     uint256 amount
  );

  function withdrawERC20(
     string calldata tokenSymbol,
     address to,
     uint256 amount
  ) external {
     //...
     emit WithdrawERC20Token(tokenSymbol, to, amount);
  }

And this test:
const { expectEvent } = require('@openzeppelin/test-helpers');

// ...

it('should withdraw ERC20 tokens', async () => {
   //
    const txReceipt = await swapManagerContract.withdrawERC20Token(
        'UNI',
        investor1,
        50
    );
    expectEvent(txReceipt, 'WithdrawERC20Token', {
        tokenSymbol: 'UNI',
        to: investor1,
        amount: new BN(50),
    });
}

I get this output error:

  expected event argument 'tokenSymbol' to have value UNI but got 0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650
  + expected - actual

  -0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650
  +UNI

It looks like the tokenSymbol is stored in kind of hexa format in the EVM. I have tried to apply several conversions to the string 'UNI' (fromAscii, asciiToHex, etc) but nothing gets this string into '0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650'.
Any clue on how to check the string from the event with expectEvent function?


texts: What should I use instead of "var" in this context? (As "var" is now deprecated)

texts:
First, I apologize as this question has been asked before; however, the solutions didn't seem to work in the context of my contract.  When I remove "var", Remix does not recognize "car", but with it, I get the warning that "var" is deprecated.  I've tried using "struct car" and "struCar", but neither worked.  How should I replace var?

mapping(uint => Vehicle) vehicles;

function newCar(bytes32 _color, bytes32 _make, uint32 _year) public returns (uint ID) {
    var car = vehicles[carID];
    car.color = _color;
    car.make = _make;
    car.year = _year;
    carID ++;
    ID = carID;


texts: Return a String with function giving an error in Solidity 0.5.1

texts:
Pretty new to solidity and I was watching some tutorial on web. and my function is giving an error while trying to return a string from a function.

Below is my simple contract:

pragma solidity ^0.5.1;

contract and {

    string d = "Hello";

    function getValueOfabc() public view returns(string) {
        return d;
    }
}

And function getValueOfabc() public view returns(string) { is giving me below error:

browser/mulreturn.sol:7:50: TypeError: Data location must be "memory" for return parameter in function, but none was given.
    function getValueOfabc() public view returns(string) {
                                                 ^----^

The above code is working fine with version 0.4.25


texts: Couldn't interact with a "complex" Smart Contract in a private network through Web3.js, however, could interact with Remix

texts:
I've developed a UI in Visual Studio. The UI is a simple HTML with some CSS and also, Javascript code. To interact with my Ethereum Private Network, I've included the web3.min.js.

Firts of all, I've developed and deployed my Smart Contract via Remix. The Smart Contract registry an entry each day, no more, so the date is the "identifier". Here is the Smart Contract.

struct Product {
        string concept;
        uint256 quantity;
}
mapping (uint => Product) allProducts;
uint[] public productDates;
function setProduct(string _concept, uint256 _quantity, uint _date) public {
     var newproduct = allProducts[_date];
     newproduct.concept = _concept;
     newproduct.quantity = _quantity;
     productDates.push(_date) -1;
 }
function getProducts() view public returns (uint[]) {
     return productDates;
}
function getProduct(uint date) view public returns (string, uint256) {
    return (allProducts[date].concept, allProducts[date].quantity);
}

Then, I interact with my Smart Contract via the Remix interface without any problem.

However, when I try to interact with the Smart Contract with my UI, it doesn't work. I try to add new "products", but I can't.

If I delete the "concept" from the Product struct, and I only create Products with a quantity, it goes ok.

Why happens this? I've done many changes and proofs but it doesn't work.

Edit 1:

My private network is created via geth. I only have a node, where I créate some accounts.


texts:
I'm following this tutorial for a simple contract.
https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05

After running testrpc, compiled with truffle compile and deploy with migrate, I open the truffle console and run these commands:

truffle(default)> var poe = ProofOfExistence1.at(ProofOfExistence1.address)
// and print its address

truffle(default)> poe.address
0x3d3bce79cccc331e9e095e8985def13651a86004

// let's register our first "document"
truffle(default)> poe.notarize('An amazing idea')

but when I run this last command, instead of obtaining the output described there I get an error:

truffle(development)> poe.notarize('An amazing idea')
Error: VM Exception while processing transaction: invalid opcode
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)

I tried to repeat all the procedure very carefully but got the same error.
Any suggestion?


texts: My balance is 0.00 after update. What to do?

texts:
I updated my Mist Wallet to 0.9.3 on Mac. When I started it, I saw that my balance is 0.00 which isn't true. Etherchain shows 24 ETH for my wallet.
It has nothing to do with syncing. Everything is correct concerning this.
I tried to restore my wallet using the backup files. When I started it, I saw the correct amount just for a second, before it was counted down to zero in front of my eyes.

I have no idea what to do. Any ideas, any help?
Many thanks in advance!!!


texts: "Truffle test" fails in petshop tutorial

texts:
I don't know what this error means or how to fix it.

I try to follow the tutorial located here and when I get to the point where I have to run "truffle test" I get the following error.

with TestAdoption "before all" hook: prepare suite:      Error: Could not find artifacts for ''EthereumPetShopTutorial/contracts/Adoption.sol" from any sources

Output of Truffle version

Truffle v4.1.5 (core: 4.1.5)
Solidity v0.4.21 (solc-js)

this is my 2_deploy_contracts.js file

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

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

this is my TestAdoption.sol file:

pragma solidity ^0.4.17;

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

contract TestAdoption {
  Adoption adoption = Adoption(DeployedAddresses.Adoption());

  // Testing the adopt() function
    function testUserCanAdoptPet() public {
        uint returnedId = adoption.adopt(8);

        uint expected = 8;

        Assert.equal(returnedId, expected, "Adoption of pet ID 8 should be recorded.");
    }

}

This is my file structure:


texts: Using geth Light Node to detect ERC-721 transactions

texts:
Is it possible to use a geth light node to detect incoming transactions executed via ERC-721 contracts?

I have experienced being not able to get receipts using getTransactionReceipt in native and ERC-20 transactions if I'm using a light node. I'm assuming it would be the same for ERC-721?


texts:
I tried to build a basic contract from some resources but failed to deposit the ether into this contract.
Following is my code, is it correct that "msg.value" and "address(this).balance" be 0 at any time?
If so, how can I send ether to another address?
If not so, how to deposit money in a correct method?

// can get balance
function getOnesBalance(address addr) public view returns (uint){
    return addr.balance;
}

// can get balance
function getMyBalance() public view returns (uint){
    return msg.sender.balance;
}

// 0
function getMyBalance2() public view returns (uint){
    return msg.value;
}
// 0
function getMyBalance3() public view returns (uint){
    return address(this).balance;
}

function deposit(uint _money) public payable {}

function getContractAddr() public view returns (address){
    return msg.sender;
}

function() payable {}


texts: Sent ether to my wallet, been almost two months now and still downloading block chain. what do i do to speed this up?

texts: i've downloaded geth but i don't know if it's doing anything. the terminal says "Fatal: Error starting protocol stack: resource temporarily unavailable" when i try to start it. i'm not really sure what all info is needed to help me, this is all new to me. thanks for any help


texts: Can the DAO hack solution proposed by Vitalik be rejected by 51% of PoW miners?

texts:
If the majority of the network does not like the softfork, followed by the hardfork idea proposed by Vitalik (because they feel like the solution is an assault on immutability of ETH or for some other reason) can it be forced on the network?

http://pastebin.com/xW16N7Ye

  "The development community is proposing a soft fork, (with NO
  ROLLBACK; no transactions or blocks will be “reversed”) which will
  make any transactions that make any calls/callcodes/delegatecalls that
  execute code with code hash
  0x7278d050619a624f84f51987149ddb439cdaadfba5966f7cfaea7ad44340a4ba
  (ie. the DAO and children) lead to the transaction (not just the call,
  the transaction) being invalid, starting from block 1760000 (precise
  block number subject to change up until the point the code is
  released), preventing the ether from being withdrawn by the attacker
  past the 27-day window. This will later be followed up by a hard fork
  which will give token holders the ability to recover their ether."


texts: How does the EVM identify a dynamic type in the function calldata?

texts:
So as per the ABI encoding specifications mentioned in Solidity Docs, for a dynamic array, the data location (in bytes from start, for the data part) is specified at first, followed by the length of the array at the previously specified location, followed by the actual data values.
Example in docs:
Function to be called: function sam(bytes memory, bool, uint[] memory) public pure {}
Calldata bytes for sam("dave", true, [1, 2, 3]):
0xa5643bf20000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000464617665000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003
Here, the first set of bold bytes represents the location of the bytes value for "dave". The second set of bold values is the actual data (starting with the length of the data which is 4 here).
So, while interpreting the calldata, how does the EVM differ the location of the dynamic data from being just a normal variable value? i.e here, how is 0x00...60 is identified as a location value, instead of being maybe a static uint?


texts: returning an uint array + gas + cost efficient problem?

texts:
I have a growing public array

struct MatchInfo {
    uint256 matchId;
    bool isMatchDone;
}

MatchInfo[] public matchInfo;

and I want to return an array of uint256 which will loop through matchInfo and find where isMatchdone == false

function getUnfinishedMatches() public constant returns (uint256[]) {
  uint256[] memory unFinishedMatches = new uint[](getMatchCount());

  for (uint i = 0; i <= matchInfo.length; i++) {
    if (matchInfo.isMatchdone == false) {
      unFinishedMatches[i] = matchInfo.matchId;
    }
  }

  return unFinishedMatches;
}

I saw somewhere in the post that constant returns will not use up gas. Is it true? if it is not true, is the above function a bad way of approach/practice to return an array in solidity? If so, what are the alternatives?


texts: Is it possible to check that does client's node's block number matches with the blockchain's best(latest) block number?

texts:
I have a sorted linked list that contains around 1000 items. When I receive a new item my goal is to push the item to the list keeping the sorted order. So if I receive very small value, I am required to iterate all the list to find the tail of the list. I have suggested that I could retreive the index via constant function and my transaction function could use the returned index value to push the item to correct location without spending gas to iterate the list.

My goal is to follow this guide (https://ethereum.stackexchange.com/a/13855/4575) to call a constant function and submit its return value into a transaction function.

getIndex() => constant
setArray() => transaction

setArray( getIndex() );

The question emerges that: when I call a constant function on my client node is it possible to check that does my client node's block number is the best block number or is it behind. If it is behind, constant function may return wrong information.

For example blockchain's best block is 100. But my node is in currently at blockNumber 90 (basically behind of the blockchain). So when the client node get the index of the list up to first 90 blocks and miss items generated on the remaining 10 blocks.

[Q] Is it possible to check that does client's node's block number matches with the blockchain's best which is the latest block number?

As you can see on the example image, block number on the client nodes may vary. Best block number is 1,002,312 but block number is 1,002,304 on node on the top. But sometimes all nodes are on the latest block number. So it is hard to trust to node's behaviour.

Following answer seems working:

web3.eth.syncing;
sync.highestBlock

But returned highestBlock number still seems few blocks number smaller than on my best block number on my private chain. Is it a normal case?


texts: Is it ok to pass function's call as arguments to functions in Solidity?

texts:
So basically, is it ok to call fun() as an argument like ethToWeiConverter in the example below? Otherwise, what style is preferable?

contract RefundableCrowdsale {
  uint256 cap;

  RefundableCrowdsale (uint256 _cap) {
    cap = _cap;
  }
}

contract MyCrowdsale is RefundableCrowdsale {

  // constructor
  function MyCrowdsale (cap) RefundableCrowdsale (
    ethToWeiConverter(cap)
  ) {
    ...
  }

  function ethToWeiConverter(uint256 eths) returns (uint256) {
    return eths * 10**18
  }
}


texts:
Can a contract view the details of a transaction, given a transaction id?

More generally, what details of the blockchain is a given contract aware of?


texts: gas required exceeds allowance when deploying ERC721token


texts:
Got his error when run truffle test
Using network 'test'.

Compiling your contracts...
===========================
> Compiling .\test\TestFirst.sol
> Compilation warnings encountered:

    /D/Truffle Projects/statevariables/contracts/First.sol:21:6: Warning: Function state mutability can be restricted to pure
     function getAge4() public view returns (int) {
     ^ (Relevant source part starts here and spans across multiple lines).

> Artifacts written to C:\Users\92311\AppData\Local\Temp\test--9552-BsbV54PdVc1Y
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

  TestFirst
    1) testAge
    > No events were emitted

  0 passing (20s)
  1 failing

  1) TestFirst
       testAge:
     Error: Returned error: VM Exception while processing transaction: revert
      at Context.<anonymous> (C:\Users\92311\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\SolidityTest.js:92:1)
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)

My code is:
pragma solidity ^0.5.0;

contract First {
    int internal age = 40;
    int public age1 = 50;
    int private age2 = 60;
    int public constant age3 = 70;

    function getAge1() public view returns (int) {
        return age;
    }

     function getAge2() public view returns (int) {
        return age1;
    }

     function getAge3() public view returns (int) {
        return age2;
    }

     function getAge4() public view returns (int) {
        return age3;
    }
}

Test file:
pragma solidity ^0.5.0;

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

contract TestFirst {
    function testAge() public {
        First meta = First(DeployedAddresses.First());
        meta.getAge1();
        Assert.equal(meta.getAge1(), 40, "Age 1 is not equal to 40");
    }

}

Version:
Truffle v5.2.4 (core: 5.2.4)
Solidity v0.5.16 (solc-js)
Node v14.16.0
Web3.js v1.2.9


texts: Does having a separate contract for storage increase gas cost of making a transaction?

texts:
I've been reading a lot about upgradability of smart contracts, and it seems like major prevailing practice is that it is generally a good idea to keep contract logic separate from contract storage, so it is possible to upgrade one and not have to change the other one.

My question is the following: does the fact that one contract has to call another contract increase the amount of gas that is spent by that logic. For example, say I had a contract that looked up a number X and then added it to the number 5.

In one case, the contract stores in X itself, and so it can directly look it up. In the other case, a separate contract is responsible for storing X, causing one contract to make a function call to get X. Does one cost more gas? If so, is it possible to tell how much more?

Thanks!


texts: Should an API call be in the Solidity backend or the Javascript frontend?

texts: I am fairly new to blockchain development.  I want to call a function in my contract when a condition in the API is true.  Should I make this API call in my contract, or in my frontend?


texts: Command "geth --rpcapi eth,web3,personal --rpc" throws Fatal Error

texts:
After deploying an private Ethereum blockchain with Azure Template "Proof of Work" we are not able to run the following command successfully.
"geth --rpcapi eth,web3,personal --rpc" following image shows the specific error we are receiving.

The reason to run this script is because we are using nethereum web3 based c# code to execute the solidity contract. we are unable to unlock account and following is the error we are receiving during the execution of C# code.

Any Quick insights on this will be appreciated.


texts: Burn existing token through new contract

texts: How can I burn a token that already exists with no burnable functionality inside its smart contract? Can i create a new contract with a burn function and call the specific token that I want to be burned? If possible, please provide an example.


texts:
I need to define a specific time phase. Therefore, I wanted to use opening timestamp and closing timestamp using block.timestamp. I get the following warning:
Linter: security/no-block-members: Avoid using 'block.timestamp'.

with the explanation that block.timestamp can be manipulated by miners.
Is there another solution working with timestamp or defining a time phase resp.?


texts: Different behavior of the same contract between JavaScript and Solidity tests with Truffle

texts:
I have a simple contract that functions as a ratekeeper - it is constructed with a capacity and
time_frame (in blocks) parameters and makes sure we never add more than $capacity payments in any given time frame. The function addPayment() registers the timestamp of the payment and adds one to the load, if the we didn't go over the capacity. It will return false otherwise.

pragma solidity >=0.5.8 <0.6.0;

    contract RateKeeper {
        uint256 public capacity;
        uint256 public timeframe;

        uint256 public load; // Number of transactions in record so far

        constructor (uint256 _capacity, uint256 _timeframe) public {

            capacity = _capacity;
            timeframe = _timeframe;
            load = 0;
        }

        function addPayment() public onlyOwner returns (bool added) {
            // removeOldEntries();
            if (load >= capacity){
                return false;
            }
            load++;
            return true;
        }

When I test the function in solidity it behaves as expected, however in JavaScript the load doesn't increase with function calls. Why is that?

In the following JavaScript test the two last assertions fail:

contract("JS RateKeeper test", async accounts => {
  it("Constructor, addPayment(). This test doesn't pass", async function () {

    let instance = await RateKeeper.new(1, 299);
    let inst_capacity = await instance.capacity.call();
    assert.equal(inst_capacity, 1);
    let load = await instance.load.call();
    assert.equal(load, 0, "load is 0 as no payments were initiated so far");
    let payment_success = await instance.addPayment.call();
    assert(payment_success, "Load is 0, capacity is 1 - payment should succeed");
    let load2 = await instance.load.call();
    assert.equal(load2, 1, "load should be 1 after a single call to addPayment()");
    payment_success = await instance.addPayment.call();
    assert(!payment_success, "We are at full capacity, payment should fail");

Meanwhile, the solidity test goes smoothly

  function testAddPayment() public{
    RateKeeper keeper = new RateKeeper(2,299);
    Assert.equal(keeper.load(), 0, "We added no payments");
    Assert.isTrue(keeper.addPayment(), "Contract has (0/2) payments");
    Assert.equal(keeper.load(), 1, "We added 1 payment");
    Assert.isTrue(keeper.addPayment(), "Contract has (1/2) payments");
    Assert.equal(keeper.load(), 2, "We added 2 payment");
    Assert.isFalse(keeper.addPayment(), "Contract has (2/2) payments");
    Assert.equal(keeper.load(), 2, "We added 2 payment");
    Assert.isFalse(keeper.addPayment(), "Contract has (2/2) payments");
    Assert.equal(keeper.load(), 2, "We added 2 payment");
    keeper.destroy();


texts: Do Larger Mining Pools Waste Fewer Hashes?

texts:
I wanted to check my understanding of the PoW consensus algorithm as it pertains to ETH and BTC mining.

Mining pools pool together resources from many miners to search over nonce values to create the next block. The first miner to find the right nonce wins, therefore all the search performed by other miners is "wasted", and they need to move onto mining the next block.
If there are two mining pools attempting to solve the same block, and one is substantially larger than the other, the larger mining pool will tend to find the block (and receive the block reward).

I understand that the intent of PoW coins is to avoid mining centralization, but if the above two assumptions are true, isn't it beneficial for miners to always join the largest mining pool?


texts: "No data is deployed on the contract address"

texts:
Following token tutorial on ethereum.org, get error message

  No data is deployed on the contract address

Forgive me, but I am new to mist. How do I find the "MyAdvancedToken" in Mist?


texts: Plasma is a layer-2 scaling solution but it seems to be not very effective , are there any other ethereum scalability solutions that are efficient and can be applied to enterprise use cases alongside hyperledger besu?


texts:
I'm trying to buy tokens and I'm getting an error and failed transaction.
It's taking the gas fee and then failing.
I've attached the contract and the errors from etherscan and error from terminal.

If someone can guide me in the right direction I'd be very grateful, at this a few days now and hitting brick wall after brick wall - surely it's a simple mistake I'm making and a simple fix.
Thanks


texts: Why (conceptually) are string functions not yet supported in solidity?

texts:
My understanding is most string functions (e.g. .charAt()) need by done "by-hand" by converting to bytes and then doing operations on those bytes, or, of course, using some sort of utility library.

I understand some choices in Solidity are for safety -- for example not supporting float for now.

Is the choice for poor string support a conscious choice for some sort of safety reason?  Or is this just an evolution of the language not yet complete?


texts: How can we assign unique hash id to the id that created inside our smart contract in ethereum?

texts:
I am using truffle, ganache and web3. I am initializing user id in smart contract while deploying the smart contract. As of now, everything is done by account[0] of Ganache.

Now, I want functionality like, if ## Heading ##I am creating any user id in smart contract then it has to be assigned with unique hash which is given by blockchain.

For that, I have no any idea that how can we integrate nwely created user to the account of ganache.

Is there any other way to do that or is anyone has any reference link for that ?


texts:
I'm writing a snippet of code that should call an API and record the response to the chain:

function(APIResponse) {
    // Write to chain
    console.log(`API responded with:\n${APIResponse}`);
    let callResult = instance.writeResponse.call(APIResponse);
    console.log(`Writing api response to chain result: ${callResult}`);
    const ID = instance.writeResponse.sendTransaction(APIResponse);
    console.log(`Transaction ID: ${ID}`)
}

In an attempt to use the proper pattern, I first call to check the function and later send the transaction. The call passes and returns a boolean value, but the sendTransaction fails with the following:

requestmanager.js:61 Uncaught Error: VM Exception while processing transaction: out of gas(…)

Referencing a similar issue I attempted to add gas to the function calls:

function(APIResponse) {
    // Write to chain
    console.log(`API responded with:\n${APIResponse}`);
    let callResult = instance.writeResponse.call({gas: helper.averageGasBump}, APIResponse);
    console.log(`Writing api response to chain result: ${callResult}`);
    const ID = instance.writeResponse.sendTransaction({gas: helper.averageGasBump}, APIResponse);
    console.log(`Transaction ID: ${ID}`)
}

This time, no Error is thrown, the transaction gets recorded but when I try to access the varable that should have been stored in the chain as a JSON string, an empty string is being returned.

Interestingly enough, inside truffle console I can invoke all functions without the need for an additional gas bump and they get recorded properly.

I'm using testrpc.

Could you explain to me what is going on?


texts: Transaction having low gasPrice makes all the other transactions pending state

texts:
When transactions are on pending, is it possible to follow a path to fix this situation without deleting the transaction.rlp file and shutting down the machine?
Thank you for your help!


texts: Where can I buy some usdt in small amount for testing on mainnet

texts: Any where to buy small amount of usdt of mainnet for testing?


texts: Require that a variable has been defined

texts:
I want to require two variables for the execution of my function, firstly a string shall not be undefined and then a mapping (address => uint) that shall be undefined. In the latter case, I have user numbers from 0...n, so 0 would be the first user.
Is there an easy way to do this, or do I have to do complicated workarounds with eg. keccak hashes?

struct userData {
    string name;
    string role;
    mapping (address => uint) accountToId;
}

mapping (address => userData) addressToUserData;

function register(string _name, string _role) public {
    require(_name !== false); // to avoid empty names
    require(addressToUserData[msg.sender] == false); // make sure mapping is undefined
    addressToUserData[msg.sender] = userData(_name, _role);
}

[I hope by now there is better solution than this]


texts: Relationship with smart contract and block confirmation

texts:
I have known Bitcoin need 6 blocks for confirmation.

However, In ethereum, It is different depend on clients

By this post What number of confirmations is considered secure in Ethereum?

It takes about 3min for block confirmation.

Then if i deploy smart contract, then it will start to work after block confirmation? or after block generation?

Every node will validate my smart contract even though a block which including contract is not generated. Therefore we can know this contract is validate before generating block.

Therefore, by finality, we are sure this transaction must be finished someday. so it seems like smart contracts don't need block confirmation if it is validated by node.

By this post At which point the smart contracts get executed?

  But the "official" execution point is the point at which the transaction occurs in the blockchain. If it's transaction #5 in block #3000000, then the transaction's "point of execution" could perhaps only be described as immediately following transaction #4, preceding transaction #6

It means after block is generated, then smart contract worked right...?

Because writer said, execution occurs in blockchain not a block.

I think smart contracts are set of transactions and transactions need block confirmation.

If that quote is right, then why block confirmation is needed in ethereum?

And if block confirmation is needed for deploying smart contracts, Are there no problems which are cased by every client has their own block confirmation number?


texts: How to set and retrieve items to/from an array that is stored in smart contract memory/storage?

texts:
I am trying to add msg.value and msg.sender into an array using web3 for every client that invokes my contract. I would like this information to be stored on the contract for as long as possible, if possible.

If a new client invokes this method, they are added to the array, and so on.

I then want to be able to retrieve those values (msg.value, msg.sender) from the array via web3 at a later point in time.

It would be great to see the contract code, and the web3 code if possible.


texts: Runtime Breaking before out of gas error

texts: I'm trying to catch an obscure bug which is causing an out of gas error after x number of runs of a particular function.  In mix you can debug a successfully run transaction but how can I break at runtime?


texts: Shouldn't gas be constant for calling same contract method?

texts:
Note that I am talking about the gas, not gas price. While testing a contract, I see different amount of gas used for invocation of same method. The method does not have any branching so every single time the same flow is executed so how is it possible that invocation of same method can result in different gas amount used?

And if that's possible then can we take the gas from test networks and use them as reference for setting gas limits when deploying to main network? I believe gas should be same irrespective of main or test network but gas price will obviously be higher in most cases on main network.

UPDATE:
I am using transfer method of OpenZappelin's BasicToken contract. Link to contract file - https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol

function transfer(address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
    require(_value <= balances[msg.sender]);

    // SafeMath.sub will throw if there is not enough balance.
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
}


texts:
The standard metadata schema for ERC721 Tokens requires three properties to be populated for each Token:

name
description
image

So if we created a collectible-game called say "CryptoHippos", we could populate these properties as follows:
-name - "CryptoHippo Token#123" (where the # would of course change for each Token)
-description - "Another unique creature from the super-addictive CryptoHippo Blockchain Game!"
-image - "http://www.cryptoHippos.com/images/CryptoHippo123.png"
Or something like that.
Now let's say our game is a huge hit and someone decides to steal some of our thunder by creating their own "hippo" contract that generates Token-metadata that is 99.9% identical to ours, as follows (see if you can spot the difference):
-name - "CryptoHippo Token#123" (here they make an exact copy of our name property)
-description - "Another unique creature from the super-addictive CryptoHippo Blockchain Game!" (same thing: an exact copy of our Metadata)
-image - "http://www.cryptoHippoos.com/images/CryptoHippo123.png" (here they have to use a slightly different URL - it's just one letter off - because they obviously can't access our domain)
So, if they put these tokens out there, my questions are:

How would the average consumer know that these are not authentic "CryptoHippo" tokens? The name and description properties certainly says they are, so how would they know they're not?
What if we decided to store the images of our tokens on IPFS and not host them on our cryptoHippos.com server - meaning that instead of our very true and authentic cryptoHippos.com domain appearing in the Token's metadata, the generic ipfs domain would appear, making it even easier to fake Tokens to seem authentic - so what then?

Seems like the metadata is very hackable.
Is there some other technique, trick, or different approach to take to ensure Tokens aren't fake-able?


texts:
I didn't have any problem using solc 0.5.0 (geth 1.9.3), but facing this problem after upgraded to 0.5.12 (geth 1.9.9).

After doing some research, I believe it is because of the changes to the transfer() function in solidity. But unfortunately I didn't get any error message when compiling.

So, I a very confused now, and didn't know if there is any where else I had made error.

Anyone know why solc is not complaining about error / obsolete functions()


texts:
I am using go-ethereum private network.

I am using the web3.shh.filter() and it is working fine.

I am not able to locate the filter() function in the code.

In complete go-ethereum folder, I am not able to locate it.

filter.get() produces output correctly with expiry time and all. But I am not able to locate "expiry" word in the complete folder.

Can some one help me to locate this.


texts: Restore Brave Browser Crypto Wallets with seed from MEW

texts:
I've created a MEW wallet and noted the seed (Mnemonic phrase).
After playing around with the Brave Browser and its Crypto Wallets plugin, I tried to restore the account from the seed I received from MEW.
My assumption at that point was (I'm still learning) that the Crypto Wallets plugin of Brave is just another Etherum client, and I could use this one in parallel (as long as I restore the keys with my seed).
To my surprise, the recovery worked well, and "an account" was restored and added to the Brave Browser. However, the account has a different public address and, of course, zero balance.
So there must be a misconception in my head.
Why can I restore with my seed but end up with a different account (public address)?

Update 1
Thanks to this answer, I was able to track down an issue on Brave's Github repository, which explains a couple of incompatibilities with other wallets. IMO this explains the confusing behavior described in my post.


texts: How to Properly use "Memory" After Function Parameters

texts:
I have a question about writing functions in Solidity - I am trying to create an array of dog structs but I can't seem to get the function declaration correctly:
pragma solidity ^0.5.1;

contract MyContract {
    struct dog {
        string name;
        string ownername;
        int8 age;
    }
    dog[3] dogarray = dog(3);
    function setIndex(int index, string name, string ownername memory, int8 age) public {
        dogarray[index].name = name;
        dogarray[index].ownername = ownername;
        dogarray[index].age = age;
    }

}

I am getting the error contracts/MyContract.sol:11:64: ParserError: Expected ',' but got 'memory' function setIndex(int index, string name, string ownername memory, int8 age memory) public { ^----^ and I have tried putting memory after all the parameters and after some of the parameters (like I did above) but the error message persists.
When do we use the keyword memory? From what I understand, memory just means temporary storage (equivalent to the stack?) and storage means more permanent storage (heap?). I have seen functions being written without it and with it, so I just want to know if it is optional and when to and when not to use it.


texts:
I'm attempting to use the function send() in Solidity
I've got this error when i try to compile my contract with truffle :

  Warning: Return value of low-level calls not used.

any idea about it?

thank you


texts: getTransaction sometimes returns null when transaction is pending

texts:
I am looking to get real time transaction data as it is broadcasted to the ethereum network, so I have subscribed to pendingTransactions. This only returns the transaction hash though, so I have to call getTransaction on each hash to get more detailed data.

const Web3 = require('web3')
const web3 = new Web3('ws://localhost:8546');
web3.eth.subscribe('pendingTransactions', function(error, result){
   if (error) console.log(error);
})
.on("data", function(hash){
    let promise = web3.eth.getTransaction(hash);
    promise.then(console.log);
});

It works about 95% of the time, but sometimes it just returns null. I have no idea why this happens. I know this has been asked before here, but I found the answer to be unacceptable. The pending state of the transaction didn't prevent the other 95% from returning data, so why is the 5% having issues? I also tried putting a timeout on the ones that failed and retrying, but it's always the same ones that have issues, so the issue isn't that my cpu might be overloaded.

Is there no reliable way of getting real time transaction data before the transactions are confirmed?


texts: Any "unix philosophy" tool to write/test/deploy Ethereum contracts?

texts:
I've tried Truffle several times already and I really appreciate their work, but for some me, I find it to be way too opinionated. It has a structure for building the whole app, including the HTML, CSS, migrations. For me, my client(s) are separate projects and I don't need migrations. I'd rather just separe those concerns and have a minimal tool that does only the Ethereum-related development:

Write an Ethereum contract;
Test it by deploying to a local testnet and calling its methods from a separate JS file;
Deploy it to the testnet/mainnet when it is done.

I'm quite lost trying to extract that minimal usage from the whole Truffle workflow. Is there any tool that does that, in an Unix-philosophy way, does that, only that, and does it well?


texts:
Is there any information regarding the process to claim the DAO classic. I hold ETH in my mist wallet and would like to know if I need to sync ETC chain, is there any concerns regarding replay attack or has this issue been resolved?
The information I am finding explains how to execute a split contract in mist but I am not sure if this process is relevant to the ETH that was withdrawn from DAO. I held ETH during the HF on Polo so I believe I have a ETC address there as well.Thanks you.


texts: Parity older version force me to sync from scratch, how to fix this?

texts:
I am using private Ethereum chain. I have sync my chain using Parity/v1.7.0-beta. Now I changed the Parity version back to Parity/v1.6.10-stable; but it gives following error:

Database was created with newer client version. Upgrade your client or delete DB and resync.

[Q] Without updating Parity, is there any way to prevent this error and continue sync from where the chain remained?

Thank you for your valuable time and help.


texts:
I am trying to understand the arguments of the built-in Solidity's (or EVM's: I am not sure) call function. I know it has 4 arguments. I am trying to understand the call function at:
Syntax Error in Program

The implicit call method in the above link is:

 a.blah.value(ValueToSend)(2, 3);

I am telling the 4 argumens, kindly let me correct if I am wrong:

Amount of gas: calculated by the EVM system using some formula?
Destination address: a.blah
Ether= Value to send
input/output: input = 2 & 3: output=?

Is the following the explicit version of above call but it would invoke the fallback function instead of blah(...), is this correct?:

a.call.value(ValueToSend)(2,3)?

Some body please guide me.

Zulfi


texts: Is it possible to hard fork a private network to Constantinople?

texts:
I have a Proof-of-Authority private Ethereum network that has Byzantium EVM version and created by clique engine. I have a single miner that has Geth version: v1.8.27.

{
  "config": {
    "chainId": 23422,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "byzantiumBlock": 4,
    "clique": {
      "period": 15,
      "epoch": 30000
    }
  },
}

Please see my configuration file: custom.json.

When I start geth I get following output:

INFO [07-10|13:46:36.647] Initialised chain configuration
config="{ChainID: 23422 Homestead: 1 DAO: <nil> DAOSupport: false EIP150: 2
EIP155: 3 EIP158: 3 Byzantium: 4 Constantinople: <nil>
Petersburg: <nil> Engine: clique}"

I assume since Constantinople: <nil> in the configuration file and I cannot alter the custom configuration file there is no way I can hard fork the private chain.

Here:

  The configuration is fixed via constants in the code (see
  ChainConfig). A custom configuration can be provided in genesis
  specification file, however, this is only applicable when setting up a
  new chain.

  Hence, currently the only way to make a hard fork in a private network
  is to ensure that all participants shutdown/upgrade/restart in a
  predefined time slot.

// I have updated the geth version but in general I am not sure to check that whether the private chain is updated.

[Q] I was wondering, is it possible to hard fork a private chain that has different EVM version to Constantinople EVM?


texts: I noticed for light wallet,it is BIP32 and BIP39,how can I import the wallet into metamask

texts: I use github light wallet, it is BIP 32 and BIP 39, how can I import the wallet into metamask or myetherwallet, I tried but not working, also, the default path is m/0'/0'/0' in light wallet


texts: Trying to translate proxy deployment script from Truffle to Buidler. Not sure how

texts:
I have a custom proxy. Writing a deployment script for Buidler. Know how to do something in Truffle but not sure how to do the equivalent in Buidler.
Truffle
let testContract = await deployer.deploy(TestContract);
let customProxy = await deployer.deploy(CustomProxy, testContract.address, <param>);
let testContractCast = await TestContract.at(customProxy.address);

Buidler
let testContract = await deployContract(wallet, TestContract);
let customProxy = await deployContract(wallet, CustomProxy, [testContract.address, <param>])
let testContractCast = ???


texts:
Synced via Geth lightnode to latest block --cache=2048. (7200RPM HDD with 8GB RAM)

Then created new geth account and did swarm --bzzaccount $BZZ

I'm am able to only browse localhost, upload to local but not download (404 error). Same error with testnet.

I've also added enodes from swarm-gateway.net to admin.addpeers but still cannot connect. It shows as 40 peers connected but I'm still getting these errors.

Some of the logs are below without stopping the connection.

INFO [04-20|19:01:16.740] unable to request                        request addr=1ae4776c80028cd48884f1a4875ce36f8eb3cd9423c459cc2376a78b065e7861 err="no peer found"

INFO [04-20|19:01:20.144] unable to request                        request addr=0f68b0450c97f77f8fe77899b86263dad6f0a55fbe6f6ae10cd11732c752dd04 err="no peer found"

ERROR[04-20|18:52:10.296] Message send error, dropping peer        peer=a2239c59643d0256 err="write tcp 192.168.0.25:49187->52.232.7.187:30405: i/o timeout"

ERROR[04-20|19:06:27.949] peer.handleIncoming                      err="Message handler error: (msg code 1): client params 'SYNC|0|h' not provided to peer b4669fadcedad677b2b810c9b91aaa9a94e61d9fc8e2165cb0c93401c1a3002e"

Been running for 2 hours so far.


texts: How to develop large applications on top of blockchain?

texts:
I am trying to develop a social media platform on top of the Ethereum platform and integrate it with my currency (an ERC20 Token). This platform will allow users to post media files (articles/images/videos) and others will view and comment. So I am here for answers of a few questions.

First Question: What is the recommended way to store media files in DApps?
I know two options; IPFS and SWARM but don't know what would be best suited in my scenario. In fact swarm is in test phase.

Second Question: What are the recommended ways to authenticate users in DApp?
To avoid authentication on basis of long public keys I found Uport, can be used in DApps for authentication of users in a user friendly way but it is still in Alpha.

Third Question: What techonology stack is recommended for frontend (Mobile,Web)? Is there any need for backend or middleware for DApps?

Fourth Question: Is it possible to develop a system in a conventional way with centralized database (marai/mongo/casendra) communicating with backend but backend is also linked with blockchain for saving hashes of data for its proof of existence.

Fifth Question: What are the good practices or recommended way to architect and develop huge blockchain based systems (Dapps) ?

Please feel free to edit if there is something missing that could be helpful for developing DApps.


texts: Casting between contract classes in Solidity

texts:
I wonder how do you cast between classes in solidity.

For example, if I have these classes:

contract Token {
    function getFive() public returns (uint) {
        return 5;
    }
}

contract MyToken is Token {
    function getSix() public returns (uint) {
        return 6;
    }
}

And I have this variable in other contract:

contract TokenSale {
    Token token;

    function TokenSale(address tokenAddress) {
        token = Token(tokenAddress);
    }
}

contract MyTokenSale is TokenSale {
    function MyTokenSale(address tokenAddress) TokenSale(tokenAddress) {
        // Here I want to call to MyToken's getSix funciton
    }
}

How can I downcast the token variable in MyTokenSale to call getSix function, assuming I can't change TokenSale's code?

As an OOP language, I'm sure that Solidity allows you to do it somehow, but for some reason I couldn't find it in the docs.

Thanks!


texts: The structure of a DAPP and contracts compared to a traditional web platform

texts:
I have been doing quite a bit of research into Solidity and Ethereum contracts in recent days (docs and tutorials) but I have some questions that I am still stuck on. I come from a commercial Web (front & back) background as well as IOS App development so I have a pretty good knowledge of site structure and frameworks.

The following questions are based on the assumption that we were building lets say a microblogging platform.

I understand that we have to think of Contracts as "classes" similar traditional web development. Does that mean that for our example project we would create multiple contracts to complete the final project and link them together? For example a user contract, blog post contract etc.
If we do have multiple contracts I assume that they are connected together via their address?
If all users call the blog post contract at address xxxxxxx in terms of the blog posts that each user makes are they stored against/inside the address of the contract that is called and if so is there a limit to the number of posts/data stored  at the address?

If we had lets say 2 million posts would they all be stored within the contract at that address?

Looking at this in a traditional database sense i.e MYSQL how is data then searched for within the contract? For example lets say I want to search by all posts from user x or posts that contain a certain string?
If i want to read data within the contract i.e the total number of users or retrieve the total number of posts do this cost gas? I have read that reading doesn't but some people say that it does if it is calling a function within a contract.

If someone could answer these that would be great.

Thanks All


texts: Failed transaction (Error encountered during contract execution) on Uniswap Router02?

texts:
I wish to send a transaction for a Uniswap swap with a path of 3 tokens: [weth, dai, chainlink].
The transaction is mined, but fails, and the error message is not enough for me to debug:
fail:  Warning! Error encountered during contract execution [Reverted]

https://kovan.etherscan.io/tx/0x50028fa99475e55cbdfc2de2a5ee3e2f7df10419d437ac7e08f85e627503e8eb
Looking at the internal transactions, it seems a transaction from Router02 to the pair address weth-dai is failing, although I had pre-approved Router02 to be able to send weth (see Router02 weth approval tx).
Why is this transaction failing, and how can I debug this?
The transaction part of my code is here:
const init = async () => {
  // Fetch the existing pair of tokens = Uniswap exchange
  const weth = WETH[chainId];
  const dai = await Fetcher.fetchTokenData(chainId, daiAddress);
  const chainlink = await Fetcher.fetchTokenData(chainId, chainlinkAddress);

  const pair_weth_dai = await Fetcher.fetchPairData(dai, weth, provider);
  const pair_dai_chainlink = new Pair(new TokenAmount(dai, '2000000000000000000'), new TokenAmount(chainlink, '1000000000000000000'));

  console.log("pair_weth_dai volumeToken0 = ", pair_weth_dai.reserve0.toSignificant(6));
  console.log("pair_weth_dai volumeToken1 = ", pair_weth_dai.reserve1.toSignificant(6));

  console.log("pair_dai_chainlink volumeToken0 = ", pair_dai_chainlink.reserve0.toSignificant(6));
  console.log("pair_dai_chainlink volumeToken1 = ", pair_dai_chainlink.reserve1.toSignificant(6));

  const route_weth_dai = new Route([pair_weth_dai], weth);

  const trade = new Trade(route_weth_dai, new TokenAmount(weth, ethers.utils.parseEther("0.01")), TradeType.EXACT_INPUT);
  const slippageTolerance = new Percent('50', '10000');// 0.005 = 0.5%

  const amountOutMin = 0;
  const amountOutMinHex = ethers.BigNumber.from(amountOutMin.toString()).toHexString();

  // path with 3 addresses
  const path = [weth.address, dai.address, chainlink.address];

  const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
  const value = trade.inputAmount.raw;
  const inputAmountHex = ethers.BigNumber.from(value.toString()).toHexString();
  const amountInHex = ethers.BigNumber.from(value.toString()).toHexString();

  // ========================
  // swapTokensForExactTokens
  // ========================
  Router02_address = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
  const account = signer.connect(provider);

  const uniswap = new ethers.Contract(Router02_address,
    ['function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)'],account);

    gasPrice = await provider.getGasPrice();

  const tx = await uniswap.swapExactETHForTokens(
    amountOutMinHex,
    path,
    to,
    deadline,
    {
      value: inputAmountHex,
      gasPrice: gasPrice.toHexString(),
      gasLimit: ethers.BigNumber.from(300000).toHexString()
    }
  );

  console.log(`Transaction hash: ${tx.hash}`);

  const receipt = await tx.wait();

  console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

init();

The reserves seem sufficient for an input of 0.01 ETH:
pair_weth_dai volumeToken0 =  59.24
pair_weth_dai volumeToken1 =  1.75332
pair_dai_chainlink volumeToken0 =  1
pair_dai_chainlink volumeToken1 =  2


texts: ICO tokens arrived back to address from which I sent ETH, but they won't load in wallet

texts:
I could use some help. I bought an ICO. Sent ETH to the ICO. The ICO sent back  tokens to the same address.

Etherscan proved it, including an overview that stated smart contract was executed.

HOWEVER, I still have a miniscule amount of ETH in the wallet from which I sent payment, like $2. So obviously, the ICO token won't load into the wallet.

How do I empty the wallet of ETH, so the ICO token can load and this disaster is done, and then how do I load the wallet once it's empty (beyond refreshing the wallet, if there's more).

I'll take links for instructions if it saves time. Not my first crypto purchase. Just my first ICO purchase.

Thank you in advance


texts: Distinguishing erc721 transactions from the response of txlist on etherscan

texts:
I am making some erc721 transactions. I can retrieve those transactions using the etherscan api like this

https://api.etherscan.io/api?module=contract&action=txlist&address=0xb30c5db4ca271653535b846f237c4a8d0d6fb32d&startblock=0&endblock=99999999&page=1&offset=20&sort=desc&apikey=

{"blockNumber":"6878479","timeStamp":"1544697153","hash":"0x68dffa9cd6b2f408a5bc1bb9c3cc9a0344e9e7e71029e551f3a5b35673bad362","nonce":"53","blockHash":"0x2e0968d71243a531b80db3a1feba3b0b16f664ae16cf3a992e4fd3fd8a40667c","transactionIndex":"153","from":"0xb30c5db4ca271653535b846f237c4a8d0d6fb32d","to":"0x06012c8cf97bead5deae237070f9587f8e7a266d","value":"0","gas":"69379","gasPrice":"5100000000","isError":"0","txreceipt_status":"1","input":"0xa9059cbb0000000000000000000000003b7b6f8c1b9fe9be5b59326a3e8c695fce3a4e0800000000000000000000000000000000000000000000000000000000000c90c4","contractAddress":"","cumulativeGasUsed":"7480061","gasUsed":"69379","confirmations":"4750"}

This is a cryptokitties transaction. However, how do I distinguish this from a erc20 transaction. I checked their other apis https://etherscan.io/apis#contracts

but, none of them seem to explicitly state the type of contract/transaction.


texts: Contract with mapping(address->bool) does not work as expected

texts:
I have a very simple Solidity contract:

contract AccessManager {

    mapping(address => bool) public registry;

    function grantAccess(address assetAddr) {
        registry[assetAddr] = true;
    }

    function isAuthorized(address assetAddr) constant returns (bool) {
        return registry[assetAddr];
    }
}

Logic is simple: whenever I call grantAccess(...) method an address (passed as an method argument) has to be added to mapping with "true" value.

The problem is that this simple code does not work. After I send a transaction to execute grantAccess("0x.....") method, I call isAuthorized("0x....) method and it always returns "false".
I've tried it with Chrome extension called "Sol" and with .NET Etherum API. The result is always same: isAuthorized(...) contract method returns "false" no matter what I do.

Here is how I call contact methods in Sol extension:

I think the problem is in passing string as an address argument but I have another contract where I do a similar thing and it works just fine.

Did somebody experience similar issues?


texts: Error with wrong calculation of gas price and value after lots of iterations

texts:
I am trying to code something that empties an address and sends that amount to my main-wallet. In order to get familiar with sending raw transactions and manually setting the eth-amount, I've tried some testprogram. My logic is to send balance from Account1 <---> Account2 in an infinite loop.

However that works many many times, but at some point either "ERROR!Error: insufficient funds for gas * price + value" or an error with a duplicate transaction happens.

I don't understand why that is the case, any ideas?

var Web3 = require('web3');
var web3 = new Web3(new
Web3.providers.HttpProvider('https://ropsten.infura.io/'));
const ethereumjs = require('ethereumjs-tx');
var BigNumber = require('bignumber.js');

var account2 = {
'address': '0xaCC9a59A4266F40846664992bE9bACD607716b7c',
'privateKey': '0x26c1999d1b6e51eda8ed8912cc678fe48879b8cefea1af11835d9d64669a818a'
}

var account = {
'address': '0x379ccad8923B1e4CF79E9dB125d70f0843cb2C35',
'privateKey': '0xc129caaa7a963e1c67bd8bf0586dcf4e47b6ae7e9294962886178a9acb842290'
}

recBalanceCheck(account,account2);

function recBalanceCheck(account, account2) {
setTimeout(function () {
    var balance = web3.fromWei(web3.eth.getBalance(account.address));
    // var balance =(web3.eth.getBalance(account.address));
    console.log('awaiting payment... current balance is: ' + balance.toNumber());
    if (balance.toNumber() > 0) {
        console.log('payment received. Balance is now ' + balance.toNumber());
        console.log('sending ether to main account...');
        sendEther(account, account2.address, balance.toNumber(), 3);
        recBalanceCheck(account2, account);
    } else {
        recBalanceCheck(account, account2);
    }
}, 10000);
}

function sendEther(senderAccount, receiveraddress, amount, gwei) {
var account = senderAccount.address;
var privateKey = senderAccount.privateKey;
privateKey = privateKey.slice(2, privateKey.length);
privateKey = Buffer.from(privateKey, 'hex');
var gas = 21000;
var gasPrice = new BigNumber(web3.toWei(gwei, 'gwei'));
var cost = gasPrice.multipliedBy(gas);

web3.eth.getTransactionCount(account, function (err, nonce) {
    var tx = new ethereumjs({
        nonce: nonce,
        gasPrice: web3.toHex(web3.toWei(gwei, 'gwei')),
        gasLimit: 21000,
        to: receiveraddress,
        value: web3.toHex(new BigNumber(web3.toWei(amount, 'ether')) - cost)
    });
    tx.sign(privateKey);
    var raw = '0x' + tx.serialize().toString('hex');
    web3.eth.sendRawTransaction(raw, function (err, transactionHash) {
        if (err) {
            console.log('ERROR!' + err);
            process.exit();
        }
        console.log(transactionHash);

    });
});
}


texts: Can I run Geth connected to public network without syncing and do a smart contract function transaction and expect it to mine?

texts:
Is there a way to run Geth connected to public Blockchain without syncing and still expect my smart contract function transaction to be mined ?? as following answer Can I run Geth without syncing? here uses "--maxpeers 0" so its not connected to any peers,so no way to mine the transaction.

Can i send smart contract function  transaction( execute smart contract function) without syncing the node ??
and after sending can i expect it to be mined??


texts: Does an SSTORE where the new value is the same as the existing value cost gas?

texts:
For example (in Vyper):
@external
def foo(bar: uint256):
  self.baz = bar

foo(3)
foo(3) # Is the gas cost here still 5000?

Is it better to do this instead?
def foo(bar: uint256):
  if self.baz != bar: # Will this check save gas from unnecessary SSTORE's
      self.baz = bar


texts: Smart contract design: Interacting with DAI

texts:
Let's say I want to build a product that let companies settle cross-border payments for invoices using DAI (https://makerdao.com/en/dai/) as medium of exchange to ensure stable value of the transaction.

I already started building a Prototyp but got stuck at some point. The idea is the following:

Biller creates an invoice that is stored on a smart contract
Receiver interacts with dapp to settle payment in DAI to the smart contract
Smart contract act as custody and redirect payment to biller once the invoice is fully payed (Receiver can also pay partially)

I was already able to to the following:

Created a smart contract that let biller create and manage invoices
Created a ethers.js based dapp that let receivers:

unlock the usage of DAI token ("approve" function on DAI smart contract)
Settle payment (using transferFrom to send DAI tokens to smart contract)

However, that's where I'm stuck. The part that is missing:

Incoming payment from receiver is stored in smart contract
Smart contract run some function to trigger payment to biller (if invoice was fully payed)

The issue:

I came to understand that there are no ways to trigger my smart contract once the receiver sends the DAI token, thus the DAI token would be transfered to the smart contract but wouldn't trigger the smart contract logic to update the invoice status and forwarding payment to biller. Given this scenario, how could possible solutions look like?


texts: How to optimize the upload of data onto the blockchain so that the miners will choose the transactions while paying relatively lower gas price?

texts:
If I have 10 transactions that would fill 10 blocks worth of gas, would the transactions be more likely to be included in a block if I send 20 transactions that fill 1/2 of each block? What about 40 that fill 1/4?

How do the miners handle large transactions of this type? Can I do something as described above and pay a relatively low gasPrice? 10GWei? 5GWei?


texts: What is from address and Topic address in Remix log

texts:
I am invoking the buyTicket function of contract from account "0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C"  in remix IDE  with 20 ethers which is clear from log but confused what is "from" and "topic" addresses  in Remix ide as per log below any idea please ?  Thanks

  event Deposit(address _from, uint _amount);

 function buyTicket() public payable returns (bool success) {
    if (numRegistrants >= quota) { return false; } // see footnote
     registrantsPaid[msg.sender] = msg.value;
     numRegistrants++;
     emit Deposit(msg.sender, msg.value);
     return true;
  }

Remix Ide Log

[
    {
        "*from*": "0x692a70d2e424a56d2c6c27aa97d1a86395877b3a",
        "***topic***": "0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c",
        "event": "Deposit",
        "args": {
            "0": "0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C",
            "1": "20",
            "_from": "0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C",
            "_amount": "20",
            "length": 2
        }
    }
]


texts: Passing array of struct as parameter: Only libraries are allowed to use the mapping type in public or external functions

texts:
I am trying to push multiple items to the array of structs in the contract. Couldn't find a clear answer if it is possible to pass an array of struct as a parameter.

Apparently I can't but I get a different kind of an error from the compiler. It thinks I am passing a mapping: Only libraries are allowed to use the mapping type in public or external functions.

Here's the code

mapping (address => Review[]) reviewsMap;
mapping (address => uint24) reviewCounts;

function addMultipleReviews(Review[] memory array) public {
    address author = msg.sender;
    for (uint i=0; i < array.length; i++) {
      reviewsMap[author].push(array[i]);
    }
    reviewCounts[author] = reviewCounts[author] + array.length;
  }

Is this not allowed? If so what would be an alternative to add multiple Reviews?


texts: How the hashing of the block data ensures the data integrity?

texts: In ethereum, as a node controller I can able to access the leveldb. If I try to modify some value  directly into the db, the value of the new hash and the next block's parent hash doesn't match right ?. How the current version of ethereum handle this problem? . Does it need to went over each and every block to check the data integrity ??


texts: How do I create and manage my own mining pool?

texts:
I realize that there are already answers to the question, but I don't think they are detailed enough.

For my use case, I have 4-5 gaming PCs, some desktop and some laptop, laying around the house. I would like to create my own pool and put them all to work.

A previous answer states that you simply run geth on a master machine and then run ethminer on your other machines which are pointing to the master. That's great, but how do the other machines know which account they are mining for? Also, is there a way to track productivity on a per-machine basis. I would like to know how much output I am getting from each machine.

Thanks in advance!


texts: How to save data in my private blockchain?

texts:
I am running a private blockchain using geth as the client.
I want to save some custom variables in my chain. I know there is a practical limitation on the storage capabilities as it would require ether.
How can I write data to the blocks as they are created and then retrieve the data later?


texts: I am trying to use chainlink using remix and i followed the chainlink docs

texts:
I am facing this issue,What to do now?
My Code
pragma solidity ^0.6.7;
import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
contract PriceConsumerV3 {
    AggregatorV3Interface internal priceFeed;

    constructor() public {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
    }

    function getLatestPrice() public view returns (int) {
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }
}


texts:
I need help with the following :
I have made an EOS token transfer transaction from myetherwallet account to another account and I have been told it can be reversed
"You would need this account to sign a transfer() transaction back to you"
Could anyone explain how this can be done?
Many thanks
L


texts: Can someone explein me this Multi mint function (Solidity)?

texts:
I came accross this function to mint token for a crowdsale but I don't understand the meaning of the bit shift operations and what bit array should represent.. what is this code doing ? The code can be found here: https://github.com/bokkypoobah/ZeroSumCrowdsaleContractAudit/blob/9fe4765a0a0394a476a618608a4914754651ce59/contracts/Ledger.sol#L290

The function is this one:

function multiMint(uint nonce, uint256[] bits) onlyOwner {
    require(!mintingStopped);
    if (nonce != mintingNonce) return;
    mintingNonce += 1;
    uint256 lomask = (1 << 96) - 1;
    uint created = 0;
    for (uint i=0; i<bits.length; i++) {
        address a = address(bits[i]>>96);
        uint value = bits[i]&lomask;
        balanceOf[a] = balanceOf[a] + value;
        controller.ledgerTransfer(0, a, value);
        created += value;
    }
    totalSupply += created;
}


texts:
I am running ethereum wallet v0.7.4, once the block had updated it seems as though it has killed my wallet and it keeps crashing as soon as I open it. I see my keystore in terminal, I would like to move it.

I have tried cp /keystore/. /location which didn't work so I tried cp -r /keystore/. /location/ and still no luck.

I am on a mac....so I thought perhaps I could show hidden files and just copy them that way....are there any other ways?
Thanks

Chris


texts: The correct approach to changing inherited variable content

texts:
What is the correct approach to change the content of an inherited variable?

If contract A inherits contract B which has an variable b,  and contract A is initialising the inherited variable b through its constructor or one of its functions.  Should contract A then declare it as A.b = 123; or b = 123;


texts: so I'm very new to crypto and such but I thought it would be fun to make my own token. The code initially compiled on https:// remix, but I realized the following morning that I had to run the code on http:// (unsecured) remix because of MetaMask. I pasted in my code again, but this time it would not create a contract (although no compiler issues appeared). I went back to https:// to see if that was the issue but that also didn't work. Below is the code I am using (everything with {{_}} is filled in in my actual code, I just didn't want to show all of that on here). Additionally, I am using the default settings on remix. Any help would be tremendously useful :). Code: https://gist.githubusercontent.com/bajcmartinez/c1cefbb3b1375d037f07b7b779568e42/raw/7028062f99ec80e69f941012fd0a793b862ed657/erc20-token.sol


texts: What are best practices for monitoring the OpenEthereum (Parity) logging?

texts:
Monitoring of the logging output of the Ethereum clients is essential for stable blockchain operation.
Do you have recommendations, experiences and/or lessons learned
concerning the logging of OpenEthereum/Parity nodes working with PoA?
Interesting aspects are:

What are proper setting for the log levels an why? What modules should be
included in the logging?
How to detect serious issues like network split, syncing problems and/or security related attacks?
Do you know already prepared solutions for standard monitoring tools (like Splunk,
Kibana) available?
Are there regular expressions to filter interesting aspects?
How are Testnetworks like Kovan monitored?

Not in scope for this question:

Network Dashboards (e.g. Ethstats)
Block Explorers
Ethereum Event Exploreres


texts:
Here is my code :

pragma solidity ^0.4.14;

contract AdminSetUp {   // contract for adding new admin
address private creator = msg.sender;
address[] public adminlist;
uint public count;

modifier onlyCreator {  // only creator of contract is allowed to add admin
    if (msg.sender == creator)
    _;
}

function addMember(address _newadmin) public onlyCreator returns (uint) {
    adminlist.push(_newadmin);
    count = adminlist.length;
    return count;
 }

}

this code allows to add admin those are already there. How to avoid this?


texts: How to start two geth instances (console and mist)

texts:
Once I start mist I can't start run geth on terminal. It says

  "Error starting protocol stack: listen udp :30303: bind: address
  already in use"

or

  "Fatal: Error starting protocol stack: resource temporarily
  unavailable".

Is it possible to run two geth as one time?


texts:
Parity V1.4.9 giving this error on startup frequently.

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

How can I fix this and how can I prevent it happening again?


texts: Can Qorum Blockchain supports partail transaction encryption?

texts:
My use case is that we need to protect sensitive data in the transaction in blockchain.  But we want to open other data in the same transaction to the public,  Can Quorum support the above mentioned transaction type?  If not, any other blockchain platform support it?

Please advise.  Thanks.

Wilson


texts: Using web3.js to interface with smart contract

texts:
I am a beginner in Dapp and don't know about web3.js. I complie myslef contracts with Truffle. I did write the following contract:

pragma solidity ^0.5.12;

  contract TEST{
    bytes public name="Yerevan is love";

    function fname() public view returns(string memory){
      return string(name);
     }
   }

and i want to see the "Yerevan is love" by alert() dialogbox in JavaScript code. Truffle provided the following .js file to interface between browser and smart contract:

App = {
  web3Provider: null,
  contracts: {},

  init: async function() {
    // Load pets.
    $.getJSON('../pets.json', function(data) {
      var petsRow = $('#petsRow');
      var petTemplate = $('#petTemplate');

      for (i = 0; i < data.length; i ++) {
        petTemplate.find('.panel-title').text(data[i].name);
        petTemplate.find('img').attr('src', data[i].picture);
        petTemplate.find('.pet-breed').text(data[i].breed);
        petTemplate.find('.pet-age').text(data[i].age);
        petTemplate.find('.pet-location').text(data[i].location);
        petTemplate.find('.btn-adopt').attr('data-id', data[i].id);

        petsRow.append(petTemplate.html());
      }
    });

    return await App.initWeb3();
  },

  initWeb3: async function() {
    /*
     * Replace me...
     */

    return App.initContract();
  },

  initContract: function() {
    /*
     * Replace me...
     */

    return App.bindEvents();
  },

  bindEvents: function() {
    $(document).on('click', '.btn-adopt', App.handleAdopt);
  },

  markAdopted: function(adopters, account) {
    /*
     * Replace me...
     */
  },

  handleAdopt: function(event) {
    event.preventDefault();

    var petId = parseInt($(event.target).data('id'));

    /*
     * Replace me...
     */
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});

I can see "Yerevan is love" in truffle console  but i want do this in browser. I don't know about working with the above codes.


texts: Can I use the `e` notation on MyEtherWallet?

texts:
I just found out about the existence of the "minification" process.

You probably know about it already, but if you don't, it basically means that
1000 = 10^3 = 1E3 .

So 1000 minified is 1E3.

Or 10'000'000 is 1E7.

And 0.000'000'000'000'000'01 = 1E-17

My understanding is that by using this notation not only you get to reduce big numbers by a few bits (i.e. 100'000'000 = 1E8 ), but you also get to stop having to count zeros all the time, thus reducing human-related mistakes (of which I usually make many).

Questions are:

Can I specify 1E6 gas units or 2*1E6 gas units in MyEtherWallet ?
Can I specify 1E-17 ETH in MyEtherWallet?


texts: Security analysis tool for Ethereum smart contracts

texts:
I'm looking for the best value affordable code checkers to find vulnerabilities in solidity code. I came across on Mythril[1] but I wonder which other products are used.

[1] https://github.com/b-mueller/mythril


texts:
I run Parity on the command line using:

parity --chain dev

I run this so I can develop and test smart contracts. The problem is, whenever I try to develop a Smart Contract by clicking Contract -> Develop, the connection closes and this error shows up on the command line

2017-08-31 13:08:04  WS Error <Io(Error { repr: Os { code: 10054, message: "An existing connection was forcibly closed by the remote host." } })>

Any thoughts on how to fix this?

EDIT: I installed it using the Parity installer for Windows.


texts: Why setting fields of a memory object and then storing it all at once is more expensive than storing each field separately?

texts:
Mind the following code:

// This is expensive
obj.a = uint32(obja);
obj.b = uint32(objb);
obj.c = uint32(objc);
objs[objName] = obj;

// This is much cheaper
objs[objName].a = uint32(obja);
objs[objName].b = uint32(objb);
objs[objName].c = uint32(objc);

Where obj is a memory struct of type

struct Obj {
    uint32 a;
    uint32 b;
    uint32 c;
}

And obja, objb and objc are uint32s. Why the first version is more expensive if, in theory, it could be done in a single SSTORE call, whereas the latter would require 3?


texts: Adding Uniswap liquidity via javascript and truffle?

texts:
I am trying to add a liquidity to Uniswap on the Ropsten network using truffle and javascript.
I am connecting to the addLiquidityETH function as described here in the Uniswap documentation:
https://uniswap.org/docs/v2/smart-contracts/router02/#addliquidityeth
When I connect to the Uniswap Router V2's addLiquidityETH function, I get a TRANSFER_FROM_FAILED error.
My javascript code is as follows:
  createPair() {
    const that = this;
    return new Promise((resolve, reject) => {

      const contract = require('@truffle/contract');
      const transferContract = contract(UniSwapRouterAbi);
      transferContract.setProvider(that.web3);
      transferContract.at('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D').then(function(instance) {
        console.log('we are inside the router contract');
        return instance.addLiquidityETH(
           '0xff5254f440816a778851b21d2dfe879b7bad182d',
           10000000000,
           5000000000,
           1000000000,
           '0xaC3c34E28D0679442e550a1177a6ce472F8C4156',
           1598313600,
          {
            from: that.account,
            gas: 4000000,
            value: 1000000000
          });
      }).then(function(status) {
        if (status) {
          console.log('adding liquidity worked');
          return resolve(status);
        }
      }).catch(function(error) {
        console.log(error);
        return reject('transfer.service error');
      });
    });
  }

Here '0xff5254f440816a778851b21d2dfe879b7bad182d' represents an example token I created to test the interface. The other address is from my testing account on metamask
I am able to successfully connect to the function and router contract. Is there something wrong with the way I am using the function or the parameters I am adding? Also I am assuming the values are sent in wei denominations.
The transaction fails on the network: https://ropsten.etherscan.io/tx/0xdaf67fc7c25028305d6330e10d717b90e775dba50f80084f06218386ee30b8c5
Thanks


texts: Why do we need both nonce and mixhash values in a block?

texts:
Looking over the sample genesis blocks, I notice that both nonce and mixhash values can be assigned independent values. Reading the yellow paper it's mentioned that:

mixhash: is a 256 - bit hash which proves combined with the nonce that a sufficient amount of computation has been carried out on this block
nonce: is a 64 - bit hash which proves combined with the mix-hash hat a sufficient amount of computation has been carried out on this block

meaning that these values together with the difficulty are used in mining. But why are they both used?


texts:
I have a mapping with the following structure:

mapping(uint256 => mapping(address => SOME_STRUCT)) public submissions;

delete submissions[uint256] is not allowed(compiler error).

delete submissions[uint256][msg.sender]  is allowed(no compiler error).

The remove function needs to be restricted i.e only the manager of the contract is allowed to delete from the submissions mapping. But the address in the inner mapping serves as the key and is an arbitrary address. How would i go about deleting the inner mapping?


texts: TransferHelper: TRANSFER_FROM_FAILED on WETH/TOKEN

texts:
I am using this swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline) to swap WETH to DAI on ropsten and filled directly the  parameters and set the value = 0 on remix but before that I approve both DAI and WETH with large values, now I am getting  TransferHelper: TRANSFER_FROM_FAILED error. I made sure that I have enough WETH both in my wallet and contract, how do I resolve this issue?
However I am not entirely sure if the WETH reside on my contract as when I wrap my eth it is stored on WETH contract
My solidity code for approve and wrapping
function wrap() public payable restricted {
  if (msg.value != 0) {
    WETH.deposit{value : msg.value}();
  }
}
function unwrap(uint amount) public payable restricted {
  if (amount != 0) {
    WETH.withdraw(amount);
    msg.sender.transfer(address(this).balance);
  }
}
function approve(uint tokenAmount, address tokenAddress) external restricted {
    IERC20 token = IERC20(tokenAddress);
    token.approve(address(uniswapRouter), tokenAmount);
}


texts: methods.myMethod.call not return value I wanted

texts:
I am attempt to get an address using methods.call(). And it's something error.

JS

var rcAddr = "0x683d1602fa7252d49cda8ac414c1641a56e73d03";
var methodName = "Access Control";
var register = new web3.eth.Contract(rcAbi, rcAddr);
var accAddr = register.methods.getContractAddr(methodName).call({
    from: "0x70f99451d9878055ca8986021ca78f6edb8f1720",
    gas: 10000000
});
console.log(accAddr)

solidity

 function getContractAddr(string memory _methodName) public view returns (address _scAddress){
        bytes32 key = stringToBytes32(_methodName);
        _scAddress = lookupTable[key].scAddress;
    }
}

I think I can get a address from function, but it's wrong. So I use console.log(accAddr) output the result.

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

It return something else. I'm confused. methods.myMethod.call in document say

  Returns
  Promise returns Mixed: The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices:

So It should return the value but why not.


texts: How Much Space is Kovan Network to Download (Oct 2018)

texts: How much space is it? How long did it take to download?


texts:
I noticed that the remix IDE now says that I can run Javascript code from .js file. I can't find any documentation. Is this possible? How do you do this?

Thanks!


texts: Separated ETH/ETC but how to transfer remaining ETC?

texts:
I'd be very grateful for the community's help/ guidance here as I'm not even sure what I've done exactly!

I had about 1000 ETH on my mist wallet which had about 300 ETC in that (pre-fork amount in the wallet). Thinking that I would do what I read to split ETH & ETC using Kraken or an exchange, I moved 300 ETH from my wallet to Kraken. However, the split never happened and Kraken only showed me a balance of ETH, not ETC. Additionally when I then checked my account balances on gastracker, I was told that my account was very vulnerable to a replay attack. So, I now moved everything back to my mist wallet - which is back to a total of 1000 ETH and then moved ALL my balance to another account on the same wallet.

So, where I stand now is - I have 1 account on the wallet with 1000 ETH and the other main account with 0 ETH but 300 ETC (as per Gastracker). My question is ---- how do I move the 300 ETC from this wallet to an exchange so I can trade it??? The balance in that wallet is 0 as per Mist and 300 ETC as per gastracker..

Please help!!

Thanks.


texts: How can I Interact with an ethereum smart contract via Java

texts:
I have successfully created smart contract on Ethereum rinkeby network and deployed as well.
Now, I want to call the methods of deployed contract through Java not through JS.
I know, there is one API web3j- through which we can interact with smart contracts but unfortunately I am not being able to get the exact lines of code.

If anyone has implemented this, then please share the code.


texts:
I was using "truffle test" for testing with JS. gives this error.
here is the code of that part.

it('transfer success', function(){
    return Eve.deployed().then(function(instance){
        tokenInstance = instance;
        // testing "require" first by sending larger than the senders balance
        return tokenInstance.transfer.call(accounts[1], 9999999999999);
    }).then(assert.fail).catch(function(error){
         assert(error.message.indexOf('revert' >= 0, 'error message must contain revert'));
         return tokenInstance.transfer.call(accounts[1], 250000, { from: accounts[0] });
    }).then(function(success){
        assert.equal(success, true,'returns true');
        return tokenInstance.transfer(accounts[1], 250000, { from: accounts[0] });
    }).then(function(receipt){
        assert.equal(receipt.logs[0].length,1, 'transfer one event');
        assert.equal(receipt.logs[0].event, 'Transfer', 'the "Transfer" event');
        assert.equal(receipt.logs[0].args._from, accounts[0], 'logs the account thr tokens are transferred from');
        assert.equal(receipt.logs[0].args._to, accounts[1], 'logs the account thr token are transferred to');
        assert.equal(receipt.logs[0].args._value,250000, 'logs the transfer amount');
        return tokenInstance.balanceOf(accounts[1]);
    }).then(function(balance){
        assert.equal(balance.toNumber(), 250000,'adds amount to recevers account');
        return tokenInstance.balanceOf(accounts[0]);
    }).then(function(balance){
        assert.equal(balance.toNumber(), (10000000 - 250000),'remaining balance of senders account');
    });
});

upon "truffle test" gives the following error.
ReferenceError: accounts is not defined
background : creating erc20 token as per standards.
the first 2 tests run successfully
How can i troubleshoot this?