texts: Possible to store data outside of contracts?

texts:
I am trying to wrap my head around a specific scenario:

A company wants to leverage Ethereum's blockchain by storing, for example, hashes of documents and storing them on the network. The Idea is that once the data is published, the company has no access or control over it. How can this be accomplished?

My take/answer:

Create a contract that stores variables (like a document hash) and then query when needed. Problem is, you'll need a contract account which has the contract. This will most likely be an account that the company owns in order to interact with the network. So, this method is not acceptable in this situation.
Another option is to send desired data as transactions input/payload. Unless the transaction can be made to "the network" and the data can be retrieved by querying the network or account not owned by the company, then this approach won't work either. What I currently know, this is not possible.

Any takes on my answers and or ways to accomplish this for the given scenario? I'm not looking for plain answers but rather resources and guidance (though plain answers would be helpful too :p)


texts: Can you embed information into individual tokens?

texts:
Say it is a gaming token. Could you for example embed and update the high score each time the token holder plays the game? The idea being the token would be worth more the higher the score.

Forget there use case. I'm just wondering about being able to include and continuously update individual tokens with specific information to show individual tokens to essentially have different value.


texts:
I want retrieve mul() from another sol, but its not works. If I used in the same file works but I need import. My error:
browser/test1.sol:22:28: TypeError: Member "mul" not found or not visible after argument-dependent lookup in uint256. uint256 adminFee = amount.mul(TEAM_PERCENT).div(PERCENT_DIVIDER); ^--------^
pragma solidity ^0.5.4;

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

  /**
  * @dev Multiplies two numbers, throws on overflow.
  */
  function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
    if (a == 0) {
      return 0;
    }
    c = a * b;
    assert(c / a == b);
    return c;
  }

  /**
  * @dev Integer division of two numbers, truncating the quotient.
  */
  function div(uint256 a, uint256 b) internal pure returns (uint256) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    // uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return a / b;
  }

  /**
  * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
  */
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    assert(b <= a);
    return a - b;
  }

  /**
  * @dev Adds two numbers, throws on overflow.
  */
  function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
    c = a + b;
    assert(c >= a);
    return c;
  }
}

pragma solidity ^0.5.4;
import "./AddBalanceToContract.sol";
import "./SafeMath.sol";

contract test1
{

    uint256[] public BOX_PERIOD = [50 days, 28 days, 20 days];
    uint256 constant public MIN_DEPOSIT = 5000000;
    uint256 constant public TEAM_PERCENT = 100;    //10%
    uint256 constant public PERCENT_DIVIDER = 1000;
    address payable constant public TEAM_WALLET = address(0x41e0e105b876f7d109468e76b92385f6cc2d9b057f);

    function deposit() public
    {
        uint256 amount = msg.value;
        require(amount >= MIN_DEPOSIT, "Your investment amount is less than the minimum amount!");

        uint256 adminFee = amount.mul(TEAM_PERCENT).div(PERCENT_DIVIDER);
        TEAM_WALLET.transfer(adminFee);
    }

    function getEthBalance(address _addr) public view returns(uint) {
        return _addr.balance;
    }

}


texts: Given a block number, how do I find the block hash using Nethereuem?

texts: Using Nethereum, I would like to get the block hash given a block number (i.e. block height).


texts: Having issue to upload 10,000 file into IPFS directly

texts:
I'm trying to upload a lot of JSON files (10,000 JSON file) in IPFS using the following API from py-ipfs-http-client package, and go-ipfs v0.7 and when I try to open the hash with localhost IPFS domain it works http://localhost:8081/ipfs/<hash> but not with the main ipfs link https://ipfs.io/ipfs/<hash>, just keep loading forever.
I tried again the same process the next day, but just a random small selection of the hashes started to work in https://ipfs.io/ipfs/<hash>, but the other do the same.
Then I tried to use Pinata website to upload these JSON files but it kept loading without any successful message, and when I did a refresh it didn't work.
I need your help to understand this behavior. And what may I do other than that to solve this challenge?
Thanks.


texts: Error: Cannot find module 'ethereumjs-wallet'

texts:
A truffle test needs ethereumjs-wallet

const wallet = require('ethereumjs-wallet');

I tried

npm install ethereumjs-wallet

and even

npm uninstall ethereumjs-wallet
npm install --save ethereumjs-wallet@0.6.0

but ethereumjs-wallet is not listed on npm ls

When installing this is the result:

> scrypt@6.0.3 preinstall C:\Users\jj\node_modules\scrypt
> node node-scrypt-preinstall.js

> scrypt@6.0.3 install C:\Users\jj\node_modules\scrypt
> node-gyp rebuild

C:\Users\jj\node_modules\scrypt>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files
\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Warning: Missing input files:
C:\Users\jj\node_modules\scrypt\build\..\scrypt\win\include\config.h
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Users\jj\node_modules\scrypt\build\copied_files.vcxproj(20,3): error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
C:\Users\jj\node_modules\scrypt\build\scrypt_wrapper.vcxproj(20,3): error MSB4019: The imported project "C:\Microsoft.C
pp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:262:23)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 6.1.7600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\jj\node_modules\scrypt
gyp ERR! node -v v8.12.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\jj\package.json'
npm WARN jj No description
npm WARN jj No repository field.
npm WARN jj No README data
npm WARN jj No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! scrypt@6.0.3 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the scrypt@6.0.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\jj\AppData\Roaming\npm-cache\_logs\2018-10-23T07_46_40_388Z-debug.log


texts: How does solidity contract handle physical/tangible objects for sales/purchasing?

texts:
As reference to solidity sample codes on the web, most of solidity sample codes relates to crowdfunding, voting, bidding focusing on the transferring, exchange or record of numeric value.

If I would like to handle mortgage (installment) or online shopping, one side holds value (money) and another side holds an physical/tangible asset.

How does the solidity represent the status and ownership transferring of physics or tangible asset ownership? (such as property, or the product).


texts: Getting revert error on transfer ether to wallet address

texts:
hi i m calculate the ether value with token price and quantity of tokens and than sending calculated ether value to seller account but i am getting revert error on remix at escrow.originatorAddress.transfer(amount); this line. i have sufficient balance also. Where am i making a mistake
below is my code.

function buyToken(uint256 _tradeId, address token, uint256 _quantity, uint256 _tokenPrice) payable external {

      uint256 decimals = 10 ** 9;
   //uint256 quantity = _quantity * (10 ** ERC20Interface(token).decimals();

   uint256 amount = _quantity.mul(_tokenPrice);
   amount = amount.div(decimals);
  // amount = amount.div(_quantity);

   Escrow storage escrow = escrows[_tradeId];
   require (_tradeId == escrow.tradeId, "Trade not found");
   require (msg.sender != escrow.originatorAddress, "You are the owner of this sell.");
   require(address(msg.sender).balance >= amount, "Insufficient balance");
  // require (escrow.receivedQty > 0, "in Sufficent");
   escrow.originatorAddress.transfer(amount);

   releaseToken(_tradeId, token, escrow, _quantity);

}


texts: Defining the structure of the contract created by other contract

texts:
I'm reading this post of this page "Solidity, create contract from contract".

And i have a question about this post, How i can define the estructure of the contract " address newContract = new Contract(name);" ?

For structure i mean the functions inside the created contract. I don't know if it is possible or not, but i'm looking for a answer about this question and i don't found nothing.


texts: value types(uint, bool, etc) as local variable is set to memory initially?

texts:
According to this answer, it says simpler variables like bool, uint, et cetera are not variable in length, and are therefore defaulted to memory, whereas this one mentions uint256 v; is default to storage. So I'm kinda confused whether the primitive types(int, uint, bool) used in the function is set to memory or storage as its default type. I know array is default to storage, ex: uint256[] x.

Anyone can clarify please?


texts: Besides Etherscan, Are There Other Places to Verify/Publish Contract Code?

texts: The title says it, but I also need at least 30 characters.


texts:
Ethereum maintains an Transaction Trie and a Receipts Trie and I'm trying to visualize how that data would be contained in a relational database.

I believe both Tries would have a primary key of transaction_hash, and I don't believe there is any other data duplicated between Tries nor any other unique identifier in either to use as a PK or FK between a transactions table and receipts table.

All that is to say, in a relational database would both Tries just live in a single table?


texts:
What's the meaning of the code, wherein the return values of a function are stored in variables which are initialized inside brackets, like the following:
(bool success, bytes memory data) = _contract.delegatecall(
        abi.encodeWithSignature("setVars(uint256)", _num)
    );

(bool success, ) = address(parentContract).call{value:msg.value}(abi.encodeWithSignature("initiatePayment(uint256)", index));

Thank you.


texts: My friend sent me a screenshot of a transaction hash, but when I search for it I find divergent data. What happened?

texts:
This is the transaction hash:

0x90e923ee01d9dfeb95ee176819eeec67d247fc6cb009c8cdc4d8ae1939e5ecc6

And this is the screenshot my friend sent me:

If you check the hash in Etherscan, some informations converge with the screenshot - block, number of confirmations and sender address - but other info are divergent - receiver address, date and amount sent. What could have happened?


texts:
How can I test (truffle test or development console) the following:
await nft.transferFrom(accounts[0], accounts[1], 1);
await nft.transferFrom(accounts[1], accounts[0],1);

The second line throws
ERC721: transfer caller is not owner nor approved

If I change to
await nft.transferFrom(accounts[1], accounts[0],1,{from: accounts[1]});

the following exception is thrown:
Ownable: caller is not the owner

How can I test a transfer from another account then accounts[0]?


texts: Do native Ethereum transactions use smart contracts?

texts: Does a smart contract come into play if I make a simple Ethereum transaction like sending someone an amount of ETH? Or do smart contracts only apply when I wish to implement additional functionality (Dapps) on top of the Ethereum blockchain? Trying to understand if smart contracts are a thing with “native” or “basic” Ethereum transactions.


texts: How do I find the average gas price of a given block? This doesn't appear to be an easily accessible thing in ethers.js or Web3.js, but hopefully I'm just missing something.


texts: How much gas did the attacker spend on TheDAO?

texts: Is there a way or somewhere I can see the gas used during the attack ?


texts: (NEW UPDATE: I need to run "testrpc") Signing a message using "ethereumjs-abi"? (Error: Invalid JSON RPC response: "")

texts:
I am trying to sign a message using following JavaScript code (from HERE)

function constructPaymentMessage(contractAddress, amount) {
  return ethereumjs.ABI.soliditySHA3(
    ["address", "uint256"],
    [contractAddress, amount],
  );
}

function signMessage(message, callback) {
  web3.personal.sign("0x" + message.toString("hex"), web3.eth.defaultAccount,
    callback);
}

// contractAddress is used to prevent cross-contract replay attacks.
// amount, in wei, specifies how much ether should be sent.
function signPayment(contractAddress, amount, callback) {
    var message = constructPaymentMessage(contractAddress, amount);
    signMessage(message, callback);
}

I have tried several approaches to run this code and get its output (signed payment), however, I could not run it successfully.

HERE is the screen shot of the .js file I created and HERE is the error message I receive when I run it by node sign.js . And when I remove callback from the code, I receive another error.

  What is the correct approach to run this code to get its output (i.e. signed message) ?

UPDATE: I modified the code as follows:

Web3 = require("web3")
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

var ethereumjs = require('ethereumjs-abi')

web3.eth.defaultAccount = '0xca35b7d915458ef540ade6068dfe2f44e8fa733c';

function constructPaymentMessage(contractAddress, amount) {
  return ethereumjs.soliditySHA3(
    ["address", "uint256"],
    [contractAddress, amount],
  );
}

function signMessage(message, callback) {
  //web3.eth.personal.sign("0x" + message.toString("hex"), web3.eth.defaultAccount, callback);

web3.eth.sign("0x" + message.toString("hex"),"0x135a7de83802408321b74c322f8558db1679ac20");

}

// contractAddress is used to prevent cross-contract replay attacks.
// amount, in wei, specifies how much ether should be sent.
function signPayment(contractAddress, amount, callback) {
    var message = constructPaymentMessage(contractAddress, amount);
    signMessage(message, callback);
}

signPayment('0xca35b7d915458ef540ade6068dfe2f44e8fa733c', 1, function(err, something) {});

I need to run testrpc before running this code.
Now the error message is as follows:

  "Error: Returned error: Error: cannot sign data; no private key"

And here is screen shot of the error message :

NOTE 1: I am using web3.js version 1.0.

NOTE 2: I run this JavaScript file in Ubuntu Terminal: node filename.js.

NOTE 3: Since I use web3.eth.personal.sign(dataToSign, address, password [, callback]) I do not need to use a password for this address ? > web3.eth.personal.sign("0x" + message.toString("hex"), web3.eth.defaultAccount);

NOTE 4: There is a similar problem here: similar problem but in remix.

NOTE 5: And alternatively, is there any other approach to sign such a message instead of using web3.js and ethereumjs-abi ?


texts: Running solidity-coverage via a buidler plugin on a project using openzeppelin/test-environment yields 0% coverage

texts:
I have a project where I would like to check test coverage for the Solidity Smart Contracts. I am using solidity-coverage via a buidler plugin and the test coverage is always 0%. The output from the tool appears to be perfectly fine, but the report yields no useful information since there are tests running for the Smart Contracts but the report returns the test coverage is 0%.
This project uses @openzeppelin/cli and not truffle.
Below are the config files and versions that I using (package.json):
"devDependencies": {
  "@nomiclabs/buidler": "^1.4.7",
  "@openzeppelin/test-environment": "^0.1.4",
  "chai": "^4.2.0",
  "ganache-cli": "^6.10.1",
  "mocha": "^8.1.3",
  "solidity-coverage": "^0.7.10"
}

The buidler.config.js file is as follows:
usePlugin('solidity-coverage')

module.exports = {
  solc: {
    version: "0.6.2"
  },
  networks: {
    coverage: {
      url: 'http://localhost:8555'
    }
  },
}

When I run the command:
npx buidler coverage --network coverage

I see the following (some content removed for brevity):
> server:            http://127.0.0.1:8555
> ganache-core:      v2.10.1
> solidity-coverage: v0.7.10

Network Info
============
> port:    8555
> network: coverage

Instrumenting for coverage...
=============================
Contract1.sol
Compiling...

Compiled 1 contract successfully
All contracts have already been compiled, skipping compilation.

...tests run here...

31 passing (10s)

------------------------|----------|----------|----------|----------|----------------|
File                    |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
------------------------|----------|----------|----------|----------|----------------|
 Contract1.sol          |        0 |        0 |        0 |        0 |                |
------------------------|----------|----------|----------|----------|----------------|
All files               |        0 |        0 |        0 |        0 |                |
------------------------|----------|----------|----------|----------|----------------|

As can be seen from the output above, everything compiles, test run (and pass) but the report concludes there is 0% test coverage (when there is).
Any help would be greatly appreciated!


texts: Transaction receipt contains all log entries, but only the last two are decoded by web3

texts:
I have a flow which yields 4 events.

When I obtain the transaction hash via web3.js, I can see that all 4 events are included in the receipt logs, but only the last 2 events are in the decoded logs (which means I have to decode the first 2 events myself):

{
    "receipt": {
        ...
        "logs": [
            {
                "logIndex": 0,
                ...
            },
            {
                "logIndex": 1,
                ...
            },
            {
                "logIndex": 2,
                ...
            },
            {
                "logIndex": 3,
                ...
            }
        ],
        ...
    },
    "logs": [
        {
            "logIndex": 2,
            ...
        },
        {
            "logIndex": 3,
            ...
        }
    ]
}

What is the reason for this?


texts: web3.js keeps throwing "error: insufficient funds for gas * price + value" on ropsten

texts:
I have been chacking around the site for possible solutions but i havent found any that would solve my (probably most basic) error. The account from which i'm sending has around 1 ether and i'm certain that the private key is correct as i had generated a new one and sent ether to it specificly to test is i had incorrect private key. I am using ropsten test network. And possible help would be much appreciated. this is the full source code.

I had written smartcontract, i can call the methods from it, but for the life of me i cannot send a transaction anywhere.

var Tx = require('ethereumjs-tx').Transaction;
const Web3 = require('web3')
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/da1b------341c38904ac78bb649502"))

const rawTransaction = {
        from : '0x76a9CEA17DbA8a371944d00a2E9A17AA3669B392',
        to: '0x17eB191cDc2b3f06c25914c2da041CEeb41e9B16',
        value: web3.utils.toWei("0.0001", "ether"),
        gasLimit: 200000,
        gasPrice: web3.utils.toWei("0.000002", "ether"),
        chainid : 3,
        network_id: 3
};

web3.eth.accounts.signTransaction(rawTransaction,'EA------------5A36B3677F74AC1')
  .then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
  .then(receipt => console.log("Transaction receipt: ", receipt))
  .catch(err => console.error(err));

The error being thrown :

Error: Returned error: insufficient funds for gas * price + value
    at Object.ErrorResponse (/home/ubuntu/ethereum_website/node_modules/web3-core-helpers/src/errors.js:29:16)
    at /home/ubuntu/ethereum_website/node_modules/web3-core-requestmanager/src/index.js:140:36
    at XMLHttpRequest.request.onreadystatechange (/home/ubuntu/ethereum_website/node_modules/web3-providers-http/src/index.js:96:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/ubuntu/ethereum_website/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/home/ubuntu/ethereum_website/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (/home/ubuntu/ethereum_website/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (/home/ubuntu/ethereum_website/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)


texts: coinbase or any other centralized exchanges diametrically opposed to decentralization goals

texts:
coinbase or any other centralized exchanges are diametrically opposed to decentralization goals.

What are some decentralized platforms available one can use to avoid using centralized exchanges?

Nathan Aw


texts: How to call a function of a contract with unknown source code?

texts:
Let's say I want to interact with a contract but I don't know the ABI of this contract. Via the UI I know which functions are called (by inspecting the transaction).

How do I call these functions in a solidity?


texts: What's the transaction-throughput on Ethereum (how fast the nodes can replicate transactions, not transactions per second)

texts: Ethereum does roughly 10-30 transactions per second (TPS), and Proof-of-Work is a bottleneck there, so Casper (proof-of-stake) should increase the TPS. What is the transaction throughput on Ethereum, how fast can the nodes disperse transactions to the entire network (ignoring how fast blocks can be built. )


texts: How to provide gas value when we can't calculate it, when using arrays?

texts:
Recently, I am trying arrays(search) in browser-solidity and I found that the number of items in it causes changes in the gas consumption.

For making a call we need to specify the gas amount but it depends on the items count in the array.

Is there a workaround to handle these kinds of operations in Ethereum?


texts:
From what I understand, a wallet is a smart contract and in order to create a wallet, you need to deploy the contract to the blockchain as stated here, which is different from creating accounts.
When I create a new wallet with the web3.js library or add an account to an existing wallet, am I creating a wallet or just a private/public key pair? Is it just a private/public key pair since I'm not deploying anything even though it's says "wallet"?
web3.eth.accounts.wallet.add('0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
> {
    index: 0,
    address: '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23',
    privateKey: '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318',
    signTransaction: function(tx){...},
    sign: function(data){...},
    encrypt: function(password){...}
}

Adding to the confusion is that web3.js also has an option to create just an account, and not a wallet.
web3.eth.accounts.create([entropy]);


texts: Chicken-Egg Problem when I deploy a Crowdsale with Standard Token

texts:
I just try to implement a standard token with a basic crowdsale from open zeppelin.

I have everything up and running but the transaction always reverts and I tracked it down to this line:

token.transfer(_beneficiary, _tokenAmount);

So within the token contract I get msg.sender to be the Crowdsale contract. However, since the crowdsale contract get's deployed after the token contract, all the tokens are at the address that created the token contract and my guess is that this is causing the revert - because the crowdsale does not have any tokens.

Hence, I have 3 questions:

is this correct?
does this simply mean that I need to transfer all tokens to the crowdsale contract?
is there a way to automate this?


texts: Smart Contract - Update implementation using a Relay with delegateCall

texts:
I know that smart contracts are supposed to be immutable and that's the whole point, but to expect someone to implement a logic that never changes (no upgrade or no bugs) from day 1 is also unrealistic.
Therefore, I've been reading about several methods of working around this immutable state. A popular method seems to be using delegateCall with a Relay contract, but I'm struggling with how to actually use this method as I couldn't find any example.
Would someone be kind enough to look at that simple example I created, and tell me what I'm doing incorrectly?
https://gist.github.com/fabdarice/d513d620d9355312d085c7a68e6c6118
Relay.sol

contract Relay {
  address public currentVersion;
  address public owner;
  mapping (address => uint) user_amounts;

  modifier onlyOwner() {
    if (msg.sender != owner) {
        throw;
    }
    _;
  }

  function Relay(address initAddr) {
    currentVersion = initAddr;
    owner = msg.sender; // this owner may be another contract with multisig, not a single contract owner
  }

  function changeContract(address newVersion) public
  onlyOwner()
  {
    currentVersion = newVersion;
  }

  function() {
    if(!currentVersion.delegatecall(msg.data)) throw;
  }
}

Donation.sol :

contract Donation {
  mapping (address => uint) user_amounts;

  /* DOES THIS METHODS MODIFY user_amounts of the Relay contract ??? */
  function sendDonation(uint n) {
    user_amounts[msg.sender] = user_amounts[msg.sender] + n
  }
}

DonationNew.sol :

contract DonationNew {
  mapping (address => uint) user_amounts;

  function sendDonation(uint n) {
    user_amounts[msg.sender] = user_amounts[msg.sender] + n
  }

  function cancelDonation() {
    user_amounts[msg.sender] = 0
  }
}

app.js :

// First, deploying Relay, then deploying Donation and retrieve Donation contract address in 'donation_contract_address'

// Then, linking Relay to my first version of my contract Donation
Relay.deployed().then(function(contractInstance) {
   contractInstance.changeContract(donation_contract_address);
})

// Then, I want to call sendDonation from the Donation contract
// !!!!! I DON'T KNOW WHAT IS THE CORRECT WAY TO CALL THIS !!!!!!
Relay.deployed().then(function(contractInstance) {
   contractInstance.sendDonation(5) ;
})
// OR
Relay.deployed().then(function(contractInstance) {
   contractInstance.currentVersion.delegateCall(sendDonation(5)) ;
})

// Now I want to update the Donation contract to add the cancelDonation function
// First I deploy the new contract DonationNew and retrieve it's address in 'donation_new_contract_address'
Relay.deployed().then(function(contractInstance) {
   contractInstance.changeContract(donation_new_contract_address);
})

// are the state variables still available from the old contract to the new one?

// Then if I want to call the new function :
Relay.deployed().then(function(contractInstance) {
   contractInstance.cancelDonation() ;
})

P.S.: I know that this method above allow us to create an "upgradable contract" in the case we need to update our logic (functions etc..), however it doesn't allow us to modify/add our state variables structure. Is there a workaround this as well?

Thanks a lot, happy to be part of this community !


texts: Why does this work with Solidity 0.4.21 but not 0.4.22?

texts:
I have this simple set of contracts.

pragma solidity ^0.4.21;

contract FirstContract {

  bool public isTrue = true;

  function sayHello() public pure returns(bool) {
      return true;
  }

}

contract ServiceContract {

  FirstContract firstContract;

  function ServiceContract (address _firstContract) public {
    firstContract = FirstContract(_firstContract);
  }

  function confirmFirstContract() public view returns(bool) {
      bool x = firstContract.isTrue();
      return x;
  }

  function sayHi() public view returns(bool) {
      bool y = firstContract.sayHello();
      return y;
  }

}

When this is compiled and deployed in the correct sequence using 0.4.21, confirmFirstContract() and sayHi() return true as expected.

When the compiler is changed to 0.4.22 the same function returns an "invalid opcode".

Why would that be?

I found this blog that suggests some hints. https://medium.com/@chris_77367/explaining-unexpected-reverts-starting-with-solidity-0-4-22-3ada6e82308c

Thanks!


texts: Is it possible to get networkid inside the contract

texts:
I started my private network with id = 15452:

geth --networkid 15452

Is it possible to get the number inside solidity smart contract?


texts: Is it possible to send a transaction to be executed on a particular block?

texts:
Is it possible to send a transaction to the Ethereum network to be executed earliest from a certain block number?

So i.e.

Now it's block 111 and I want to have my transaction in block 115 (If it's accepted with that gas price).

Or that the transaction will be executed in block 115 and if the gas price is to low do block 116 with gas price times 2?

And do I need to run my own full node for this?

EDIT:

The suggested duplicate only anwsers part of the question.

Wouldn't it be so that if you know the pending transactions you can sum the gas limits and then know that the top X transactions will be included in the next block. If you then set you gas limit to be higher then one of those that it will be included?

Although here I can see pending transaction, this includes the ones in the current block. Is it possible to only see the ones which haven't been included yet and do I need to run a full/mining node for this


texts: What is the Identity function and what are its uses?

texts: The contract at address 0x04 is the identity function.  What is it and what are use cases for it?


texts: what's the "Contract Creation Code" in Etherscan Verfied Contract?

texts: what's the difference between "Contract Creation Code" in Etherscan Verfied Contract and the bytecode compiled by Solc?


texts:
What is the best way to show truffles migration history or at least the last successful step. Something similar what I see when I do truffle migrate:

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x4724cf1e4bd9ce7323f837199d7bb0c71e36e7a0ebb1758f03d42814a6df18a2

  Migrations: 0xcfde951064e454bc5b1aeecc9d47745046b953a6

Saving successful migration to network...
  ... 0x46a6e8551dd37bf5c3354ce75da29b4cfd8d2cdeb14491bf25d7ada82630d4b4
Saving artifacts...

Running migration: 2_deploy_mycontracts.js

  Deploying MyToken...
  ... 0xc6cfb8617f3a8a75b9a1b6eb95d62066e1e4c4b2ba45f0be616ade7ed3e67f32
  MyToken: 0x2678b1f2c7d9c13279802bec54ee4284f7b736cc

  Deploying AnotherContract...
  ... 0xe54a6edc72d606da2d80f28022bb35cc6a393f4014549c5d1f7c2f614fc88ea8
  AnotherContract: 0x9f2a1cc604b86e75b88dd302be4bb0d66dcdd13e


texts: What is the cheapest hash function available in solidity?

texts:
AFAIK there are 3 hash functions to choose from in solidity (sha3, sha256, and ripemd). sha3 is native while the others use precompiled contracts.

Which one of these is cheapest (in terms of gas)?


texts:
Tried sending some Eth from MetaMask to Huobi. It left and says it was a success but the eth not showing up. Checked the address 5 times and all good so have I missed something simple here? Been over 3hrs!!

Cheers


texts: Contract is not deploying, not working as per plan

texts:
My plan is to develop a sample agreement contract between customer and car provider. workflow is as below...

Customer will register to carRentalServiceProvider contract.
after registration, only registered customer can rent a car using RentingCar contract. (not working both registered and non registered customer is renting car) actually i am facing a problem to deploy this contract. I guess problem is
with below function with isActive() function
function rentingCarFromCarPool (address _customerAddress){

if(isActive() && NumberOfAvailableCarInPool > 0){
    carRentingFromPool[_customerAddress] = CarRentingStatus({
                                                carRentActive: true,
                                                lastUpdate: now,
                                                carModel: "ToyotaCorolla X 2015"
                                                });
    NumberOfAvailableCarInPool--;
} else {
    throw;
}

}

IsActive function:

function isActive()  returns (bool) {
    if(rentCar[msg.sender].active == true){
    return true;
    } else {
    return false;
    }
}

car service provider can set rent and registration fee for customer with CarRentalServiceProvider contract.>>>> (works fine)
customer can pay the bill using CarRentalServiceCustomer contract. Problem is after paying the rent and registration fee both should be zero. But it is not becoming 0 after showing successful payment. But from my contract account showing the same amount of money.

here is my complete code
https://ethereum.github.io/browser-solidity/#version=soljson-v0.4.9+commit.364da425.js

Kindly help me to develop this project as per plan and error free. Thanks a lot in advance.

Note: after solving this problem i will add some other functionalities.


texts: Are simultanous transactions possible (basic but potentially very dangerous security concern...most likely impossible...)?

texts:
Long story short I am curious how a contract stores variables in memory, so is it possible to spam say 100 transactions at once and the values to be changed afterwards...I am sure I am giving bad description so here is the code to better illustrate my point:

contract thiscontract
{

uint256 balancer = 3000;

function something() public payable
{
if(balancer > 0)
{
balancer -= 1000;
msg.sender.transfer(1000);
//event Transfer(msg.sender, balancer);
}

}
}

Basically: The function should send no more than 3000 wei, each time sending 1000 wei - if 4th msg.sender calls it after the first 3 calls it will not send anything since the value is 0 and the "if" statement prevents it.

But what will happen if 100 or more transactions call the "if" simultaneously? Does the contract 'freeze' and processes every single check one after another? Or does the contract allow some sort of parallelism like a web server and many people can call it and do this exact operation in parallel?

Because if the case is as described in "parallel" what happens is:

// it takes 0.05 seconds or so to check "if" statement...
// however 10000000 calls are made to cause denial of service/parallel check:

if (balancer > 0)

// let's say 5000 pass the check and continue to sending...
If someone calls it an hour later it will surely fail but still way many succeed.

I am sure this isn't possible, the only thing I know is "if" check or "Require" takes some computational time and you can read a contract without any blockchain interaction, however this is so basic that it can't be possible. Maybe someone should send 200 transactions via loop statement in web3 js/python on ropsten and see if they all obey the if rule above or more succeed or better yet pass them to aws instances who execute transactions in parallel.

Final note for now: From purely programming point of view this may be impossible since the transaction will be sent to bytecode assembly LIFO which will obey the "last in, first out" rule causing indeed freeze/slowdown and impossibility of parallel execution (so no: solidity seems far simpler than java/c# or webservers with asynchronous calls and so on). I am not 100% sure and maybe the many nodes can make it possible but I admit I have limited understanding of how exactly the transaction flow occurs between Ethereum nodes.


texts: I accidentally sent the same transaction twice because it was pending

texts:
I seem to have gotten myself in a bit of a pickle. I sent some ether to another one of my wallets. The gas price was too low and it was pending for hours.

I read online that if you send the same transaction (to the same wallet and everything) with a higher gas price, the transaction with the higher gas price will override the previous one and you are good to go. I did this and the transaction is stuck on pending.

When I take a look at the Etherscan page, usually it just shows the first transaction. But, sometimes when I refresh, it occasionally shows both transactions as pending. I'm a little spooked and don't know what to do.

Any information/advice/guidance would be immensely appreciated. Thank you.

Edit: Every once in a while, I a message from my wallet pops up saying "java socket timeout exception".


texts:
hihi this is my code

    pragma solidity ^0.4.18;
contract ValueIO {

 uint myidaaaa;

 uint price = 100000000 wei;

 function Input(uint feion) public payable {
     require(msg.value > price);

     myidaaaa = feion;
 }

 function Output() public constant returns (uint,bool) {
     return (myidaaaa,true);
 }
}

i wish user input and change myidaaaa data and pay the 1eth to my contract

but i don't know how can do this

please help me my teach

thank you so much

(the photo is error note)


texts: Why does a Solidity throw consume all gas?

texts: When you throw an exception, all gas is consumed. What is the rationale for this design decision?


texts: Error-Creation of node in Private Ethereum Chain

texts:
I am trying to create node in Private Ethereum Chain.

l have used this command for creation of Ethereum node:-

  geth --datadir="~/data/node1"  init="/Documents/PRIVATENET/genesis.json" –nodiscover --ipcdisable --networkid 100 --port 30301 --rpcport 8101 console

I have specified networkid and custom genesis file for creation in the command.But the output shows that,it directs towards the default genesis file and default network id '1'.

(Refer these lines

     I1209 13:48:24.553115 eth/backend.go:189] Protocol Versions: [63 62], Network Id: 1

     I1209 13:48:25.092896 eth/backend.go:207] WARNING: Wrote default ethereum genesis block)

This is the output :-

 I1209 13:48:24.479719 cmd/utils/flags.go:624] WARNING: No etherbase set and no accounts found as default
 I1209 13:48:24.479972 ethdb/database.go:83] Allotted 128MB cache and 1024 file handles to /home/toshiba/data/node1/geth/chaindata
 I1209 13:48:24.531343 ethdb/database.go:176] closed db:/home/toshiba/data/node1/geth/chaindata
 I1209 13:48:24.532522 node/node.go:176] instance: Geth/v1.5.4-stable-b70acf3c/linux/go1.7.3
 I1209 13:48:24.532569 ethdb/database.go:83] Allotted 128MB cache and 1024 file handles to /home/toshiba/data/node1/geth/chaindata
 I1209 13:48:24.553115 eth/backend.go:189] Protocol Versions: [63 62], Network Id: 1
 I1209 13:48:25.092896 eth/backend.go:207] WARNING: Wrote default ethereum genesis block
 I1209 13:48:25.093089 eth/backend.go:217] Chain config: {ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSupport: true EIP150: 2463000 EIP155: 2675000 EIP158: 2675000}
 I1209 13:48:25.093502 core/blockchain.go:219] Last header: #0 [d4e56740…] TD=17179869184
 I1209 13:48:25.093538 core/blockchain.go:220] Last block: #0 [d4e56740…] TD=17179869184
 I1209 13:48:25.093573 core/blockchain.go:221] Fast block: #0 [d4e56740…] TD=17179869184
 I1209 13:48:25.094619 p2p/server.go:342] Starting Server
 I1209 13:48:27.245136 p2p/discover/udp.go:227] Listening, enode://65436e03004806bd4f4fc9a131c022c32a6cd2dcdd2773a1a13e03475295fbec6913070b843e756f06d1cf2847808f02ae712aefe93a439ddaaae7bdbcaba88e@[::]:30303
 I1209 13:48:27.246387 p2p/server.go:610] Listening on [::]:30303
 I1209 13:48:27.255301 node/node.go:341] IPC endpoint opened: /home/toshiba/data/node1/geth.ipc


texts: How to connect to Etherscan Ropsten API using python

texts:
I want to connect to the etherscan Ropsten test-net with python:

URL = 'https://api-ropsten.etherscan.io/api?module=contract&action=getsourcecode&address=0x1c7f98370206b4d44bfbb011c65bc582fcdae4fe&apikey='+ API_key
s = requests.Session()
response = s.get(URL)

The response code is always Forbidden 403.
I tested with curl the same url and it works.
I tried to use py-etherscan-api, but there are no examples how to connect to Ropsten.


texts: Unable to write data into blockchain - Ganache

texts:
I've this contract and web3js html GUI that's interacting with it. The contract is deployed in ganache at localhost 8545 and unable to write data into blockchain.

SimpleStorage.sol -

pragma solidity ^0.4.17;

contract SimpleStorage {   uint myVariable;   string myName;
     //mapping (myName => address) name;

  function set(uint x) public {
    myVariable = x;   }

  function get() constant public returns (uint) {
    return myVariable;   }
     function setName(string name) constant public  {
    myName = name;   }
     function getName() constant public returns (string) {
    return myName;   }    }

SimpleStorage.html -

<!doctype>


texts: Sending Ethereum to the contract owner on purchase

texts:
I have a smart contract that allows one to purchase a set number of NFTs for 0.2 ether each.
I have set the owner of the smart contract to the one who deploys it and whenever someone purchases an item via my dapp, it should mint the token for them and then transfer the ethereum passed into the function to the owner.
I also want to be able to change the _cap, only if I am the owner, as long as its below 500, so I can release the NFTs in waves.
address payable private _owner;
uint256 private _cap = 10;

constructor(string memory myBase) ERC721("Nftree", "Tree") {
    _setBaseURI(myBase);
    _owner = msg.sender;
}

function buyItem()
    public
    payable
    returns (uint256)
{
    require(totalSupply() < _cap);
    require(msg.value == 0.2 ether, "Need to send exactly 0.2 ether");
    _tokenIds.increment();
    uint256 newItemId = _tokenIds.current();
    _safeMint(msg.sender, newItemId);
    _owner.transfer(msg.value);
    return newItemId;
}

function setCap(uint256 newCap) public returns (uint256 changedCap){
    require(_owner==msg.sender);
    require(newCap<=500);
    _cap = newCap;
    return _cap;
}

I am wondering if it is dangerous to send msg.value directly to the owner via the transfer function, and if there are any security flaws anyone can see.
Additionally I am thinking of calling _owner.transfer before _safeMint, so that my dapp is updated with the number of tokens minted on cue, instead of updating slightly before the transaction has completed.Would this cause any issues?
Thank you


texts:
Noob here. I have made two transactions from EtherLi. It looks that they are "stuck" in between. I had enough of gas and the transactions are shown in "internal transactions" but never received at the receivers end.

What could be the problem?

Regards,

Dennis


texts: storage gas refund, is gas only refunded when storage is completely deleted? What if a key / value in a mapping is deleted?

texts:
I have a which tracks ids for some structs for different users.

mapping (address => uint[]) usersStuff

This  mapping for each user can grow or shrink.

If it happens to shrink to 0 for a single user (i.e. with delete usersStuff[msg.sender] ) but the actual variable hasn't been deleted because usersStuff has data for other users, is there a gas refund?


texts:
I have just install Ethereum today so im a complete newbee to Ethereum and doing some research. I have installed the Ethereum Wallet app and synchronized the testnet.

However, to deploy my first contract in testnet, it requires some Ether, so can someone guide how to get that?
In Ethereum-Wallet, there is an option for CPU mining in the Develop menu. I try to use it to mine ethers (and win ethers) bt dosent work. It dont swich on.
Someone knows how can i resolve it.


texts: ILendingPool.getReserveData function gives YulException: Stack too deep when compiling inline assembly:

texts:
I am trying to call the getReserveData function of a library ILendingPool interface:
interface ILendingPool {
  function addressesProvider () external view returns ( address );
  function deposit ( address _reserve, uint256 _amount, uint16 _referralCode ) external payable;
  function redeemUnderlying ( address _reserve, address _user, uint256 _amount ) external;
  function borrow ( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external;
  function repay ( address _reserve, uint256 _amount, address _onBehalfOf ) external payable;
  function swapBorrowRateMode ( address _reserve ) external;
  function rebalanceFixedBorrowRate ( address _reserve, address _user ) external;
  function setUserUseReserveAsCollateral ( address _reserve, bool _useAsCollateral ) external;
  function liquidationCall ( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable;
  function flashLoan ( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external;
  function getReserveConfigurationData ( address _reserve ) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive );
  function getReserveData ( address _reserve ) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp );
  function getUserAccountData ( address _user ) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor );
  function getUserReserveData ( address _reserve, address _user ) external view returns ( uint256 currentATokenBalance, uint256 currentUnderlyingBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled );
  function getReserves () external view;
}

Unfortunately the getReserveData function returns a tuple that has 13 fields.
I need only one of the fields and you can see me call it below:
   function getAvailableLiquidity(ILendingPool _lendingPool) internal view returns (uint256){
    uint256 _availableLiquidity;
    (,_availableLiquidity,,,,,,,,,,,) = _lendingPool.getReserveData(RAW_ETH_ASSET);// in ether
    return _availableLiquidity;
  }

..Solidity keeps complaining:
YulException: Stack too deep when compiling inline assembly: Variable dataEnd is 1 slot(s) too deep inside the stack.
This is the interface definition so of course I can't do anything about it.
Please what trick can I use to wangle the available liquidity out of the getReserveData function?


texts:
Some points I want to understand:

Why it exists given we can authorize the transaction with password.
What does generate a new token means?
Can I have multiple tokens?
How to revoke a token?
Is there further plan of it? It seems to be exclusive Parity.

The resources about the trusted token is quite limited, thanks in advanced:)


texts: Explicit type conversion not allowed from "string memory" to "uint256"

texts:
I'm using an oracle to get results from a custom api. The result is in string by default. I want to convert it to uint256, so that I can perform basic arithmetic functions.
Here's my code:
function __callback(bytes32 myid, string result) public{
       if (msg.sender != provable_cbAddress()) revert();
       uint256 points = uint(result); //Error here
       balanceOf[pointsAllowance[myid]] = points;
       remSupply = remSupply - points;
       emit LogPriceUpdated(points);
}


texts: What would be the probability for miners having very low gas price to deploy a transaction?

texts:
Here is guide for the Gas price in ETH unit Calculation:

  If 1 ETH is $10, 1 gas will cost 0.00000002 * 10 dollars.

  If ETH is $10, 21000 gas will cost 0.00000002 * 10 * 21000 = 0.0042
  dollars, which is 0.42 cents.

Based on the calculation shown, with the current ether price (250$) the result will be 0,105 dollars instead of 0.42 cents, which is very expensive in my opinion.

[Q] Is there any miners having gas price less than the default gas price(0.02 microether)? If yes, what would be the probability for miners having very low gas price to deploy a transaction?


texts:
I am currently trying to push my unit testing far in order to achieve a complete coverage over my code.
I am using Open Zepplin's Ownable.sol contract and I cannot find in the documentation something about mocking the user sending the request (understand msg.sender) using remix_test.sol.

Do any of you ever heard about or have done such a thing ?


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

texts:
I'm testing a contract on testnet using Mist.

When I deploy it, it says "No data is deployed on the contract address!".

And then it doesn't appear on the contracts section.

What does it mean?


texts: How many active nodes does ethereum currently have?

texts: Here shows that ethereum has nearly 33k nodes, though I'm curious how many active nodes there are?


texts: How to access a smart contract function protected by access rights using Web3?

texts:
I have a smart contract address for security tokens, and certain functions of it are protected by access rights, for which I have an address to access those functions, however I am not able to figure out, how to call that function by specifying the rights.

from web3 import HTTPProvider, Web3, exceptions

w3 = Web3(HTTPProvider('https://ropsten.infura.io/RPw9nHRS7Ue47RaKVvHM'))
contract_address = '0x635209612bf0e830ac348ef30357ee4f0e5bf560'
provider_abi =  [{"anonymous":False,"inputs":[{"indexed":False,"name":"addr","type":"address"},{"indexed":False,"name":"propertyKey","type":"bytes32"},{"indexed":False,"name":"propertyValue","type":"bytes32"}],"name":"PropertySet","type":"event"},{"constant":False,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"},{"name":"_propertyValue","type":"bytes32"}],"name":"setProperty","outputs":[{"name":"","type":"bool"}],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_addr","type":"address"},{"name":"_propertyKey","type":"bytes32"}],"name":"getProperty","outputs":[{"name":"","type":"bytes32"}],"payable":False,"stateMutability":"view","type":"function"}]

instance = w3.eth.contract(
    address=Web3.toChecksumAddress(contract_address),
    abi = provider_abi
)
user_address = "0x25BEADE120E501D7b984498D196eFe4AbE6a11F6"
country_key = "country"
country_byte_32 = Web3.toHex(Web3.toBytes(text=country_key))
print(country_byte_32) # Prints 0x636f756e747279
country_val = "IN"
country_val_byte_32 = Web3.toHex(Web3.toBytes(text=country_val))
print(country_val_byte_32) # Prints 0x494e
try:
    result = instance.call().setProperty(user_address,country_byte_32,country_val_byte_32)
    print(result) # Prints False
except exceptions.MismatchedABI as ve :
    print(ve)
    import traceback
    print(traceback.format_exc())

Can someone tell me, how do I provide the access right address?


texts: Having to set reset flag with truffle migrate

texts:
I am having a weird issue where my migrations are not being deployed when I run truffle migrate --network development.  But when I run truffle migrate --network development --reset, the contracts are being deployed correctly.  Does anybody know what the cause to this could be?

I am on truffle version 4.0.1 and solidity version 0.4.18.

This is an example of the console messages I am seeing.  In this picture I just added the staging network to my truffle.js before running these migrate commands. (The authentication error is expected)


texts: How to concatenate an address to a string in solidity

texts:
I am trying to find the correct way to concatenate an Ethereum address to a string in Solidity v0.6.7
I tried the following but it did not seem to work :
    function append(string a, address b) internal pure returns (string) {

    return string(abi.encodePacked(a, b));

}

Any point in the correct direction would be appreciated


texts: Accessing the network through light node

texts: I've been trying, unsuccessfully, to make a web3.py app that needs to catch events, with the use of filters. After hours and hours of testing it appeared the problem was that Infura, which is the provider I used, doesnt support filters. Therefore I need to set up a node but do not really have the space available to maintain a full node. Can a light node handle filters properly? I do not need old data, i just need to catch events from now on. Thanks


texts: Noob: Do I need to create my own private chain or use Ethereum's chain?

texts:
Hi I'm an ethereum noob and I have a few questions about integrating ethereum into my app.

Imagine I want to create a transaction on the blockchain every time a user opens the MySecret app. I want to log this information. Eventually I will reward the users with "MySecret" tokens for letting me log this information. My questions are:

Can I just use the standard Ethereum blockchain? Or do I need to create my own private chain?
When I create this transaction, do I need special nodes to verify this transaction was indeed from a real device (and generated by a hacker)? Or does Ethereum handle this already? If I need special nodes to verify the transaction, won't I need several devices that have a lot of computing power?


texts: Why is ethereum not using threshold signatures like dfinity for randomness? What's the drawback?

texts:
So ethereum goes for RANDAO. The disadvantage with randao is that the last validator in the commit-reveal scheme is able to hold his contributed value back and thereby influence the random outcome. Ethereum is trying to overcome this by using verifiable delay functions.

Why all that hassle? Why not just go for threshold signatures like Dfinity? What's the drawback?

Some link to a statement from Vitalik Buterin on this would be higly appreciated. Otherwise if you can explain it it's also fine


texts: hardware and software requirements to launch an ERC20 Token

texts:
Pardon me I'm new in this.

I'm trying to launch my ERC20 token. So What are the hardware and software requirements for an ideal transfers handling server system?


texts: Range error : Maximum call stack size exceeded

texts:
I am trying to deploy my contract written in solidity on a test network (Rinkeyby),But when i run the command "node deploy.js" i get the mentioned error in the title of this article which is "RangeError:Maximum call stack size exceeded".I will be appreciated if someone helps with this issue  :)
------------------------------------------------- deploy.js ------------------------------------------
const HDWalletProvider =  require("@truffle/hdwallet-provider");

const Web3 = require("web3");

const { interface, bytecode } = require("./compile");

const provider = new HDWalletProvider(
    "<MNEMONIC>",
    "https://rinkeby.infura.io/v3/<INFURA_ID>"
);

const web3 = new Web3(provider);

const deploy = async () => {
    const accounts = await web3.eth.getAccounts();

    console.log("Attempting to deploy from account", accounts[0]);

    const result = await new web3.eth.Contract(JSON.parse(interface))
      .deploy({ data: bytecode, arguments: ["Hi there Sina!"] })
      .send({ gas: "1000000", from: accounts[0] })

    console.log("Contract deployed to", result.options.address);
};

deploy()

------------------------------------------------- compile.js ------------------------------------------
const path = require("path");

const fs = require("fs");

const solc = require("solc");

const inboxPath = path.resolve(__dirname, "contracts", "inbox.sol");

const source = fs.readFileSync(inboxPath, "utf8");

module.exports = solc.compile(source, 1).contracts["Inbox"];

------------------------------------------------- inbox.sol ------------------------------------------
pragma solidity ^0.4.17;

contract inbox {

    string public message;

    function Inbox(string initialMessage) public {
        message = initialMessage;
    }

    function setMessage(string newMessage) public {
        message = newMessage;
    }
}


texts: Returning values from Solidity function that does not define a return?

texts:
I'm a bit confused by the code at this smart contract, which is part of the Aragon project code:

function delegatedFwd(
    address _dst,
    bytes _calldata,
    uint256 _minReturnSize) internal {

    require(isContract(_dst));
    uint256 size;
    uint256 result;
    uint256 fwd_gas_limit = FWD_GAS_LIMIT;
    assembly {
        result := delegatecall(sub(gas, fwd_gas_limit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
        size := returndatasize
    }

    require(size >= _minReturnSize);

    assembly {
        let ptr := mload(0x40)
        returndatacopy(ptr, 0, size)

        // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
        // if the call returned error data, forward it
        switch result case 0 { revert(ptr, size) }
        default { return(ptr, size) }
    }
}

The function declaration does not declare a return value, yet the function itself appears in the last line to return data.

If a caller called this function, wouldn't the caller have to ignore the return value or the code should fail to compile?

What am I missing? Would the caller have to access the return values with assembly and if that's the case isn't this violating the spirit of the function definition? It seems like bad programming practice to me.


texts: What is the best way of storing document hashes on Ethereum?

texts:
I have a website in which users can add some input and be given back a 'download' button that will generate a report in PDF format after some calculations are run in the backend of the website on the provided input.
I want those reports to be authenticated, i.e. I want to store the hash of those PDFs on a blockchain (Ethereum ideally but open to any).
When a third party is sent a report from someone, he can go on the website and check that the document he was sent is the same original one generated from the website (a sort of box to compare hashes). Something quite similar to what universities do when they want their certificates to be blockchain validated, but everything would happen on the website.
So the short question is - what is the easiest solution to do this? I would like to deploy it myself rather than using 3rd party providers.
Do I need a whole smart contract or can I use simple transactions and store the PDF hash within the transaction? Sort of like using the 'add data' field in MyEtherWallet when sending transactions.. can I then retrieve the added dat field through an API maybe?
I am not really experienced to blockchain so an easy explanation would help.
Thanks a lot in advance
L.


texts:
ethereumjs-abi is great for easily ABI encoding and decoding in javascript. Is there an equivalently simple package for Golang?

Geth's accounts/abipackage does this, but there's a lot of setup and it's hard to change the types, because you have to specify a full ABI-JSON. I imagine this is a common need and solved. Any suggestions?

Example of ethereumjs-abi:

let encoded = abi.rawEncode(["bytes32", "bytes"], [val1, val2])


texts: Organize received customer deposits payments

texts:
What's the best way to organize received payments?
Is the only possibility to assign a new payments address to each customer or is it possible to identify customers reliably on data payload of the transaction or any other method? (I don't want to use sender addresses for identification).
How would you organize a wallet for the payments?  Is there a good secure HD wallet implementation for node.js or should I better use a non deterministic wallet? Is it possible to implement a "wallet" as a smart contract, so I don't need to store keys on server?


texts: Byzantium related homework required for pool operators and developers

texts: Is there a summary of what code and/or configuration changes need to be implemented by mining pools and associated code to properly support the upcoming hard-fork? Do packages like ethash need to be updated?


texts:
I am working on a smart contract that take a data from each node to be stored in the blockchain

What is the best data structure to pass it as a method parameter?. I have done a string but it doesn't work if I pass a long string which contains some special character.

For example, I have the following code:

function push (String str)
{
.....
}

// invoking the method
push("temp-temp,1234*cent,skgvxcj12497sdf7485t70gsbvw4987ety");

Thanks


texts: web3js - "new BigNumber() not a base 16 number: " error after making function that compares strings

texts:
I have a contract that I've been able to successfully make web3 calls on. However, after adding this function to a new version of the contract:

function removeDevice(address owner, string dev_addr)public{
    delete registeredTo[dev_addr];
    for(uint i = 0; i < ownership[owner].length;i++){
        if(keccak256(ownership[owner][i].device_address) == keccak256(dev_addr)){
            ownership[owner][i] = ownership[owner][ownership[owner].length-1];
            delete postedItems[owner][postedItems[owner].length-1];
            postedItems[owner].length--;
            break;
        }
    }
}

Every function that sends data to the contract generates a "new BigNumber() not a base 16 number: " error, and fails.

ownership[owner][i].device_address and dev_addr are both strings, and I assume the error is being generated by the comparison of the two, since other functions in my contract do similar operations without issue. I have also double-checked to make sure that I'm using the correct contract address and ABI, and I am using version 0.4.21 of Solidity, which appears to be the most up-to-date version, so I am certain that the issue stems from this block of code; I just cannot figure out how to go about fixing it.


texts: Error: Invalid number of arguments to Solidity function | when trying to pass in parameter from App.js to Solidity

texts:
I am trying to call a function in my Solidity file (Coder.sol), while passing through a parameter from my App.js file. My function in my App.js file looks like this:

handleStartRequirement: function(reqId, payment_amount) {

  var coderInstance;
  App.web3.eth.getAccounts(function(error, accounts){
    if (error) {
      console.log(error);
    }
    // Set client address equal to a testrpc account
    let client = accounts[0];
    App.contracts.Coder.deployed().then(function(instance) {
      coderInstance = instance;
      const thing =  coderInstance.startRequirement.call().then(res => {
        return coderInstance.startRequirement(payment_amount, {from: client, value: web3.toWei(1, "ether")});
      }).catch(err => console.error(err));
    }).then(function(success) {
      App.markReadytoStart(reqId);
    }).catch(function(err) {
      console.error(err.message);
    });
  },

The startRequirement function in my Solidity file looks like this:

function startRequirement(address _client, uint256 _contract_amount) returns (bool) {
      client = _client;
      return true;
  }

I'm not sure what I'm doing wrong but I am getting the following error every time:

  Error: Invalid number of arguments to Solidity function

I am declaring the following variables in my Solidity file:

  address public client;         //ETH wallet address for the client

  int contract_amount;

The parameters would be getting transferred via the click of a button.


texts:
I am wondering how can I have ethers in my contract. I have 2 contracts associated with different accounts.

I want to send ethers from one contract to another but how do I have ethers in my contract first to be able to send it ?

Here is the example:

contract ethertransfer {
  function fundtransfer(address etherreceiver, uint256 amount) {
    if(!etherreceiver.send(amount)) {
       throw;
    }
  }
}

contract etherreceiver {

  function etherreceiver() {
  }
}


texts: Is it possible for a ERC20 token to be associated with an application account after the fact?

texts:
Say you want to create a new utility token offering, and owning that token will be useful in an application still in development. You don't want to dissuade people from purchasing by requiring a lot of information up front during the sale, but rather, you want to allow them to associate their tokens with their account in the forthcoming application.

Is this possible, and if so, what are your suggestions for doing so?

Caveats:

newbie here, might be a dumb or obvious question
I suppose you'd be able to validate the number of tokens with a wallet address, but that information is public AFAIK, so that wouldn't be very helpful
functionality can be built into the original contract to make this work

Thanks!


texts: Extremely slow sync after moving to external drive (macOS; thunderbolt)

texts:
I was getting low on disk space so I decided to move the blockchain to an external drive with thunderbolt. I did it using Method 2 from this answer: In Mist browser how can I move the data (blockchain) to another drive on Mac OSX?

Now when I start Ethereum Wallet (Mist), the sync is extremely slow. It's been like 5 minutes and I downloaded only about 10 blocks, which is like 20x times slower than when I was downloading to internal drive.

Is there any way to make it go faster? Shouldn't it be downloading directly to the external drive? It's thunderbolt so it should be fast (40GBs), no?


texts: ERC721 Dapp not working, not showing token owner

texts:
So I am building a Dapp to interact with an ERC721 contract. So far I'm able to mint, transfer and check an address balance. I'm stuck with trying to show who owns which token( via their token id). The output keeps saying

  0x

It randomly works and shows the address of the owner. The console is not showing any errors. Attached are my code and picture of the output.
Thanks in advance.

HTML CODE

Token Owner

Token ID;<input type="text" id="tokenId" placeholder="e.g., 03945812"></input>

Owner is

<button id="check" onclick="App.ownerOf()">Check</button>

App.js Code

//App.ownerOf function 5
ownerOf: function(){ //stuck at Checking blockchain info... not throwing an error
var self = this;

var tokenId = parseInt(document.getElementById("tokenId").value);

this.setStatus("Checking Blockchain info...");

var check;
ERC721Token.deployed().then(function(instance){
  check = instance;
  return check.ownerOf.call(tokenId,{from: account});
}).then(function(account){ //function(owner)
  var value;
  value = account;
  var account_element = document.getElementById("wallet");
  account_element.textContent = value.valueOf();
}).catch(function(e){
  console.log(e);
  self.setStatus("Error checking ticket ID; see log");
});
}

ERC7221BasicToken.sol Code

...
function ownerOf(uint256 _tokenId) public view returns (address) {
  address owner = tokenOwner[_tokenId];
  require(owner != address(0));
  return owner;
 }

Web Screenshot

Thanks Again! Let me k now if you guys need me to add anything else.


texts: Why do `throw` and `revert()` create different bytecodes?

texts:
throw and revert() are both compiling to the revert operation (opcode 0xfd). According to the docs:

  The throw keyword can also be used as an alternative to revert().

Why is it then that the following contract

contract test {
    function () {
        throw;
        //revert();
    }
}

produces different bytecode if I use revert() instead of throw in the example above? I am using Remix with Solidity 0.4.13+commit.0fb4cb1a.Emscripten.clang. These are the resulting opcodes:

using throw:    PUSH1 0x60 PUSH1 0x40 MSTORE CALLVALUE ISZERO PUSH1 0xE JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST JUMPDEST PUSH1 0x47 DUP1 PUSH1 0x1C PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN STOP PUSH1 0x60 PUSH1 0x40 MSTORE JUMPDEST CALLVALUE ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x19 JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST JUMP JUMPDEST STOP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256 0x4a PUSH32 0x5473469C00A2379987B5AF61DFF50F8FABE3B71589C4D2BBB53073BEB9D10029
using revert(): PUSH1 0x60 PUSH1 0x40 MSTORE CALLVALUE ISZERO PUSH1 0xE JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST JUMPDEST PUSH1 0x47 DUP1 PUSH1 0x1C PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN STOP PUSH1 0x60 PUSH1 0x40 MSTORE JUMPDEST CALLVALUE ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x19 JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST JUMP JUMPDEST STOP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256 0x5f 0xef 0xc4 0xac 0x4c STATICCALL DUP15 TIMESTAMP CODECOPY PUSH10 0x17070269221C62F6F5D4 0xba 0xe1 BALANCE BYTE 0xf7 EQ 0xca SWAP6 SWAP13 0xd0 0x27 0x24 STOP 0x29

We see that the last instructions are different. While the version with throw ends on

0x627A7A723058
KECCAK256
0x4a
PUSH32
0x5473469C00A2379987B5AF61DFF50F8FABE3B71589C4D2BBB53073BEB9D10029

the version with revert() ends on

0x627A7A723058
KECCAK256
0x5f
0xef
0xc4
0xac
0x4c
STATICCALL
DUP15
TIMESTAMP
CODECOPY
PUSH10
0x17070269221C62F6F5D4
0xba
0xe1
BALANCE
BYTE
0xf7
EQ
0xca
SWAP6
SWAP13
0xd0
0x27
0x24
STOP
0x29


texts: Fatal: Error starting protocol stack: gap -- Chain freezer table opened

texts:
I started to get following error: Fatal: Error starting protocol stack: gap (#3697270) in the chain between ancients and leveldb. What may be the cause of this error?

I was able to fix it by syncing my chain from scratch.

(geth version: 1.9.13-unstable)
// Please see the debug log with the highest verbostiy:
$ sudo geth --syncmode fast --cache=1024 --shh --datadir /private --port 3000 \
            --rpcaddr 127.0.0.1 --rpc --rpcport 8545 --rpccorsdomain="*" \
            --networkid 12345 --rpcapi admin,eth,net,web3,debug,personal,shh \
            --targetgaslimit '10000000' --gasprice "18000000000" \
            --allow-insecure-unlock --verbosity 5
DEBUG[08-09|18:48:48.751] Sanitizing Go's GC trigger               percent=100
INFO [08-09|18:48:48.751] Maximum peer count                       ETH=50 LES=0 total=50
INFO [08-09|18:48:48.751] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
DEBUG[08-09|18:48:48.751] FS scan times                            list=25.366µs set=2.999µs diff=1.612µs
TRACE[08-09|18:48:48.751] Handled keystore changes                 time=45.406µs
TRACE[08-09|18:48:48.751] Started watching keystore folder         path=/private/keystore
INFO [08-09|18:48:48.752] Starting peer-to-peer node               instance=Geth/v1.9.13-unstable-0e6ea919/linux-amd64/go1.13.1
INFO [08-09|18:48:48.752] Allocated trie memory caches             clean=256.00MiB dirty=256.00MiB
INFO [08-09|18:48:48.752] Allocated cache and file handles         database=/private/geth/chaindata cache=512.00MiB handles=524288
DEBUG[08-09|18:48:48.837] Chain freezer table opened               database=/private/geth/chaindata/ancient table=bodies items=3697270 size=23.61MiB
DEBUG[08-09|18:48:48.838] Chain freezer table opened               database=/private/geth/chaindata/ancient table=receipts items=3697270 size=11.91MiB
DEBUG[08-09|18:48:48.838] Chain freezer table opened               database=/private/geth/chaindata/ancient table=diffs    items=3697270 size=14.07MiB
DEBUG[08-09|18:48:48.838] Chain freezer table opened               database=/private/geth/chaindata/ancient table=headers  items=3697270 size=1.05GiB
DEBUG[08-09|18:48:48.839] Chain freezer table opened               database=/private/geth/chaindata/ancient table=hashes   items=3697270 size=112.83MiB
INFO [08-09|18:48:48.839] Opened ancient database                  database=/private/geth/chaindata/ancient
Fatal: Error starting protocol stack: gap (#3697270) in the chain between ancients and leveldb


texts:
How can one set the block height of testrpc so that a contract can react on the new height.

Concrete problem is that I want to write an automated test that shows that after a certain block number conditional can be executed.


texts: Generic remapping of "import" statements

texts:
I have vim setup to report solc errors while editing via syntastic.

If I have the line:

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

I receive the error:

Source "zeppelin-solidity/contracts/token/StandardToken.sol" not found: Unknown exception in read callback. [solidity/solc]

I get the analogous error at the command line using solc.

However truffle compile --all works just fine.

I have vim setup with:

let g:syntastic_solidity_checkers   = ['solc', 'solium']

How do I get rid of this error?


texts: Let's say a miner created an invalid block and the network catches the miner red handed. Then the miner loses all the coins staked on that block. What I do not understand is where do these coins go?


texts:
I am testing stuff on Ganache and am using Metamask to send transactions to simulate user behavior with the app. Now here's the issue. If I restart Ganache it resets all accounts (no problem with that). However, Metamask keeps the old transactions in it's memory and thinks the nonce of a new transaction is nonzero. That is not true.

If I want to fix this, I should delete all my accounts, which I am not going to do. There should be a default way of resetting nonces. I've tried reconnecting to the network, but it seems that it remembers that even "localhost:7545" will be the same network all the time, hence nonces never change.


texts:
I am wondering if this is even a problem. So I have a function that calls another contract. After the first call to the external contract I call it again. I am not just reading data on each one of these calls, I am writing. My question is, will I have an issue if I call two writing methods on an external contract all within a single function.

Note I am also using some of the data from the first method call to call the second method. Is the transaction time between the two going to use to much gas, or what?


texts: In a futarchy, how do you measure the success of a specific proposal?

texts: Concrete example: in a futarchy system, we have 3 current indices, Ia, Ib, Ic, reflecting desired values, and 3 proposals P1, P2, P3 just passed. In 1 year, you measure the indices and confirm that they increased, which means the proposals succeeded. Problem is, how do you pick which proposals were responsible for the good effects? It could very well be the case that proposal P1 and P2 were outstanding, but P3 was awfully damaging. Since the overall indices increased, you can't detect that P3 was a bad choice, you can only assert the group of proposals did good.


texts:
I'm trying to integrate uPort in one of my project and, the first thing that I noticed are the different ways to give a provider:

from the official repository uPort-lib

let web3 = uport.getWeb3()
from the official example

let rpcUrl = "https://consensysnet.infura.io:8545";
let Uport = window.uportlib.Uport;
  let web3 = new Web3();
  // App options
  let options = {
    ipfsProvider: {
      host: 'ipfs.infura.io',
      port: '5001',
      protocol: 'https',
      root: ''
    }
  }
  let uport = new Uport(appName, options)
  let uportProvider = uport.getUportProvider(rpcUrl)
  web3.setProvider(uportProvider)

and after

let uport = new Uport('TEST92184091284091284')
 let web3 = uport.getWeb3()

from uPort test-app

let web3 = new Web3()
let options = {
  ipfsProvider: {
    host: 'ipfs.infura.io',
    port: '5001',
    protocol: 'https',
    root: ''
  }
}
let uport = new Uport('TestApp', options)
let uportProvider = uport.getUportProvider('https://ropsten.infura.io:8545')
web3.setProvider(uportProvider)

In .1 which provider? https://ipfs.infura.io:5001?

In .2 uPort use https://ipfs.infura.io:5001 or https://consensysnet.infura.io:8545 ?

In .3 https://ipfs.infura.io:5001 or https://ropsten.infura.io:8545

and... what happen if I use my provider :) https://ropsten.infura.io/myKey?


texts: Find all pending transactions from my account with web3

texts: I've sent a few transactions a few days ago and they haven't been mined yet. Now I try to find them because they do not show up on etherscan at all. I tried finding my transactions with various web3 functions but didn't have any success so far. Then I stumbled accross parity_pendingTransactions and txpool_content to see If my transactions are still there. Unfortunately I don't have a node set up on my PC right now. Parity is still syncing and I think this will go on for a bit. Is there a way to get a list of all pending transactions with web3? Or is there a way to get something like txpool_content or parity_pendingTransactions using metamask?


texts:
while looking on Etherscan I see a several types of failed transactions:

Bad Instruction
Bad Jump Destination
Reverted
Out Of Gas

I can only understand Out Of Gas failure. what is the reason for the others?

Also, I saw that there are failed transactions with the word [CANCELLED] and some are without it.

for example:
with cancelled : https://etherscan.io/tx/0x67ec3acc5274a88c50d1e79e9b9d4c2c3d5e0e3ba3cc33b32d65f3fdb3b5a258

without cancelled :
https://etherscan.io/tx/0xc2c388756c7e379d7ebb7af58a7f54156ac83a8df702b7b72f111344fe2df013


texts: How does Ethereum client select which peers to synchronise with?

texts:
On start up the discovery protocol uses a Kademlia style approach to find peers. Thus we obtain a local routing table which holds the (IP address, UDP port, and node ID) of some online and alive peers.

The next stage as I understand it is:

Run a server which implements the Devp2p wire protocol
Connect to some peers to synchronise the blockchain.
Connect to some peers in order to broadcast any transactions.

What is the strategy used in order to select which nodes to connect to?

e.g.

How many nodes do we connect to?
What is the criteria for selecting which nodes to connect to
What is the criteria for banning nodes
How does this strategy ensure full network connectivity without partitions?


texts:
This contract correctly connect an username to their public address. But when I used the function to display the name by their address, the user name isn't shown but instead of that their is an address but not the actual name. (see picture below). How can I make it happen to show the users name instead of a address?

      contract Users {

    mapping (address => bytes32) public names;
    mapping (bytes32 => address) public owners;

    function register(bytes32 name) {

            owners[name] = msg.sender;
            names[msg.sender] = name;

    }
}


texts: How can I recover the Ethereum wallet from an old OS X backup?


texts: Transfer token failed due to Gas estimation failed

texts:
Have issue transfer token, hope to get support from this. my contract https://rinkeby.etherscan.io/address/0x6D96673922d54108e8eFaFDe191Dc473dCeE709B
pragma solidity ^0.5.0;

import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Capped.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/ownership/Ownable.sol";

contract OceanToken is Ownable, ERC20Detailed, ERC20Capped {

    using SafeMath for uint256;

    uint256 CAP = 1410000000;
    uint256 TOTALSUPPLY = CAP.mul(10 ** 18);

    constructor()
        public
        ERC20Detailed('OceanToken', 'OCEAN', 18)
        ERC20Capped(TOTALSUPPLY)
        Ownable()
    {
        _mint(msg.sender, TOTALSUPPLY);
    }

}

contract Try {
  //address token address = 0x8967bcf84170c91b0d24d4302c2376283b0b3a07; // token address
  mapping ( address => uint256 ) public balances;

     IERC20 public token;

    constructor(address _token) public {
        token = OceanToken(_token);
    }

  function deposit(uint tokens ) public payable{

    // add the deposited tokens into existing balance
    balances[msg.sender]+= tokens;

    // transfer the tokens from the sender to this contract
    token.transferFrom(msg.sender, address(this), tokens);
  }

  function returnTokens() public {
    balances[msg.sender] = 0;
    token.transfer(msg.sender, balances[msg.sender]);
  }

}


texts: I have transfered ether from coinbase to metamask. the transaction is complete and i see the confirmation and all on etherscan. I didn't see the balance on Metamask so I connected to the testnetwork and reconnected to the ethereum one. Now I see the ether's transaction in the Activity tab. I see "receive" the money, with an actual arrow but I don't know how to import them in my wallet!


texts: Creating raw transactions for sending ERC721 tokens

texts:
I was able to create raw transactions for eth following this article https://medium.com/blockchain-musings/how-to-create-raw-transactions-in-ethereum-part-1-1df91abdba7c

However, how can I create raw transactions when send ERC721 tokens? More specifically, where do I add the token id field when creating raw transactions?


texts: Can an ENS name point to a contract address?

texts: I know that an ethereum wallet address can have a ENS (Ethereum Name Service) name, but it is possible for a contract? So instead of giving the contract address is it possible to give the contract's ENS name?


texts:
In Geth, if I use the --nodiscover option, my node won't be discovered by default from other nodes.

Conversely, with bootnode tool implemented in geth, first I have to generate a key, then I have to use the command

bootnode -nodekey "./boot.key" -addr "addr:port"

and lastly I have to put the output enode information as parameter when starting each node (so that I can have an authomatic "adding peers mechanism"). However, using this tool, I can't use --nodiscover option.

Is it less secure to use this tool? Could my nodes be discovered from external nodes?


texts: I found 4 very similar wallet addresses. How is this possible?

texts:
These are the addresses:

0x7cB57B5A97Eabe94205c07890BE3C1aD31E486A8
0x7Cb57B5a97EaBe94205c07890bE4C1aD31E456a8
0x7cB57B5A97eAbe94205C07890BE4c1aD31E486A8
0x7CB57b5A97eabe94205C07890beaC1aD31E486a8

They all have transactions on Etherscan, is there a method i don't know to create similar addresses?


texts: Suck at JavaScript and overall just a beginner in the dev world. Whats the best way to begin building DApps? The title is my question LOL.


texts: Error: Contract not deployed after cloning private geth network from one server to another

texts:
Steps to reproduce:

Private geth network is running on server1.

Deploy contract using truffle and make a few transactions.

Stop geth n/w of server1 and copy its entire directory (accounts.txt,
boot.key, genesis.json, node's password.txt along with its
directories keystore and geth) and paste to server2

Change in the geth configuration --rpcaddr 'xx.xx.xx.xx' with private IP of the server2.

Bring up this geth network clone of server1 on server2 (it is able to
successfully seal new block, mine potential block, and commit new
mining work)

Interact with contract on server2.

Error: contract not deployed

Restart the stopped geth n/w on server1 (it is able to successfully seal new block, mine potential block, and commit new mining work)

Interact with contract on server1.
Error: contract not deployed.
Expectation: Restarting the geth n/w on server1 should not cause any data loss and should be able to interact(get the transactions performed on server1 as the data should be present in chaindata) with the contract on server2.
Note: I was able to migrate a test geth n/w successfully for a n/w running from past 2 days. After this successful operation, I was migrating this geth n/w which was running from past 7 months which is failing now with error contract not deployed. Will it sync/heal itself if its up for a long time? What are the correct ways to restart and migrate the n/w with huge chaindata.


texts:
I have been working on a dApp where a user can create contests and set attributes of contest like contest start date, end date, no of players, entrance fees etc. There can be N no of contests running parallelly. There will be a third party API call every 5 minutes for each player which would calculate some score of each player.

The contest will automatically end at the defined end date and the winner is decided by the score calculated by third-party API call. Anyone can join the contest. So, we have contests data and players data.

I am not sure of the contract structure for the same. Do I have to keep all the data on the contract, or I can put some data off Blockchain as well like calling third-party API and calling contract on contract end date? And would multiple contests would run on the same contract, or do I need to redeploy the contract for each contest?

Any help would be appreciated.
Thanks


texts: Comparing msg.value using javascript test always fails

texts:
So I have this solidity function:

function claimGoodTest(uint256 typeId) public payable {
    if (msg.value < 4000) revert();
}

I test it with the following:

var result = await contract.claimGoodTest(typeId, {
    from: accounts[0], value: web3.utils.toWei('40', 'ether')
}, function(result) { })

I get this :

Error: VM Exception while processing transaction: revert

Why is this happening ?  This seems like a bug or I have the wrong syntax.


texts: How do I give every user Ethereum an address and does it affect security

texts:
I have a project with Ethereum Blockchain  the users send the data to the server and the server writes the data in the blockchain network
My question is how do I represent the server in the smart contract?
I guess I got it wrong when I said server
If I said that the server is a user in the network
My question, do you have an idea how each user can send data to the contact


texts: How to sign data locally without access to Ethereum node with web3.eth.sign, web3.eth.personal.sign functions?

texts:
When I use web3.eth.sign, web3.eth.personal.sign functions to sign data I should pass to them account address.

eth.sign(dataToSign, address [, callback])
eth.personal.sign(dataToSign, address, password [, callback])

My understanding is that these functions are usually provided with address by connecting to Ethereum node. Then my understanding is that these functions communicate with node to retrieve respective for the address private key.

If I run these functions on a client that does not connected to a node, how these functions can be used to sign data? I guess they would get private key from keystore file or passphrase, or metamask that are available locally. How the retrieval of private key from these local sources is done, passed to web3.eth.sign, web3.eth.personal.sign functions?
An example, would be very much appreciated.


texts: I run private geth testnet and my program is on docker. Everytime I try to call api I get: no JSON RCP response. Must I run geth on docker too?


texts: In ethereum network how data structured and is every data stored, is public?

texts:
Let's say, 3 companies are using ethereum network.

Company A
Company B
Company C

Company A put some data, block01 and block02. So ethereum network looks like,

  Genesis Block -> block01 -> block02

Now Company B put another piece of data block03. So the chain looks like,

  Genesis Block -> block01 -> block02 -> block 03

Here come the Company C and this company put bock04 and block05

So finally the blockchain is like

  Genesis Block -> block01 -> block02 -> block03 -> block04 -> block04

Am I right about the blockchain architecture?

Also, all the data stored in the block, are they visible to all?
Can anyone check the data inside block in the ethereum network?


texts: Are there any public services which allow broadcasting tx (like etherscan.io/pushTx)?

texts: I'm looking for a way how to broadcast signed raw tx without Ethereum node. It's possible to do via https://etherscan.io/pushTx, but I'd like to find other options because of reliability.


texts: What are payment channels? Can they be implemented on Ethereum?

texts: I've read bits and pieces on payment channels and the benefits it would provide for micro-transactions.  For example, under the current fee structure, it's not wise to send micro transactions below the mining fee since it would cost you more to send the value.  Are there any mechanism to open payment channels where micro-transactions can be lumped to reduce mining fees?  Either now, or within a future version of Ethereum (i.e. planned release )?


texts: What is the fundamental value of Ethereum according to state of the art economic theory?

texts: For example professional investor apply the Capital Asset Pricing Model (CAPM) to determine the intrinsic value of an equity. What would be the result of such a financial analysis?


texts: How can I see the transactions which move funds from a destroyed contract?

texts:
I got this external account from which I called a function of this contract which subsequently called selfdestruct and sent all the funds to the caller.

Where can I see the tx making this transfer? There's no internal transactions tab in the external account's page, but there is one in the tx page. However, it displays 0 Ether, although the external account was actually funded with 0.03 ETH.


texts:
I am trying to run the follow code that queries an address to track the balance of an ERC 20 Token through the chain's. Eventually I plan on running a big array of account through all the blocks track balances for every account that has ever owned this token.

const Web3 = require('web3')
const web3 = new Web3(`http://some_url`);

const contractAddress ='some_contract_address'
var contract = new web3.eth.Contract(contractAbi, contractAddress);

const address ='0x6C1F09F6271fbE133Db38DB9c9280307F5d22160';

for (var i = 0; i < 8444182; i++) {
    contract.methods.balanceOf(address).call(null, i, (error, balance) => {

    contract.methods.decimals().call((error, decimals) => {
    //   balance = balance.div(10 ** decimals);
      console.log(balance);
    });
  })};

Unfortunately, I get the following error:

  <--- Last few GCs --->

  [14889:0x103000000]    72963 ms: Mark-sweep 3982.1 (4188.2) -> 3971.5
  (4191.2) MB, 2127.2 / 2.2 ms  (average mu = 0.121, current mu = 0.031)
  allocation failure scavenge might not succeed [14889:0x103000000]
  75158 ms: Mark-sweep 3985.1 (4191.2) -> 3974.5 (4194.2) MB, 2133.7 /
  2.3 ms  (average mu = 0.076, current mu = 0.028) allocation failure scavenge might not succeed

  <--- JS stacktrace --->

  ==== JS stack trace =========================================

0: ExitFrame [pc: 0xa18d83dbe3d]
1: StubFrame [pc: 0xa18d83847bb]
2: ConstructFrame [pc: 0xa18d838d145] Security context: 0x1836dc99e6e9 <JSObject>
3: DoJoin(aka DoJoin) [0x1836dc985e91] [native array.js:~87] [pc=0xa18d863daad](this=0x1836988026f1 <undefined>,l=0x18363c5bf0a9

  ,m=40,A=0x1836988028c9 ,w=0x1836988029f1
  ,v=0x1836988029a1 )
      4: Join(aka Join) [0x1836dc985ee1] [native ar...

  FATAL ERROR: Ineffective mark-compacts near heap limit Allocation
  failed - JavaScript heap out of memory  1: 0x10003b59c node::Abort()
  [/usr/local/opt/node@10/bin/node]  2: 0x10003b775
  node::OnFatalError(char const*, char const*)
  [/usr/local/opt/node@10/bin/node]  3: 0x10017bf4f
  v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool)
  [/usr/local/opt/node@10/bin/node]  4: 0x10017bef0
  v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char
  const*, bool) [/usr/local/opt/node@10/bin/node]  5: 0x100431c74
  v8::internal::Heap::UpdateSurvivalStatistics(int)
  [/usr/local/opt/node@10/bin/node]  6: 0x1004338b3
  v8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double)
  [/usr/local/opt/node@10/bin/node]  7: 0x100430f4e
  v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector,
  v8::GCCallbackFlags) [/usr/local/opt/node@10/bin/node]  8: 0x10042fd6d
  v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace,
  v8::internal::GarbageCollectionReason, v8::GCCallbackFlags)
  [/usr/local/opt/node@10/bin/node]  9: 0x10043854e
  v8::internal::Heap::AllocateRawWithLigthRetry(int,
  v8::internal::AllocationSpace, v8::internal::AllocationAlignment)
  [/usr/local/opt/node@10/bin/node] 10: 0x100438598
  v8::internal::Heap::AllocateRawWithRetryOrFail(int,
  v8::internal::AllocationSpace, v8::internal::AllocationAlignment)
  [/usr/local/opt/node@10/bin/node] 11: 0x100418d73
  v8::internal::Factory::NewFillerObject(int, bool,
  v8::internal::AllocationSpace) [/usr/local/opt/node@10/bin/node] 12:
  0x1005f247a v8::internal::Runtime_AllocateInNewSpace(int,
  v8::internal::Object**, v8::internal::Isolate*)
  [/usr/local/opt/node@10/bin/node] 13: 0xa18d83dbe3d  Abort trap: 6

The error still persists after running

export NODE_OPTIONS=--max_old_space_size=4096

I will appreciate any pointers on this. Is there a more efficient way of doing this that will not draw on as much memory?


texts: NFT wallet transfer pending on ETH but succeeded on Matic?

texts:
Wondering if anyone can advise me on the below...
I transferred inventory from my Matic wallet to my Ethereum wallet on Arkane Network.
There were two separate NFT's and the Matic transaction history says both transactions succeeded at 16:26 and 16:28 respectively, the inventory now empty.
When I go on to my Ethereum wallet's transaction history the transactions are still pending.
Does anyone know how long the transaction should/could take until it appears in this wallet?


texts: Get number of all the past events using ethers v5

texts:
I am writing an integration test and I need to get the number of all the past events using ether.js. The issue I am having is that it seems like I receive only 1 event even though there should be 4 in total.
Here is the code I use:
  const provider = new ethers.providers.JsonRpcProvider(TEST_JSON_RPC)
  const loanVaultFactory = new ethers.Contract(
    address,
    abi,
    provider.getSigner(0)
  )
  let events = loanVaultFactory.filters.LoanVaultCreated()
  console.log(events)

And this is the output:
{
  address: '0x27e8A5B8Af57aEE27A33247D867ED52173876791',
  topics: [
    '0x2c80e53ce4a0770abb7d3436ea6bc5ff59702f84b0d9378b4c58cc59e4618042'
  ]
}

I would expect there to be 4 items in the topics list. Am I doing something wrong with the filters?
Thank you


texts:
So basically I'm trying to make something like that.
Btw. Logic is not important.

modifier validateValue(uint fee){ if(msg.value != ((0.1 ether) * fee)) revert(); _; }

modifier checkFee(address payOutAddr){
    uint begin = 30 * uint(payment[phoneBook[payOutAddr]].paymentsCount);
    uint end = begin + 15;
    uint cycleOfContract = now - startDate;
    if(begin < cycleOfContract && cycleOfContract < end){
        return validateValue(1);
    }
    else {
        uint totalFee = (int(cycleOfContract/30) + 1) * 0.02 ether;
        return validateValue(totalFee);
    }
}

I want to make a modifier returning modifier, but this can't compile. Is there a way to make something like that?


texts: How to get data location for string > 31 length

texts:
The documentation says:

bytes and string are encoded identically. For byte arrays that store
data which is 32 or more bytes long, the main slot stores length * 2 +
1 and the data is stored as usual in keccak256(slot).

I am working with a string (> 31 bytes), a state variable in storage, and am trying to get the location of the data. I am passing the slot number (converted to a bytes variable) to keccak256. It returns a bytes32. How do I use that to find out where the data is stored?
If it matters, I am getting the bytes32 value from this code.
bytes32 data_slot = keccak256 (uint_to_bytes (slot_number));

And the function is defined like this.
function uint_to_bytes (uint value) internal pure returns (bytes memory)
{
    uint byte_count = value <= 255 ? 1 : 2;
    bytes memory slot_contents = new bytes (byte_count);

    uint content_index = 0;
    bool value_started = false;
    for (int16 b = 31; b >= 0; b--)
    {
        uint a = uint (b);
        uint shift = a * 8;
        uint anded_value = (0xff << shift) & value;
        uint8 this_byte = uint8 (anded_value >> shift);

        if (this_byte > 0)
            value_started = true;

        if (value_started)
            slot_contents [content_index++] = byte (this_byte);
    }

    return slot_contents;
}

In my case, the base slot number is 5, which contains the length of my string. The length in that slot is correct.
But how do I get the location of the data when keccak256 returns a bytes32. When I convert the bytes32 to a uint256, I get 99383055861825221844433915613614375939768875017829574557572350922731547121557. Certainly that can't be the slot number where the data is.


texts: How to remove this ParserError of contract in solidity langauge. I am using remix ide

texts:
pragma experimental ABIEncoderV2;
pragma solidity >=0.4.18;

contract Record {
    struct MedRecord {
        string password;
        string name;
        address patient;
        address[] doctor;
    }

    mapping(address => MedRecord) internal medRecords;

    address[] public recordList;

    function addRecord(address _key, string memory password, string memory name) public {
        address docs[] = new ;
        medRecords[_key] = MedRecord(password, name, _key, []);
        recordList.push(_key);
    }

    function remove(address _key) public {
        delete medRecords[_key];
    }

    // function contains(address _key) public view returns (bool) {
    //     return MedRecords[_key][0] != '';
    // }

    function getByKey(address _key) public view returns (MedRecord memory) {
        return medRecords[_key];
    }
}

And its throwing error:

browser/tests/project/record.sol:18:21: ParserError: Expected ';' but got '[' address docs[] = new ;

The code looks fine to me.