texts: How contract method returns struct or array?

texts:
I have written a contract. It store struct data based on key. I want to write a get method which accept key and return all the stored data mapped to provided key.

Can anyone help into this


texts:
How to unlock account from web3?

How to enable ipcapi from geth javascript console?


texts: Do I have to run geth locally to access Rinkeby via web3.js?

texts:
I have used truffle to a migrate some contracts to a local instance of geth that points at Rinkeby. The problem is that I'm behind a firewall, with little hope of getting port 8545 open, so now I can't get my dApp to use those contracts :(

However, do I have to use a local instance of geth to access contracts deployed to Rinkeby, via a dApp?

In other words, within my dApp, instead of:

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

Can I do something like:

window.web3 = new Web3(new Web3.providers.HttpProvider("http:/api.rinkeby.io:8545"));

...or some such like?


texts: Reward for running a full node on some blockchain?

texts:
For today, it takes a lot of time to install & sync a full node of the most popular blockchains - Bitcoin, Ethereum, etc. That's why so many people use only light wallets like Jaxx or Electrum. Which is not the blockchain way at all.

So the question is - can you name some protocols/consensus mechanism or anything else, which can solve this problem? Maybe it's possible to give a part of mining reward to the full nodes holders?


texts: AAVE Protocol v1 issue on reserve addresses with compound ctoken addresses

texts:
https://kovan.etherscan.io/tx/0xa7f5e857d1a9ecb4aca0714b24a70ca0942cc1a656c8e09b6d01bab9af4ec9e5
I am trying to make a transaction from DSProxy (Smart Wallet) on a contract
https://kovan.etherscan.io/address/0x718099d292b1ad14555e25889a91e7d11552ec0c#code
Which make a importLoan transaction on the aave protocol v1 address of lending pool
the token are of compound protocol , which needs to get loan on a contract which is :
https://kovan.etherscan.io/address/0x847c2772610712407f9afd780cdb206658913944
In this case what i see, on kovan the transaction is failing because the reserve address of ctoken is not avalible on aave protocol , if yes let me know how i can run this on kovan network !?


texts: Possible to create new contract via a proposal in the ethereum.org/dao framework?

texts:
Is it possible to deploy contracts from within contracts, using something like
    p.recipient.call.value(p.amount * 1 ether)(bytecode);

This article says so, https://blog.ethereum.org/2015/12/04/ethereum-in-practice-part-2-how-to-build-a-better-democracy-in-under-a-100-lines-of-code/

  Can it get any better than this? Actually, it can. On our next post we will explore how you can use “transactionBytecode” to allow the DAO to execute any kind of ethereum transaction, even owning or creating other contracts.

But when I try create a contract by sending the bytecode without an address field, the transaction is sent to 0x0000000000000000000000000000000000000000 but no contract is created.

UPDATE:

  Show us your code! We can't usefully help if we can't see what
  you're trying. – Nick Johnson

In the ethereum.org/dao framework, doing new proposal,

bytes32 transactionBytecode =  0x606060405260068060106000396000f3606060405200

newProposal(transactionBytecode)

to create contract

contract MyContract {
    /* Constructor */
    function MyContract() {

    }
}

The bytecode should create a new contract, but no contract is created. If I do the same transaction from a human account, it deploys a contract.


texts: Is there any benchmark about the speed of blocks search engines?

texts:
I want to know the performance of search engines such as blockchain.info, smartbit or blockr.io I know that they are very speed but I want a real benchmark that gives the actual speed (in seconds or milliseconds) of a research operation by block number or address.

If no benchmark exists, could you, please, guide me on the necessary steps to follow in order to make such a benchmark?

Thanks.


texts: Where are the smart contract accounts stored in geth?

texts: I have a single geth node running a private blockchain with a network ID N and data directory data/. I had deployed a smart contract ContractName on the same and things were working fine. I wanted to start fresh once again, so I deleted the directory data/geth/ entirely and ran geth init and started my node with the same network ID N. However, when I enter truffle console and run ContractName.address, I am still returned an address. The block data has been reset and the new block number is 0. How is this happening?


texts: How to implement a data-type Range (or Interval) in Solidity

texts:
For a Smart Contract, in Solidity, we want to implement ranges.

The reason is that many interactors do so on "ranges". Our Contract holds batches of coupons which we don't need, nor want to, track individually. Interactors simply say "give me the next 200 coupons" after which we update the state of Range. Which allows interactors to check for the state of "individual" Coupons as well.

A pseudo-interface would look like:

contract.issue(10000)
contract.amountAvailable() #=> 10.000
contract.reserve(200, { from: A })
contract.reserve(800, { from: B })
contract.reserve(9001, { from: C }) #=> Fails, not enough available.
contract.amountAvailable() #=> 9.000
contract.amountReserved(A) #=> 200
contract.amountReserved(B) #=> 800
contract.stateOf(16) #=>  1 (reserved)
contract.stateOf(9001) #=> 0 (free)

From here on, an interactor can perform an action on a single coupon, for the example, coupon with ID 16. Which changes the state of this coupon. This is where it becomes hairy.

contract.claim(16)
contract.amountReserved(A) #=> 199
contract.amountReserved(B) #=> 800
contract.claim(16) #=> Fails.

Because 16 is within the batch/range "reserved" by A, the mapping that maintains reserved-batches per address must be updated; most probably, it needs to be split into two ranges: 1-15 and 17-200. But this is an implementation detail that I'm not certain of.

What I'm trying to show, is that operations work on ranges, but that an interface allows for the checking of singular items. Those singular items could be considered "virtual" in the sense that they are not stored in some mapping or array.

A Range would be a pair of integers: [bottom, top] and have associated helper methods such as memberOf(item, range), length(range) or pop(amount, range).

We chose not to manage individual items, because (i) we don't need to and (ii) we found that e.g. ERC721 as provided by e.g. Solidity, is above all expensive here. E.g. in order to mint (issue) 100 unique tokens with ERC721 from Solidity, we already needed 14.164.312 gas. So we investigate operating on ranges instead.

So, is there a library, standard or common practice on how to implement a Range? Is this maybe covered in an ERC that I overlooked?


texts:
I am currently running a private ethereum chain with 2 nodes. My coinbase address on the main node has plenty of ether so I went to make a transaction but got the error "Gas Limit exceeded". I noticed that the gas limit was set to 5000 which is too low to make a transaction so I went to the customised genesis.json file and increased the limit to "0xC350" or 50000. Despite this the limit only moved to 5003. I have no idea why it does this and I have replaced the figure with other bigger numbers yet it only ever manages to get to 5003 instead of the default 5000. Any help would be much appreciated.

Here is my Genesis.json file:

{
"nonce": "0x0000000000000042",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x0",
"gasLimit": "0xC350",
"difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333",
"alloc":
{
    "0xcf117e46aa225864ed1d0dd7e99b8b006abe3410":
    { "balance": "10000000000000000000000000" }
}

}

I am using Geth.


texts:
If I were trying to make a synthetic unsigned integer_512, but the largest supported integer in Ethereum is u256, how would I combine 2 u256 to make a single u512 in solidity?

If I were also looking to overload operators like gt, lt, eq, read/show/tostring, being mappable keys, on this joint data type---all of the functions that exist on a base data type, where is a good template for how to do this correctly or get started?

Thank you


texts: Why call() function stopped working in solidity 0.5.0?

texts:
I am sending ether to another smart contract and calling its fallback function with higher gas as like:

contractAddress.call.value(1 ether).gas(53000)();

It was working in solidity version 0.4.25 but it stopped working in 0.5.0 giving me error:

  TypeError: Wrong argument count for function call: 0 arguments given
  but expected 1. This function requires a single bytes argument. Use ""
  as argument to provide empty calldata.

If I try to add blank argument in call() as it says in the error, then it gives me another error:

  TypeError: Member "value" not found or not visible after
  argument-dependent lookup in tuple(bool,bytes memory) - did you forget
  the "payable" modifier?

I studied the breaking change documentation but that still could not find the solution.
Any help would be appreciated :)


texts: Error when subscribing to ERC-20 (BAT, i.e. Basic Attention Token)

texts:
I'm trying to subscribe to BAT(Basic Attention Token) ERC-20 token "Transfer" event to detect any transaction made to my ethereum address using web3 in nodejs. I'm using parity (Parity/v1.10.6-stable-bc0d134-20180605/x86_64-linux-gnu/rustc1.26.1) node running on same local machine -

parity --jsonrpc-hosts all --jsonrpc-apis all --ws-apis all --ws-hosts all --ws-origins all --ws-interface all

Here is the code that I've used to subscribe -

const Web3 = require('web3');
const abi = require('human-standard-token-abi');

var contract = '0x0D8775F648430679A709E98d2b0Cb6250d2887EF'; //BAT contract address

var web3Socket = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

function tokenEventListener = (address) => {
        let token = new web3Socket.eth.Contract(abi, address);

        console.log(address);
        let subscription = token.events.Transfer({
            fromBlock: 0
        })
            .on('data', (event) => {
                 // do something
             })
            .on('error', console.error);
}

tokenEventListener(contract);

I get an error when I run the code -
 Error: CONNECTION ERROR: Couldn't connect to node on WS


texts: Call method with bytes argument from Truffle

texts:
When calling a Smart Contract method that requires a bytes parameter, truffle is not accepting the bytes parameter, no matter how I express it. All these tests fail on truffle:

// 0x6154696d657374616d704576656e744369706865726564 is hex for string 'aTimestampEventCiphered'
let bytecode = myMethod(..., 0x6154696d657374616d704576656e744369706865726564).encodeABI();
let bytecode = myMethod(..., web3.fromUtf8("aTimestampEventCiphered")).encodeABI();
let bytecode = myMethod(..., "aTimestampEventCiphered").encodeABI();
let bytecode = myMethod(..., "0x6154696d657374616d704576656e744369706865726564").encodeABI();
let bytecode = myMethod(..., bytes("aTimestampEventCiphered")).encodeABI();
let bytecode = myMethod(..., web3.fromAscii("aTimestampEventCiphered")).encodeABI();

Truffle is throwing this error on and on:

Error: invalid bytes value (arg="_timestampEventCiphered", coderType="bytes", value=9.322336429922961e+54)

Any idea how to properly send a bytes argument from truffle? Thx!


texts: What is the sequence of events when a transaction is made on Uniswap?

texts: I elect to swap 100 UNI for 700 USDC on UniSwap, but with a low gas fee. In 1 hour, the price of 1 UNI has dropped significantly. would the pending transaction still swap for 700 USDC (as long as there is sufficient liquidity, in which case I guess it would be cancelled), or would the price not have been 'locked in' at the point the swapper confirmed the swap in Metamask?


texts:
How can I get the creator's address of a contract? I'm using truffle, so usually I do

let instance = await VM.instance()

and then get the contract's address via

instance.address

Then, how can I get the creator?
(Setting the owner via a constructor as in an Ownable contract is not an option)


texts: How to change the consensus algorithm in ethereum from PoW to PBFT?

texts:
https://github.com/ethereum/wiki/wiki/Consortium-Chain-Development

I would like to use PBFT as the consensus mechanism in my locally deployed ethereum network.

as the document specified above, we can use PoA, PBFT, DPoS consensus algorithm in private or consortium ethereum blockchain. Anybody have any clue about how to implement it?

Any suggestions would be appreciated.


texts:
I have a contract called bridgeStacked that uses a library called BytesLib.
When I have both loaded into Remix, I compile and deploy bridgeStacked from in Remix.
First, I notice that in the log it says

creation of library browser/bridgeStacked.sol:BytesLib pending...

So I don't kno why it includes BytesLib in that.
Then nothing shows up under the deployed tab - I have to manually get the tx hash from the log and look at a Ropsten block explorer to get the address of the contract that was created, then load that into the At Address field which correctly loads the right functions in the Deployed Contracts section.
Then why I try and call a simple test function:

function test(uint256 _val) public view returns (uint256) {
        return _val;
    }

It returns 0 when I enter 2. If I remove view and make it a write tx, the tx just fails even though it's mined. Similarly fails when called from web3.py.

What's going on here? I think the issue is that the wrong contract is being deployed, but why? :<


texts: Cant create account on second node in private chain

texts:
I have problem with connection of two nodes in private network.
First i am set private nodes on different PCs, and create accounts\mine on it apart. And all been ok.

Next time, i am deleted all database, then create custom genesis file, and initalize this file on both nodes. Then, i am run and connect nodes with addPeer command.
Nodes successfully connecting. On first of them, i am creating accounts and mine, second node start to receiving blocks.

But then, i try to create account on second node, it returns hex addres, but accountsList returns undefined.


texts: Read the timestamp of the transaction via JSON RPC?

texts: How do I retrieve the timestamp of a mined transaction using the JSON RPC?


texts: Is there a way to halt a transaction from being confirmed until an event occurs?

texts:
For example, user 1 sends a transaction to user 2, but that transaction is not able to be confirmed until an event occurs, allowing the transaction to be confirmed and thus sent into user 2's wallet.

This would eliminate any 3rd party in the middle from the situation, making it somewhat more secure. It seems like smart contracts would be able to do this, but I am just wondering if this is possible with blockchain in general?

A good example is the bitcoin website called Purse.io. The buyer sends the bitcoin, and until the item is delivered and the buyer acknowledges that it has been, the bitcoin sits in the "escrow" and is then immediately delivered to the 2nd user's account when it has been delivered. I am asking if there is a way to do this, eliminating the 3rd party, or in Purse.io's case the "escrow".


texts: Truffle v3.2.5 migration error: contract code couldn't be stored

texts:
I'm using Truffle 3.2.5 and Parity to try and migrate a project to Ropsten. I've tried changing the gas amount per the error's advice. I'm running a full Parity node on the same machine, so my truffle settings are localhost, 8545, network ID 3. All of my contracts compile, and I'm able to successfully run the exact same migration on testrpc. On Ropsten, I authorize the transaction in the Parity UI, Truffle successfully migrates 1_initial_migration.js, and then I get the following:

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

at Object.callback (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/web3/lib/web3/contract.js:147:46)
at /home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/web3/lib/web3/method.js:142:25
at /home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/web3/lib/web3/requestmanager.js:89:9
at XMLHttpRequest.request.onreadystatechange (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:118:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/user/.nvm/versions/node/v7.10.0/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)

Thanks for any help

Here's my truffle.js

module.exports = {
  migrations_directory: "./migrations",
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" // Match any network id
    },
    live: {
      host: "localhost",
      port: 8545,
      network_id: 3,
    }
  }
};


texts: How can you create a contract within a contract and pass the value / payable amount?

texts:
I want to create another contract in a contract function call and pass the associated ether into that new contract.  Seems like it makes sense to want to do but...

Why doesn't this work?

contract B {
    uint x;
    function B(uint a) payable {
        x = a;
    }
}

contract A {
    function createAndPassAmount(uint arg, uint amount) payable {
        B newD = new B.value(amount)(arg);
    }
}


texts: Is there any advantage or disadvantage of using javascript over solidity when building dapps on etherum?

texts: I am aware that there are libraries that let you build dapps on ethereum. What are the pros and cons of using javascript over solidity for dapps. I know this might sound like a partly subjective question but sometime that is what you need to give you perspective.


texts: How to generates the private and public key from a given name or address?

texts: I want to generate both keys for transaction and also let me know how to calculate the processing time using solidity for the whole program?


texts: I need help importing wallet contract into mist after my old laptop got wet and had to get new one

texts: Could someone please help me as I am lost here.  I am holding some ether in mist.  I have the ether in a wallet contract for storage as I read this is more secure than a normal wallet.  I came home from work one day last week and I had left my laptop on my coffee table.  My 3 year old decided he wanted to wash the table and my laptop got wet.  It wont turn on now.  I have my keystore backed up on usb.  We decided to get a new laptop as my wife required one for work related stuff.  I installed the latest mist on the new laptop and synced the chain.  I went into mist, account, backup, and dragged my account keystore from usb into mist.  The problem is that the wallet showed up but the wallet contract associated with that wallet did not.  When I created the wallet contract and backed up my keystore originally I noticed that there was not a keystore file associated with the wallet contract itself.  I had inquired if this was ok and was told that the wallet contract associated with the wallet account would be saved along with the wallet in the same keystore file.  Is this not correct?  Did I do something wrong here?  It is a significant amount of ether and would like to explore any options I have to reclaim it. Thanks in advance for any help


texts: Is Kraken hiding the real cost of deposit?

texts:
A part of my current strategy is to mine ETH, and to send a part of it from my wallet (MEW) to Kraken for: a) buying BTC b) withdrawing some sweet € to pay the bills.
When I'm using MEW to send ETH to Kraken, I pay for the gas, let's say 0.002ETH right now. So looking at etherscan everything is nice, I send say 0.2ETH and 0.197ETH go through.
When arriving in Kraken, without asking me for gas price, and pretty much hidden if you want my opinion, funds are directly transferred from deposit address to Kraken account with 0.004ETH worth of gas.
Fees practically triple, it's really opaque, and is really misleading for newbies (I integrated those fees in my strategy but BOI).
Do you think this is bad implem, or do they have a really good reason to do that?
PS: I'm aware in this case fees are for miners and not Kraken, but they are unnecessary / could be lessen by a lot. Kraken already owns PVK of deposit addresses, it's not like we can get them out ourselves.


texts: Compiling multiple contract file with web3

texts:
I have a solidity file with:

contract X {
    // ...
    Y y;
    function X() {
       y = new Y();
    }
}

contract Y {
    // ...
}

But when I compile this contract using web3.eth.compile.solidity(code); I only get the ABI for contract Y. How do I get the ABI for each contract without putting them in seperate files?


texts: Generated wallet addresses do not seem random in MyEtherWallet

texts:
I have generated a couple (well, dozens) of accounts with MyEtherWallet (currently v3.5.6), and strangely every single one of them starts with "0xff...".

I remember doing the same experiment in an older version and getting completely (well, seemingly more) random addresses. But now the first two digits are always F. I tried changing the password too. Did something change in the algorithm? Is this a bug?


texts: What is the meaning of ODR in go-ethereum?

texts:
Inside the go-ethereum codebase there are many references to ODR, but I cannot see any definition of what it is.
References to ODR appear in the following files among others.
https://github.com/ethereum/go-ethereum/blob/master/les/odr.go
https://github.com/ethereum/go-ethereum/blob/master/light/odr.go


texts: Trouble getting started with Ethereum Blockchain

texts: I'm trying to get started with Ethereum. So I tried the Ethereum wallet, but it took way too long, and after it finished I couldn't even mine on the test network. So instead, I tried to use GETH, and when I did geth --testnet --fast --cache=1024, it again takes a long time, and the testnet is now at processed=4629136. Is this too many blocks? Is the testnet really this large? I'm trying to get started with this but it's very confusing and there is basically no documentation for troubleshooting.


texts: Parity schedule on block number n-1 or n-2?

texts:
I'm trying to get in on some ICO's, and was wondering what the best way to get in was using Parity. I've read some people say that you should use n-2 so the block number the ICO starts at minus two blocks to ensure you get in right at the block start.

But I've also read this doesn't work anymore. I've read to put n-1, 1 block less as well. Can someone who has knowledge in this tell me what the best block to send at is to ensure I'm one of the first one's at the starting block?

Thank you.


texts: How do I transfer funds from an exchange to a wallet I control?

texts:
This Q&A was spawned by the fact there's no one good place with this information. All answers will be wikis. A few of us are going to be collaborating on this effort. Please keep one answer per exchange. Feel free to add whatever you can.

The answers are solely going to cover transferring from an exchange to a wallet you already have. If you need help generating a wallet, see (todo: insert links here).

Thank you.

Poloniex
Kraken
Gatecoin
???


texts: Setting the address for a contract - within another contract

texts:
so I'm working with two contracts in one remix file and I'm slightly confused.

I know this works (I've seen it used before)

NonFungibleToken public nft;
  function setNFTAddress(address addr) onlyOwner{
        nft = NonFungibleToken(addr);
    }

But can someone explain to me the syntax behind using

nft = NonFungibleToken(addr);

specifically the

NonFungibleToken(addr);

part. Why does passing in the address to NonfungibleToken work? Wouldn't this just call the default function in NonFungibleToken? Another way to phrase this is: Why are there "()" after nonfungibletoken?

Maybe I'm confused on what

NonFungibleToken public nft;

is actually doing.


texts: Incompatibility issue of solidity 0.5.12 (or perhaps ^0.5) with web3 js v1.2.2 or with Geth v1.9?

texts:
Is there any incompatibility issue of solidity 0.5.12 (or perhaps ^0.5) with web3 js v1.2.2 or with Geth v1.9?
Because a contract in v0.4.24 works perfectly with given web3 version and Geth version, while the same contract in v0.5.12 (with syntax changes wherever required) keeps giving Error: Returned values aren't valid, did it run Out of Gas?


texts: Trying to pass 1 struct values from 1 contract to other struct in 2nd contract

texts:
contract old{
    struct Student{
        bytes32 name;
        uint age;
    }
    uint public sno = 0;
    mapping (uint => Student) pupil;
    function input(bytes32 n, uint a){
        <Student updated>
    }
    function output() constant returns(bytes32[], uint[], uint){
        bytes32[] memory n = new bytes32[](sno);
        uint[] memory a = new uint[](sno);
        for(uint i=0; i<sno; i++){
            Student s = pupil[i+1];
            n[i] = s.name;
            a[i] = s.age;
        }
        return(n,a,sno);
    }
}

contract receiver{
    old o;
    struct Student1{
        bytes32 name1;
        uint age1;
    }
    uint public sno1 = 0;
    mapping (uint => Student) pupil;
    function set(){
      ........
    }
}

Want to copy struct in contract old to struct in contract receiver.
I know struct can not be acceseed directly in another contract but want to do it through array.


texts:
i have a particular problem with a smart contract: I have made some in a wrong way in the Ethereum Sandbox and now i want to delete them...but when i search the id of the contract to delete with "CustomContracts.find().fetch()" i couldn't find the id...

The only information i become is this:

CustomContracts.find().fetch()
[Object]0: Objectlength: 1__proto__: Array(0)

Can anyone help me please?


texts:
I would like to call a function which returns a boolean. How would I go about calling this function and storing the true or false in a variable? I have tried this var result = contract.checkCertHash(certid,hashedData,address); and initialised the contract using : var parsed= JSON.parse(fs.readFileSync(jsonFile));
const abi = parsed.abi;
 const contract =  new web3.eth.Contract(abi, '0xce395e1f6532e128f35469bb304ca46660a9f376');

I tried searching over here but I have tried what I found but none worked. Thanks in advance!


texts:
I'm using react and javascript. For whatever reason, I've tried a few methods and it doesn't seem to be opening metamask.

await window.ethereum.enable();

and

window.web3 = new Web3(web3.currentProvider);

But in the second instance it has no clue what web3 is.


texts: UniswapV2 addLiquidity revert ds-math-sub-underflow

texts:
I'm trying to use Uniswapv2Router with Truffle and Ganache, but haven't been able to identify what I'm doing wrong. I'm using addLiquidty method as follows:
await uniswapV2Router02.addLiquidity(token0.address, token1.address, 500, 250, 250 , 125, accounts[0], 1618158769);Which throws error  Error: Returned error: VM Exception while processing transaction: revert ds-math-sub-underflow -- Reason given: ds-math-sub-underflow.
But If I comment out .minto(to) The code executes properly until there.
    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
        IUniswapV2Pair(pair);//.mint(to);
    }

This happens even if I have a simple mint implementation just for testing what is going on.
  function mint(address to) external lock returns (uint liquidity) {
        liquidity = 3;
    }


texts:
The below contract deploys fine but the method cannot be executed. I just want to assign a long member number to each member like 12345 and maybe look through the array with that ID. Is this possible?

contract MembersMODDED {

    mapping (address => uint) public memberId;
    Member[] public members;

    struct Member {
        string Name;
        string SurName;
        address MemberAccountNo;
        bool IsActive;
        int AccountType;
        uint MemberNo;
        uint memberSince;
    }

    function Members( ) {

    }

    function changeMembership(address memberAccountNo, bool isActive, string name, string surName,int accountType,uint memberNo) {
        uint id;
        if (memberId[memberAccountNo] == 0) {
            memberId[memberAccountNo] = memberNo;
            id = memberNo;
            members[id] = Member({MemberAccountNo: memberAccountNo, IsActive: isActive, memberSince: now, Name: name, SurName: surName, AccountType: accountType, MemberNo: memberNo});
        } else {
            id = memberId[memberAccountNo];
            Member m = members[id];
            m.IsActive = isActive;
            m.Name = name;
           m.SurName = surName;
        }
    }
}


texts: If Ethereum's contracts are based on "If this than that" is there an "else" that works on the same level? -newbie question

texts:
I just got to start learning the smart contracts, and I have a beginner question.

Before coding, I am doing a top-down research. I read a lot about the if-this-than-that. However, I do not hear about the "else", that is, if the conditions are not met, is it possible to execute?  For example, if some person A does not send me the right amount of money, execute the contract, otherwise, do not. Can this be done ?  How about, if A does not send me the right amount money, execute some other contract that would correct an error (either subtract the money from my account or from their account, and file a report to management (lets say) )? Furthermore, can the contract be time-based? For example, if A does not send me the money on Monday, execute the contract and file a report to management.


texts: Disable nasty pseudo-error message in solium

texts:
Solium treats now require without error message as error that obviously incorrect. I have a lot of require inside my contract and do not want  to garbage it with disabling comments. In the same time I cannot find how to disable message error-reason: Provide an error message for require(). completely through .soliumrc.

I added this line to my project's solium config without any results:

"error-reason": {"enabled": false}


texts: Creating a new contract specifying a sender and value with factory pattern

texts:
I am using a factory pattern to deploy its children contracts here.

The child contract has a constructor as followed:

  constructor (
    string memory _potName,
    uint _duration,
    uint _minStake,
    PotType _potType
  )
  public payable {
    require(msg.value >= _minStake);
    ...
  }

The factory contract create the child contract as:

  function createLotteryPot(
    string memory potName, uint duration, uint minStake,
    LotteryPot.PotType potType
  ) public payable returns(LotteryPot) {
    LotteryPot newContract = new LotteryPot({ _potName: potName,
      _duration: duration, _minStake: minStake, _potType: potType });
    ...
  }

My questions are:

In the factory contract, how can I pass the msg.value to the children contract? This is a requirement that during child contract creation, the owner also need to commit some ethereum.
How can I pass the msg.sender to the children contract to specify it is the owner instead of the contract? I understand I can pass in an additional parameter msg.sender. Just wonder is there a cleaner way to do it?

Thanks a lot for input.


texts: How does chainlink solve the oracle problem?

texts: I've heard a lot about Chainlink recently -- how Synthetix, Aave and other top Defipulse projects are using them. How exactly does Chainlink solve the oracle problem from a technical perspective?


texts: What should I do about losing my private key to a phishing scam?

texts:
I have a MEW address associated with a private key that was Phished and funds depleted, (my fault...) I also have MEW address created with a Trezor, are my ETH and Tokens in my Trezor wallet safe?
I know not to use my address with the compromised private key anymore, but are my MEW accounts linked in any other way I should be concerned about?
e.g. is the private key I was given only associated with the one address?

Discussion of best practices would be appreciated.
Any suggestions about what to do with the phished account?

Best.


texts: Any option to get larger amount (i.e. 2000) of Rinkeby Ether?

texts:
We are planning to open our product to the public for live testing. We want to support both Ropsten and Rinkeby networks, just in case.

When registering, each user should get around 10 ether on their account so that they can freely play around with the product. The product is an abstraction layer over a blockchain implementation, so we do not want users to have to deal with faucets in order to get it. Because of that, we would like to fill our main account with enough ether so that we can redistribute them to the users when necessary.

For Ropsten, that is easy because we can automate withdrawal from the faucet.

For Rinkeby that approach is not possible, because of the social network account limitation.

Do you know of any other way to get a one-time injection of larger amount of Rinkeby ether?


texts:
I was reading this post: https://medium.com/@alexberegszaszi/lets-bring-the-70s-to-ethereum-48daa16a4b51 and i'm a bit unclear about some of the details. I was hoping someone can shed some more light on this!

He lists 3 use cases for being able to verify RSA signatures which i'm not entirely clear on how that would actually work (bear with me).

Using an RSA key to sign transaction with a contract. This includes your encryption device as well government ID cards.

I'm not sure what is actually meant here. Would I sign a transaction or document using my RSA key and then create a regular ethereum transaction as the payload allowing the contract to identify my RSA real world identity with my ethereum digital identity? Or do I actually sign an ethereum transaction with my RSA key, send it to a contract and have it verify my signature? That's not possible right? And it would also need some lookup table to match the identities.

Verifying certificate structures in smart contracts

Is this suggesting that you could build some PKI infrastructure managed by a smart contract?

Using government ID cards to prove individuality

I'm guessing this works because they can verify that a signed transaction validates against my public RSA key, but that doesn't link it to my ethereum (or uPort) account yet.

Pls hlp.


texts: Is there any api for creating the wallet and transfer the ETH coin to wallet to wallet?

texts: Please suggest me? Which api should be the better option and is ethereum does not provide any api ? or we only need to access third party api?


texts: solidity cant deposit 1.1 (float ether value)

texts:
hi this is my contract

pragma solidity ^0.4.2;

contract TrusteeFinTestToken {
    /* Public variables of the token */
    string public standard = 'Token 0.1';
    string public name;
    string public symbol;
    uint8 public decimals;
    uint256 ethtstraito = 100;
    uint256 public totalSupply;

    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    /* This generates a public event on the blockchain that will notify clients */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function TrusteeFinTestToken(
        uint256 initialSupply,
        string tokenName,
        uint8 decimalUnits,
        string tokenSymbol
        ) {

        initialSupply = 10000000000 ;
        tokenName ="TrustiFintraTest";
        tokenSymbol="TFINT";
        decimalUnits = 4;
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
        totalSupply = initialSupply;                        // Update total supply
        name = tokenName;                                   // Set the name for display purposes
        symbol = tokenSymbol;                               // Set the symbol for display purposes
        decimals = decimalUnits;                            // Amount of decimals for display purposes
        transferFromUser(this,initialSupply);

        }

    function setETHTokenTokenRaito(uint256 newRaito){
        ethtstraito = newRaito;
    }

    function() public payable{

        transferFromContract(msg.sender,msg.value/1000000000000000000*ethtstraito*10000);
    }

    function contractETHbalance() constant returns(uint256) {
        return this.balance;
        }

    /* Send coins */
    function transferFromUser(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
        Transfer(msg.sender, _to, _value);                   // Notify anyone listening that this transfer took place
    }
        function transferFromContract(address _to, uint256 _value) {
        if (balanceOf[this] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[this] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
        Transfer(this, _to, _value);                   // Notify anyone listening that this transfer took place
    }
}

when i send deposit 1 eth to fallback
its return me 100 Tokens
but when i deposit 1.1 ehter or other float value
contract doesn't work
and show no errors
what is the problem


texts: How to persist contract data from Truffle transactions

texts:
After running Truffle tests, the blockchain reverts to a clean room environment and all the data is lost.

How can you do transactions from Truffle and persist the data in your contract?
In my case I want to use that data in a web3 frontend.

From the frontend, the transactions are saved, but it is tedious as you must approve the MetaMask confirmation each time, and creating hundreds of transactions would be a pain, whereas in Truffle you can just loop and not worry about the confirmation messages.


texts: Is it possible to get all entries of a Mapping or Array?

texts:
For debugging a smart contract, it would be helpful to see all entries of an Array or Mapping object in the smart contract.

When using Truffle, I can see individual elements of a public array with valid index i by running mycontract.myarray(i) but running mycontract.myarray() yields a BigNumber Error.

This question indicated that getting the full readout is not straightforward because the getter functions for mappings and arrays expect index keys. However, has anyone found a way to do this in geth or Truffle?


texts: How do I let other people use my contract?

texts:
Using Remix, I created the Hello contract from the docs and successfully published it in the Kovan testnet (using the MetaMask plugin).

Also, from Remix "Contracts" tab, I successfully sent "setGreeting" and "greet" messages to my contract, by clicking a button.

Now, I want to let a friend use the same contract using the same convenient GUI of Remix. To see how it works, I opened Remix in an incognito window.
I went to the "Contracts" tab.

EDIT: I clicked the button named "At Address" and entered the address of my contract, but got this error:

Apparently, Remix opens with the default contract ("ballot") and tries to find the "winningProposal" of my contract. But, my contract does not have this field since it is a different contract ("Hello")!

Does it mean that I have to send my friend the entire source-code of my contract, to put in Remix?

Is there another way to easily let my friend play with my contract?


texts: How to take coins from a msg.sender? Or verify coins were sent?

texts:
I'm writing a contract in solidity (for practice) that is a guessing game that is played as such:
1) Users are given 100 MetaCoin (dummy currency) on sign up.
2) Users can pay 1 coin to play a guessing game, if they guess correctly they're given 5 coins, if not, they lose the coin.

However, I'm unsure on how to best implement this. Here's a pseudo implementation:

function takeGuess(int guess) returns (bool){
    uint balance = getBalance(msg.sender);
    if (balance>0){
        int actual = popNumber(); //Retrieves next "random" number
        if (guess == actual){
            coin.sendCoin(msg.sender, 4);
            return true;
        } else {
            coin.sendCoin(this, 1, {from: msg.sender}); //Not legal syntax
            return false;
        }
    } else {
        return false;
    }
    return false;
}

Now, this doesn't work because the third argument in the else statement is not a valid argument (it's JS abi notation), but it's a representation of what I want to do. Is there a way to take coins from users in-contract like this? Or does the user need to send coins, and then wait for the verification? How would I do that?

Here is the repo if you want to see the full source code:
https://github.com/willikers19/GuessTheEth

Edit: This contract is mostly just for practice. It's not intended to have "good" random behavior.


texts:
Working on some smart contract security cases to become more comfortable with it but am running into an issue.

In order to solve this particular puzzle, I need to initiate a fallback function from a contract that is non-payable and send some data along with it. In the case of a payable fallback function I'd just send over some wei together with the msg.data and that should work. But what if a fallback function is nonpayable? I can't select it as a function to send to in web3's sendTransaction right, because I do not have a method name for it.

How would you go about initiating that function while sending data along?

Cheers


texts: Risk of using BlockHash, other miners preventing attack.

texts:
When I read about the risk of using the blockhash as a random number it was explained to me the issue was that a miner can trow away the block if the block-hash is not in his advantage, and keeps mining till he finds one that is.

However if a miner trows away a block, to keep mining for a more favorable block, he would only have till the next person finds a block right?

So this would only be a issue if all miners are trowing out all the blocks till they get a favorable block, otherwise a other miner will mine a block in about 20 sec.

Even when the attacker would spin up 10.000 GPU instances at for example amazon, he would only have about 20 sec for him to find a favorabel solution before a other miner finds a solution?


texts: Smart contract ability to query a database

texts:
I'm having some concerns while developing smart contract. As I see that, Ethereum blockchain can be known as a distributed database, where transactions are stored as hashes in a block. A smart contract is the back-end of the DApp. In my scenario, I store data "this is my input" in a block by sending a transaction from accountA to accountB. As I see(Or I missed something)there is no option for me to get that data from the smart contract. Is it because the code for that function not supported by the solidity language, or it is the issue from the EVM, that has no opcodes to retrieve and decode the transaction. I read multiple documents but no one mentioned about how smart contract can get data that is not stored in its own storage.
Regards,


texts: Question about Crowdsale contract token cost

texts:
I have a quick question. What line of code do i need to add or remove here

function Crowdsale(
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        token addressOfTokenUsedAsReward
    ) {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken * 1 ether;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

To make the Ether cost of each token where 1 ether gives you 2,500 token?


texts: Why is the first item of an int array type casted to an int?

texts:
I was reading a book on solidity, the array was defined as
int[5] age= [int(10),20,30,40,50]

When data type int was declared at the start then why it is declared again in the array with 10?


texts: How to use web3 in a mobile context (ionic)?

texts:
Hello I am building an ionic app that send transaction to ethereum smart contract.
in web I used metmask but what is the alternative for mobile?
is possible to run an ethereum client in a mobile?


texts: What is the actual gasPrice used in a Truffle + Ganache environment?

texts: It doesn't seem to match the Ganache UI, nor web3 gas price.


texts: Is an Ethereum address with no outgoing transactions initialized if someone sends funds into it?

texts:
If there exists an address that nobody (yet) owns the private key to, and somebody sends funds into it, does that private key get initialized to nobody, and no one will ever be able to access it?

I am asking for something like REXmls, who sent their ICO funds to an address that doesn't exist. Will somebody, some day generate a wallet with that public key?


texts: Solidity Browser - Issue with every example => Error: Type "address" not supported for state variable

texts:
I am very new to blockchain and Ethereum. I want to get started with a BaaS cloud service and develop / execute some smart contracts. I successfully set up the Azure Ethereum template (https://github.com/Azure/azure-quickstart-templates/tree/master/ethereum-consortium-blockchain-network) and want to use Solidity Browser to create a first contract. As done in the corresponding example, I use MetaMask in Chrome to confirm transactions.

My issue: I tried several Solidity smart contract examples in Solidity browser. All show one specific error:

Error: Type "address" not supported for state variable

I think this is the reason why nothing happens besides "waiting to be mined" in Solidity Browser. Actually, MetaMask should popup to confirm the transaction as in the tutorial, but nothing is happening in MetaMask.
First, I thought it is an issue with my blockchain cluster or the template (therefore, I also posted this issue here: https://github.com/Azure/azure-quickstart-templates/issues/2797), but after some more playing around, I think the issue is not related to Azure, but just to Solidity and Solidity Browser.

I also tried out different compiler versions (e.g. the most recent one and the one with the same version as the smart contract), but always the same error message. Note that all smart contracts do NOT show compile errors in the editor itself. This error is shown in the "formal verification" tab.

As I said, it happens with any example - that is what I find so strange... Let's take this one from https://www.ethereum.org/greeter:

contract mortal {
/* Define variable owner of the type address*/
address owner;

/* this function is executed at initialization and sets the owner of the contract */
function mortal() { owner = msg.sender; }

/* Function to recover the funds on the contract */
function kill() { if (msg.sender == owner) selfdestruct(owner); }
}

contract greeter is mortal {
/* define variable greeting of the type string */
string greeting;

/* this runs when the contract is executed */
function greeter(string _greeting) public {
    greeting = _greeting;
}

/* main function */
function greet() constant returns (string) {
    return greeting;
}
}

Can someone please help me? What am I missing?

Thank you.


texts: How to execute a transaction within a contract given to address, and calldata?

texts:
Let's say I've got a contract called MyContract. My contract has a function which receives calldata and an address for another contract, called OtherContract
I want to be able to take the calldata and address in MyContract, and execute the callData in OtherContract from MyContract.
I don't know anything about the OtherContract, or the function that uses the calldata.
Is this possible?
Thanks for your time!!!


texts:
Self-destributing token contract template

Hello,

Are there any complete templates or resources for making a token which distributes itself when funds are sent to the contract?

I. e. user sends 0.01 ETH to contract, which in turn sends X tokens back to user.

I would prefer blockchain based solutions but if none are available then maybe a server based solution.

Vesa


texts: unable to deploying Truffle Contracts to Rinkeby!

texts:
I am stuck with an issue as unable to deploying Truffle Contracts to Rinkeby network!
As shown here it's using network 'development'? why? I want Rinkeby!

ASMAHANs-MacBook-Pro:project-6 asmahan$ truffle compile
ASMAHANs-MacBook-Pro:project-6 asmahan$ truffle migrate network rinkeby
Using network 'development'.

Network up to date.

I made sure I installed both of the web3, truffle, infura and MetaMask.
here is truffle.js file

const HDWalletProvider = require("truffle-hdwallet-provider");
module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },
    rinkeby: {
      provider: function () {
        return new HDWalletProvider("mus***********tuff sustain",
          "rinkeby.infura.io/v3/********")
      },
      network_id: '4',
      gas: 4500000,
      gasPrice: 10000000000,
    }
  }
};


texts:
The WETH10 project offers a flash minting feature.

This contract allows to flashMint an arbitrary amount of Wrapped Ether, unbacked by real Ether, with the condition that it is burned before the end of the transaction.

Is there an example of how this feature can be used?


texts: Does increasing the size of array guarantees that new elements are initialized to default value?

texts:
I get an error when trying to initialize array inside a struct of an array and I find this post: https://github.com/ethereum/solidity/issues/4115 .

It seems that I have to work around by increasing the size of the outer array by 1 and fill the value by hand. But does it guarantees that the newly appeared elements are initialized properly to the default value of their types? And, without explicit memory reservation which is often required in other similar languages, will the array overlap with other data?


texts: how do you sign transactions programatically?

texts:
imagine there's a dapp you're building and on your website users type the receiver address, the value and what you do is send from that user's address to the receiver's address the value ether.

My questions are:

a) do you make users type their private key in an input field so that you can sign the transaction?

b) if you let them type the private key in an input field, then it's no safe right? how is the user sure you're not gonna save his private key somewhere?

c) if you don't ask him the private key, how are you going to sign the transaction programatically?

d) if you're using the metamask, it's easy, but let's say we don't use metamask. what are the options?


texts: A new block sealed in 6 hour on average in my POA private chain using AWS EC2. Why?How do I increase the frequency?

texts:
As title：
My AWS EC2 spec. is ： 1 vCPUs, 2.5 GHz, -, 1 GB memory, 30GB SSD ,a free testing VM.
My init command is:
geth --datadir "." --networkid 15  init "./CustomGenesis.json"
and then,using following command：
geth --datadir "." --nousb --http --http.port 8545 --port "30303" --http.api "db,eth,net,web3,personal" --syncmode "full" --unlock 0b9331e020335d4cab5e00cea9de3xxxxxxxxxx --password "./password.txt" --mine --allow-insecure-unlock  --networkid 15  console
When I enter the geth console，I use miner.start(1) to mine.
The console shows these message repeatly:
INFO [10-29|19:11:05.775] Writing clean trie cache to disk         path=/home/ubuntu/chain/geth/triecache threads=1

INFO [10-29|19:11:10.450] Regenerated local transaction journal    transactions=5  accounts=1

INFO [10-29|19:11:10.765] Persisted the clean trie cache           path=/home/ubuntu/chain/geth/triecache elapsed=1.970s

After about 6 hoers,a new block seased.
My genesis.json is belowed:
{
"config": {
"chainId": 15,
"homesteadBlock": 1,
"eip150Block": 0,
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"eip155Block": 0,
"eip158Block": 0,
      "byzantiumBlock": 4,
      "constantinopleBlock": 5,
      "petersburgBlock": 0,
      "istanbulBlock": 0,
      "clique": {
        "period": 15,
        "epoch": 30000
      }
},
    "nonce": "0x0",
    "timestamp": "0x5f9bcb9c",
    "extraData": "0x00000000000000000000000000000000000000000000000000000000000000000ad712c9171102d7eaf86d29589944411e3a70450b9331e020335d4cab5e00cea9de36b9c514e3a40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x8000000",
"difficulty": "0x1",
"alloc": {
      "0b9331e020335d4cab5e00cea9de36xxxxxxxxxx": {
        "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
      }
    },
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}


texts: What is "data" param of rawTx? How to send ETH by using web3

texts:
I want to send eth by using web3 on testnet. Source address is 0xbddf0bf3ac858d7fb8a2bdda55884d61779ba5a9. The destination is 0x8005ceb675d2ff8c989cc95354438b9fab568681.

I found the example on web3 reference page. I can imagine how to use it. However I don't know what is "data" and how to calculate the gasLimit.

var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('xxx', 'hex')

var GAS = web3.eth.estimateGas({
    to: "0x8005ceb675d2ff8c989cc95354438b9fab568681",
    data: "WHAT IS DATA"
});

var rawTx = {
  nonce: '0x00',
  gasPrice: GAS,
  gasLimit: 'HOW AMOUNT OF GAS SHOULD I SET',
  to: '0x8005ceb675d2ff8c989cc95354438b9fab568681',
  value: '0x01',
  data: 'WHAT IS DATA'
}

var tx = new Tx(rawTx);
tx.sign(privateKey);

var serializedTx = tx.serialize();
web3.eth.sendRawTransaction(serializedTx.toString('hex'), function(err, hash) {
  if (!err)
    console.log(hash);
});

https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsendrawtransaction

Update 1

Seems data is optional value or something...

  data - all of the interesting stuff goes here

What is the ethereum transaction data structure?

In Bitcoin, transaction fee is calculated by the size of transaction. Thus, I thought "data" is related to fee...


texts: Can't get event data selecting the event by name

texts:
This is my contract

pragma solidity ^'0.5.2';

contract MyContract {
    event ContractCreated(address newAddress);

    constructor() public { }

    function createOtherContract() public {
        address contractAddress = address(contract);
        emit ContractCreated(contractAddress);
    }
}

if I watch the events using this code

MyContract.methods
    .createOtherContract()
    .send({from: accounts[0]})
    .on('transactionHash', function (hash) {

        MyContract.events.allEvents({
                fromBlock: 4477390,
                toBlock: 'latest'
            }, (error, events) => {
                if (error) { console.log("ERR", error); }
                console.log("Events", JSON.stringify(events));
            });

            MyContract.once('ContractCreated', {
                fromBlock: 4477390,
                toBlock: 'latest'
            }, (error, event) => {
                if (error) { console.log("ERR", error); }
                console.log("My Event", JSON.stringify(event));
            });

        })
        .on('confirmation', function (confirmationNumber) {
            console.log("confirmation number", confirmationNumber);
        })
        .on('receipt', function (receipt) {
            console.log("RECEIPT", receipt);
            MyContract.getPastEvents('ContractCreated', {
                fromBlock: 0,
                toBlock: 'latest'
            }, (error, events) => { console.log("Events", events); })
            .then((events) => {
                console.log("Events", events)
            });

        });

That's my console log print:


texts: Deploying new contract in transaction MIX IDE

texts:
I'm running into an issue whenever i try to create a new transaction with my newly created contract "richoCoin". It seems like its expecting the "Sample.sample()" contract.

How do I resolve this?


texts: broadcasting signed transaction from multiple endpoints

texts:
I want my transaction to broadcast fast to network.
Will it help if I broadcast it from multiple publick APIs?
etherscan.io/pushTX
+
MyEtherWalet

Will it help transaction to be included in nearest possible block?


texts:
Is there any security issue when making for-loops inside getter functions ?
Let's say the array is very large, and it takes a long time to loop through the array. Is it a potential threat or I can ignore this as long as the function is passed as view or pure ?
Moreover in general can I consider all view and pure functions as none dangerous for the smart contract security ?
Best regards


texts: Based on my understanding, Oraclize is a centralized solution. What are some ways to decentralize Oraclize?


texts:
What's the best way to clear a mapping? Consider the following case:

struct user {
    string name;
    uint id;
    bool valid;
    bytes32 hash_id;
}

mapping (address => user) userRegister;

function clearStruct (address addr) constant returns (bool cleared) {
   userRegister[addr].name = null;
   userRegister[addr].id = null;
   userRegister[addr].valid = null;
   userRegister[addr].hash_id = null;
}

I am looking for a generic way to clear structs. the error i see right now at = null:

  Error: Expected primary expression

Anyone who could suggest, it would be greatly helpful. is the only way to make them corresponding nulls i.e. '' for string, 0x000... for bytes32, false for bool, and 0 for int and so on?


texts: Web3 Websocket conflicts with server request

texts:
I am listening to contract events through the following function:
  const subscribeLogEvent = async (contract, eventName) => {
    const eventJsonInterface = web3.utils._.find(
      contract._jsonInterface,
      o => o.name === eventName && o.type === 'event',
    )
    const subscription = web3.eth.subscribe('logs', {
      address: contract.options.address,
      topics: [eventJsonInterface.signature]
    }, async (error, result) => {
      if (!error) {
        const eventObj = web3.eth.abi.decodeLog(
          eventJsonInterface.inputs,
          result.data,
          result.topics.slice(1)
        )
         //   console.log(result)
         const x = await fetchData()
      } else {
          console.log(error)
      }
    })
  }

Once I receive an event, I would like to run a fetchData() function that fetches an object from my server. The problem is that the object that it returns is undefined, whilst if I call the function outside the websocket, it returns the correct value.
How can I solve this issue?
Thanks


texts:
I am load-testing Ethereum using a private network of two nodes. The DApp is a web-service which stores and retrieves data in/from a smart-contract deployed in the private Ethereum. For load-testing I am using JMeter which simulates around 100 users over a period of 1 hour. The protocol flow submits 12 transactions per user, totalling around 1200 transactions. I have noticed this particular behaviour:

Each block contains only one transaction even though there are multiple transactions in the transaction pool. A screenshot is given below:

As you can imagine, the load testing creates a huge backlog of transactions in the transaction pool which takes a considerable amount of time to be included in the block.

I wonder why only one transaction is being included in the block. Is there any way to include more than one transaction in a single block?

I use Geth for interacting with the private blockchain. Its parameters are:

Version: 1.5.4-stable
Git Commit: b70acf3c5bd335d8dedc2a5aa6eff05c4c32105e
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.7.3
OS: linux

Thanks in advance.

Ripul


texts: How to solve max call size stack exceeded when compiling solidity?

texts:
I am using this - https://github.com/ericxtang/browser-solc

The code works when I select a new compiler version but I continually get a stack error when I try and run the same version. Does anyone have any ideas how to solve this?

I have this code -

document.getElementById("compile-output").value = "";
    var result = compiler.compile(getSourceCode(), optimize);
    var stringResult = JSON.stringify(result);
    document.getElementById("compile-output").value = stringResult;

    var bytecode = result.contracts.greeter.bytecode;
    var abi = result.contracts.greeter.interface;

    web3 = new Web3(web3.currentProvider);

    // Our future code here..
     web3.eth.defaultAccount = web3.eth.accounts[0];

Uncaught RangeError: Maximum call stack size exceeded
    at Object.pgb [as dynCall_viiiiii] (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:12)
    at invoke_viiiiii (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:1)
    at Array.hwa (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:13)
    at Object.acb [as dynCall_vi] (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:12)
    at invoke_vi (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:1)
    at Array.pua (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:10)
    at Object.Thb [as dynCall_iii] (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:12)
    at invoke_iii (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:1)
    at Array.nua (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:10)
    at Object.mib [as dynCall_iiiiii] (VM380 soljson-v0.4.25-nightly.2018.8.16+commit.a9e7ae29.js:12)


texts: BigNumber Error: new BigNumber() not a number: [object HTMLInputElement]

texts:
Getting this Big Number error when trying to update my token price.Seems like a Javascript issue with the number size being passed.Anyone know a fix for this?

//Javascript
priceChange:function(){
App.contracts.DappTokenSale.deployed().then(function(instance) {
  let newPrice = document.getElementById('updatePrice');
  newPrice = web3.toWei(newPrice, 'ether');
  instance.setTokenPrice(newPrice);
})

}

 // Solidity
function setTokenPrice(uint256 _newPrice) public{
  tokenPrice = _newPrice;
}


texts:
I'm totally new to Ethereum, and want to create some deposit address monitoring system using web socket. Which gets newly generated blocks and scan it for transactions made into it.
You can find code here:
https://github.com/AlanL1/Ethereum-FrontEnd

But geth is not connected with application. I have already installed geth

Am i missing something?


texts: Is it possible to host a new smartcontract and access it through api?

texts:
Smart contract is already deployed and we can view our own smart contract. Now we want to access its method from API?

var tokenContractABI = {your token contract ABI}
var tokenContractAddress = "{your token contract address}"
var tokenContract = eth.contract(tokenContractABI).at(tokenContractAddress)
tokenContract.testMethod()

like at this link https://github.com/ethereum/wiki/wiki/JSON-RPC, Its mentioned that apis are available for default contract and can be accessed from api (localhost:8545) using {"jsonrpc":"2.0","method":"eth_getCode","params":["0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x2"],"id":1}

If i want to use my smart contract method to be exposed to API, then how can i use them. can i do it like this ? {"jsonrpc":"2.0","method":"tokenContract_testMethod","params":["", "0x2"],"id":1}

PS: My understanding is admin, personal, eth are default contracts deployed when we start blockchain.? Am i correct ? please validate this point also.

Thanks in advance.!


texts: Is ERC20 Token Contracts the Only Way to Create Custom Tokens?

texts:
Is the only way to create your own tokens/cryptocurrency on Ethereum by deploying a Smart Contract following the ERC20 standard?
After deploying the token contract, is the only way to transfer the tokens using this contract?
For example:
If the transfer method in the contract is hard coded to transfer to address "ABC" no matter what you specify the "to" address to be.
Is there a way to transfer the tokens to address "XYZ"?

Many thanks


texts: Can not deploy to Rinkeby via truffle - cannot read property 'bind'

texts:
I am using truffle: "^4.1.14" and ganache-cli version "^6.1.8".
When I try to migrate to ganache cli network, it works without a problem.
But when I try to migrate to Rinkeby, it always fails.
The error message says TypeError: Cannot read property 'bind' of undefined. The problematic line is buried somewhere deep in webpack, and I can't get to that script to inspect it or console.log it.

The relevant part of truffle.js looks like this

rinkeby_infura: {
      provider: function() {
        // using process.env.MNENOMIC would be safer, but this is test project
        const mnemonic = require('./.mnemonic');
        const apiKey = require('./.infura_api_key');
        return new HdWalletProvider(mnemonic, 'https://rinkeby.infura.io/' + apiKey);
      },
      network_id: 4,
      gas: 4612388 // Gas limit used for deploys
    },

The full stack trace of the exception is below. It probably has something to do with connecting to Rinkeby via provider, at least from what I've googled so far. But I am unable to make it work.

$ ./node_modules/.bin/truffle migrate --network rinkeby_infura

C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-provider\wrapper.js:26
    var originalSendAsync = provider.sendAsync.bind(provider);
^
TypeError: Cannot read property 'bind' of undefined
    at Object.wrap (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-provider\wrapper.js:26:1)
    at Object.wrap (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-provider\index.js:7:1)
    at Object.create (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-provider\index.js:21:1)
    at Config.get [as provider] (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-config\index.js:165:1)
    at Object.detect (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-core\lib\environment.js:46:1)
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-core\lib\commands\migrate.js:91:1
    at finished (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-workflow-compile\index.js:53:1)
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-compile\index.js:314:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:158:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:3888:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:473:1
    at replenish (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:1006:1)
    at iterateeCallback (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:995:1)
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:969:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:3885:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:154:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:1140:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:473:1
    at iteratorCallback (C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:1064:1)
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:969:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\~\async\dist\async.js:1137:1
    at C:\src\personal\ens-registrar\node_modules\truffle\build\webpack:\packages\truffle-compile\profiler.js:133:1
    at FSReqWrap.oncomplete (fs.js:155:5)


texts: What is the fastest way to call a function for incoming ICO

texts:
We have Alarm Contract: http://docs.ethereum-alarm-clock.com/en/latest/

We have parity client-side scheduling: Parity - How to schedule a transaction?

We can write custom contracts similar to this contract. Reddit thread

According to my test results, parity client side scheduling is not the best and guaranteed way to be the first one in. Plus, you have to run the node all the time.
So, what would the fastest way to get into ICO based on ERC20?


texts: Can not retrieve Ethereum address form transaction signature on Python

texts:
I'm trying to retrieve the ethereum address from the transaction signature. I have got the following transaction:

{
  blockHash: "0x82388a80a654586ec646115ae63a664e594e0e34dd6fb20dcf078d9495788578",
  blockNumber: 4311,
  from: "0x6825487b18c45c507d06b44ec2ba5b5bf3925f23",
  gas: 4712388,
  gasPrice: 100000000000,
  hash: "0x0fe0a5142f41e516f55017c03c173ea59382f7554a4d3e9efabd12b35734da32",
  input: "0xfdacd5760000000000000000000000000000000000000000000000000000000000000002",
  nonce: 249,
  r: "0x5897c2c7c7412b0a555fb6f053ddb6047c59666bbebc6f5573134e074992d841",
  s: "0x1c71d1c62b74caff8695a186e2a24dd701070ba9946748318135e3ac0950b1d4",
  to: "0xccfaed4390d5e757476f657bf96146570126188d",
  transactionIndex: 0,
  v: "0xa96",
  value: 0
}

Following Ethereum yellow paper I would have to do the following to retrieve the from address 0x6825487b18c45c507d06b44ec2ba5b5bf3925f23:

S(T) ≡ B 96..255(KEC(ECDSARECOVER(h(T), Tw ,Tr ,Ts))))

Where the values in my case is (Python code):

Tw = long("1c",16)
Tr = long("5897c2c7c7412b0a555fb6f053ddb6047c59666bbebc6f5573134e074992d841",16)
Ts = long("1c71d1c62b74caff8695a186e2a24dd701070ba9946748318135e3ac0950b1d4",16)
Thash = long("0fe0a5142f41e516f55017c03c173ea59382f7554a4d3e9efabd12b35734da32",16)

Then:

x,y=ecdsa_raw_recover(bin(Thash), (v, r, s))
k = sha3.keccak_256()
k.update(str(x)+str(y))
k.hexdigest()

But I'm getting 8485031e62b6cf0ea13a32580e00b8ce77d614443f1a14a1f1495cfc48e985a7 instead of 6825487b18c45c507d06b44ec2ba5b5bf3925f23.

Anyone knows what am I doing wrong? I don't know if I'm missing some convertion or something like that.

Thanks in advance.

Best regards,
Albert.


texts: Remix IDE Ethereum is blank page on local host

texts:
After installing Remix IDE, it shows blank page!

I use these command lines to install remix IDE:

sudo apt install build-essential
sudo npm install -g node-gyp
npm install remix-ide -g
remix-ide

Node.js and npm versions:

node -v
v10.21.0
npm -v
6.14.4

there is no error, how to solve this please?

Local host page for Remix IDE:


texts:
Here is my code example:

pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;

contract Operations {

    Operation[] public operations;

    struct Operation {
        uint startOperation;
        uint endOperation;
        string responsible;
        string opType;
    }

    function getAllOperations() public view returns(Operation[] memory){
        return operations;
    }
}

I have 3 questions:

1 - Why do I need pragma experimentals ABI to return an Array of structs?

2 - Why do I have a warning saying I shouldn't use experimental features in live deployments?

3 - Is there any other way of doing this without using an experimental feature?


texts:
I have a voting contract and I am trying to find out the best way to get the winner key. Here is my code.

pragma solidity ^0.4.25;

contract Voting {
  mapping (int => uint8) public votesReceived;
  int[5] candidateList = [int(0),1,2,3,4];
  uint[] votes;

  function totalVotesFor(int candidate) view public returns (uint8) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  function voteForCandidate(int candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate] += 1;
  }

  function validCandidate(int candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        votes.push(votesReceived[candidate]);
        return true;
      }
    }
    return false;
  }
}

votesReceived keeps track of number of votes that each candidate has received but I am unable to figure out a way to get the key with most votes.


texts:
I have four transactions which I would like to include in the same block, T1, T2, T3, T4.

There is a race condition so I do not want to broadcast these transactions unless I can be sure they will settle together and in order. This requires running a miner to make this assurance.

Running geth, how could I add four transactions, in order, to my pool so that they will be included if I mine a block but they will not otherwise be broadcast from my machine?


texts: What are the ways I can contribute to Ethereum?

texts: I'd like to know more about how to contribute, both on a technical and non technical perspective


texts: Best way to delete element of a dynamic array without knowing the index

texts:
I have this mapping

  mapping(bytes32 => address[]) public authorisation;

This maps a hash with a list of authorised users.

I have a function to add, and confirm - these work and its not an issue. But now I need to add a delete funciton, where given a hash and an address, that address is revoked access/permission

function deletePermission(bytes32 hash, address user) public {// get index of element with the address = user, then delete this element from the array.}

I already looked over here but didn't find any solutions where the index isn't known. I know you can loop through the array until you find the element matching the address but that would be very costly( in terms of gas). Is there any more efficient way to do it? Thanks


texts:
I have created a Private Ethereum network and I have deployed a contract in it..

Now I am trying to post a transaction in that contract but I m getting error that transaction has been reverted by EVM without any further details..

What should be the best way to diagnose such cases..

Note : I have tried one using debug.trace but it give me whole dump of ops code level details which i m not sure how to use for diagnose.. Appreciate your valueable inputs

Regards
Dev


texts:
I've gone through with the debugger to make sure msg.sender is my metamask account and that it should be updating.

I'm messing with the 0xBitcoin ERC20 contract.

function myfunction() {
     balances[msg.sender] = balances[msg.sender].add(reward_amount)
     // My contract is 18 decimals but even after converting the amount to "ether"-like
     // units the amount is still 2 digits long. So it's not that the update is too small

     emit Mint(msg.sender, reward_amount, epochCount, challengeNumber
}

Where Mint is defined as

event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);

So in summary my account balance doesn't update and I've checked

1) message.sender value

2) reward_amount is large enough that it should be visible

3) the transaction is going to completion without any errors preventing it

What could be going wrong that I haven't considered?

Here's the entire function. It's basically straight from the 0xBitcoin contract cited above.

function Mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
        bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));

        if (digest != challenge_digest) revert();

        if(uint256(digest) > miningTarget) revert();

        bytes32 solution = solutionForChallenge[challengeNumber];
        solutionForChallenge[challengeNumber] = digest;

        if(solution != 0x0) revert(); // same answer can't be awarded twice

        uint reward_amount = getMiningReward();

        balances[msg.sender] = balances[msg.sender].add(reward_amount);
        tokensMinted = tokensMinted.add(reward_amount);

        lastRewardTo = msg.sender;
        lastRewardAmount = reward_amount;
        lastRewardEthBlockNumber = block.number;

        _startNewMiningEpoch();

        emit Mint(msg.sender, reward_amount, epochCount, challengeNumber);

        return true;
    }


texts: Circular reference error in factory contract pattern

texts:
I've used the factory model before, but I've never encountered a circular reference error, and I'm having trouble seeing how this could be a circular reference when I'm creating a brand new AssetTokenizationContract below.

I'm trying to accept an ERC 721 token and deploy a corresponding ERC 20 token contract with the ERC 721 token underlying. You'll see below, once the 721 token is locked, I'm trying to deploy a new AssetTokenizationContract, which is where I get the following error:

TypeError: Circular reference for contract creation (cannot create instance of derived or same contract).

function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4){
        (address _distributionAddress,
            address _paymentAddress,
            address _taxAddress,
            uint256 _erc20Supply,
            string memory _erc20Name,
            string memory _erc20Symbol,
            uint _erc20Decimals,
            uint _minimumShares,
            bytes memory _deploymentData) = abi.decode(_data, (
                address,
                address,
                address,
                uint256,
                string,
                string,
                uint,
                uint,
                bytes));
        require(lock721Token(_operator, _distributionAddress, _paymentAddress, _taxAddress, _tokenId, _erc20Supply, _erc20Name, _erc20Symbol, _erc20Decimals, _minimumShares, _deploymentData) == true);
        return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
    }

    function lock721Token (
        address _tokenToLockAddress,
        address _distributionAddress,
        address _paymentAddress,
        address _taxAddress,
        uint256 _tokenToLockId,
        uint256 _erc20Supply,
        string memory _erc20Name,
        string memory _erc20Symbol,
        uint _erc20Decimals,
        uint _minimumShares,
        bytes memory _deploymentData) private returns(bool)
    {
        TokenToLock memory _tokenToLock = TokenToLock(_tokenToLockAddress, _tokenToLockId);
        locked721Tokens.push(_tokenToLock); //need to think about if this will cause space issues
        AssetTokenizationContract newAssetTokenizationContract = new AssetTokenizationContract(_tokenToLockAddress, _distributionAddress, _paymentAddress, _taxAddress, _tokenToLockId, _erc20Supply, _erc20Name, _erc20Symbol, _erc20Decimals, _minimumShares, _deploymentData);
        ERC20ToToken[address(newAssetTokenizationContract)] = _tokenToLock;

        bytes32 _tokenToLockHash = abi.encode(keccak256(addressToString(_tokenToLockAddress), _tokenToLockId));
        tokenToERC20[_tokenToLockHash] = address(newAssetTokenizationContract);
        return true;
    }


texts: How to get a private key of an encoded account which was created with geth?

texts:
I have next problem:
I have created an account with password via geth. Right now I need to get private keys (or somehow retrieve my eth) without starting a peer-to-peer node. Is it possible to retrieve the private key or send eth to a different address without starting peer-to-peer node and eth? I have keystore with the needed account.


texts: How to get EVENT name from event signature hash?

texts:
I fount that some developers can get event_signature_hash for a event's name MyEvent(uint256) by using bellow code:

event_signature_hash = w3.sha3(text='MyEvent(uint256)').hex()

But vice versa, I couldn't find anyways to detect Event's name from event_signature_hash.

Can someone give a sample to do this?


texts: eventFilter web3.py in python to get events of locally deployed smart contracts using geth

texts:
I have tried ganache and geth too for contracts deployment locally hosted port # 8545. A function of deployed contract is called from another smart contract (deployed locally on same port)

So its like ContractA func1() -> ContractB func2(p1,p2) { emit event!!! }

ContractA

ContractA obj = ContractA(0x034309b0de3af84089cbaf6bb7a5b6f657f9f0e5);
obj.triggerEvent(param1, param2);

while ContractB

function triggerEvent(uint param1, address param2)
    public {
    emit TotalInv(msg.sender, param1, param2);
 }

  Now problem is I am trying to get this event in eventFilter as

  current_block = Web3(HTTPProvider('http://localhost:8545')).eth.getBlock('latest')
  event_filter = contractB_instance.eventFilter('TotalInv', {
            'fromBlock': 0,
            'toBlock': current_block['number']
        })

Other than this, I have created a simple function returning string in ContractB to check if instance of contractB is correct or not. And its working well, printing that string on console.

Env Details :

Python : 3.6.2

Geth : 1.8.15-stable-89451f7c

Truffle : 4.1.14

Windows 10

Web3.py : 4.6.0

Ganache : 1.1.0


texts: How does this code from ERC223 standard implementation work?

texts:
Here is a code snippet from the ERC223-token-standard.

function transfer(address _to, uint _value, bytes _data) {
    // Standard function transfer similar to ERC20 transfer with no _data .
    // Added due to backwards compatibility reasons .
    uint codeLength;

    assembly {
        // Retrieve the size of the code on target address, this needs assembly .
        codeLength := extcodesize(_to)
    }

    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    if(codeLength>0) {
        ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
        receiver.tokenFallback(msg.sender, _value, _data);
    }
    Transfer(msg.sender, _to, _value, _data);
}

What I don't understand is that how do these two lines work:

ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);

No new instance is created here but we are still calling the function.
How can we call the contract function like that?
There is no contstruct in the ERC223RecievingContract yet here the address is passed.
What exactly is happening here?


texts: ETC Stuck in ETH standard wallet contract

texts:
I used to use the standard wallet contract in Mist to store ETH and as a result have some ETC still stored in the wallet contract address according to the ETC block explorer. I am trying to figure out how to move the ETC from the contract.

I can access the contact on MEW by switching to ETC mode. Is there a function on the standard wallet contract that can return the ETC to the contract owner address? I have read and I'm not 100% sure the kill function could do this? I want to make sure as I don't want the ETC to be stuck forever. Any help or ideas would be appreciated.


texts: Remix - another transaction execution failed

texts:
I am trying to reproduce the results on Remix with the smart-contract as written here:
https://etherscan.io/address/0xb6ed7644c69416d67b522e20bc294a9a9b405b31#code

(for remix, go to http://remix.ethereum.org/)

The code compiles fine (with solidity ^0.4.18), however, when I try to deploy the _0xBitcoinToken contract, I get the "transaction execution failed" error.  I am placing enough gas for a transaction, so that does not seem to be an issue. What am I doing wrong, and why does the error appear ?


texts: What is the runtime performance of Ethereum Libraries compared to Contracts?

texts:
I'm looking for the cheapest way (in terms of gas price) to design upgradeable contracts. I don't expect many upgrades.
Being inspired by Writing upgradable contracts in Solidity, I'm investigating the use of libraries for logic implementation for a contract (so separating storage from the logic).
One obvious advantage is to only deploy once (or reuse already deployed) libraries and not contaminating the Blockchain with repetitive code.

Are there any runtime penalties (performance) of using libraries rather then contract inheritance?

The article mentioned above says:

  With libraries, there is a slight gas overhead on each call. However, it makes deploying a new contract much cheaper.

But it doesn't clarify what is the overhead.
If the overhead still exists, are there any plans to eliminate it?


texts: What phase are we in, today 22 January 2018? Still in Homestead?

texts: What phase are we in in the Ethereum roadmap, today, 22 January 2018?  Are we in Homestead?


texts: it is possible to save the hash in the ethereum contract before the transaction?

texts:
i have a question because i dont know how to do this.
Question : it is possible to save the hash in the ethereum contract before the transaction ?

Example Steps : Run The ethereum function -> get the hash transaction and save the has in a variable -> return the result of transaction
Explained : i wanna run a function that save the hash transaction of the own function runed
Example 2 : i have this struct of example

struct puppy {
 string name;
 string transactionHash
}

when i run a X function i wanna save the hash of that transaction in the "transactionHash"
i dont know if i explained at all , i dont know how to take that transaction hash to save when i run the function :

Example 3 : i wanna a create a "puppy" but when i create with function "createPuppy" i wanna save that transaction hash in the same struct of puppy.

struct puppy {
  string name;
  string transactionHash
}
function createPuppy ( string memory name ) public {
  // take the transaction hash of this function runed and save in "transactionHash" of the "puppy" struct
}

thanks a lot for read , if you know how to do this ... please say me how , i wanna learn and this is difficult to me because i dont know how to do it


texts:
Suppose I have a product with a specific id for sale(so I am the owner) and someone wants to buy the product from me. When he pays the price he will become the new owner of that product.

How can I record multiple owners for one specific asset?

I want to have a result like this (get all the addresses with the id)

56 => [0xcc6Bfe0C579416A6cC8532e984af0e6a, 0xcc6Bfe0C579416A12C8532e984th0e6a,...]

This is the way I did it which is not working as it should.

I summarized it to make it easier to understand.

Thanks in advance.

contract transfer{

  mapping(uint => address[]) public owners;

  function createAsset(string name, uint price) public
  {
      uint id = getRandom(); //I use a random generator function for id

      Asset memory newAsset = Asset(name, price); //struct to create a new product

      owners[id].push(msg.sender);

    }

  function transferProduct(uint id) public payable {
    owners[id].push(address((msg.sender)));

  }
}


texts: Please provide PHP example for eth_sendRawTransaction

texts:
I wish to have a PHP script use Infura's endpoint to call eth_sendRawTransaction. I have a PHP script which uses curl to call functions through Infura's endpoint, like eth_getBalance.

I use BlockCypher's "signer" program to sign data at BlockCypher.

The following description of eth_sendRawTransaction does not indicate how to create the signed transaction data, here.

Please provide a snippet of PHP code which exemplifies how to create the signed transaction data. At the place where the data needs to be signed, just use this line of code:

$sSignature = exec("./signer $sToSign $sPrivateKey");

I'm sure many other people will benefit from this example.


texts: sendRawTransaction is giving invalid txHash

texts:
While sending a raw transaction to rinkeby to deploy a contract, getting a transaction hash but in rinkeby etherscan.io it is showing the txHash as an invalid string. Here is my code :

web3.eth.getTransactionCount(account1, (err, txCount)=>{

//build the transaction
 const txObject = {
     nonce: web3.utils.toHex(txCount),
     gasLimit: web3.utils.toHex(1000000),
     gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
     data: data
 }
 //Sign the transaction
 const tx = new Tx(txObject)
 tx.sign(privateKey1)

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

 //Broadcast the transaction
 web3.eth.sendSignedTransaction(raw, (err, txHash)=> {
     console.log('err:', err, 'txHash:', txHash)
  })
 })


texts: What's the difference between Ethereum blockchain and Ethereum Classic blockchain?

texts: One project specifically was born after a hard-fork (Ethereum Classic) and the other one still having value but, what differences can we find between these two project concerning the blockchain?


texts: Ethereum: How to create new account using web3.py?

texts:
Using web3.py, I'm gonna create new account, however, I can't get passphrase.

  Generates a new account in the node’s keychain encrypted with the
  given passphrase. Returns the address of the created account.

  web3.personal.newAccount('the-passphrase')
  ['0xd3cda913deb6f67967b99d67acdfa1712c293601']

I saw this paragraph in Web3.py docs.
How to generate passphrase?


texts: My metamask was hacked. How to safely remove my staked tokens?

texts:
Yesterday my metamask was hacked. It happened when I was adding metamask to a reformatted laptop. My working theory is that I downloaded an illegal copy of metamask from chrome and that stole my funds. My question regards what happens next as I still have staked tokens associated with that wallet.
Interestingly they didnt steal all the funds from my wallet. They only stole tokens when I interacted with that token (actually when I added a custom token name to metamask the funds disappeared). In other words when I added AIOZ as a custom token to the metamask wallet the funds were actually diverted to the thief's account. The funds that I didnt interact with were not stolen. These included everything in the etherium part of the wallet and also the bsc tokens such as BNB with no intereaction.
Before realising what had happened (but after the tokens were stolen) I also noticed that there was some issues with the connection between metamask and projects. Maybe this also suggests that the metamask wallet was a fake download.
After realising the theft I turned off the laptop and went onto a PC that already had a proper copy of metamask on it. I was able to unstake some tokens (a small number to see that the result would be) and was able to then move these tokens to a new secure metamask wallet (I will be finding a new more secure home as soon as possible). I then gradually unstaked all my other tokens and removed them to the secure wallet in manageable blocks in case a bot or human interferred.
My ongoing issue is with three other tokens that are staked with vesting periods. One has a 7 day vesting period. The others 14 days and 1 month. If they could be unstaked now I could remove them as with the other tokens. But is it possible in the next 7 days the theives will see that the bot did half of the job and then manually try to access the tokens? If the laptop if off will they have access still? I am keeping a small amount of tokens in the wallet to monitor to see if there is any more activity.
And what to do with the staked vested tokens? Do I unstake them and and just pray that after 7 days I am the fastest to transfer them out?
They got about 15% of my portfolio. I am just happy that it was not worse. It could have been everything I guess. Try explaining that to the wife! I remember when I started that I was told exchanges are not secure and tokens should be kept in wallets. To be honest I feel my safest tokens are being stored exchanges with 2fa.
Any help would be appreciated. Thanks.


texts: How to redirect to Etherscan website when transaction completes?

texts:
In my project, I am doing a transaction by using

  ethereum.send({ })

method from web3 in javascript using metamask.  After the transaction completes I want to display the link to the user in label which will redirect to the Etherscan website with the current transaction details such that user can view transaction details on clicking that. Like this link :
https://kovan.etherscan.io/tx/0x5ffc0cd24cc1bba25df0d971ae4cbabbf0979aa76909272387bda6a0ab96dd64.
Currently I am using Kovan Testnet Network. How to get this complete link?


texts: Newbie. Getting cannot read property 'abi' of undefined when trying to deploy on Ubuntu

texts:
let abi = compiled.contracts.example.PartyTime.abi;

This is the line of code that is causing the error. I copied the abi code from Remix into an abi.json file. But it doesn't seem to be reading it correctly. Should I post the full code?

I am in the right folder where I have the code and have the code deploying it and the abi code in the same file.


texts: Would a 51% attack be easier if an attacker can DoS certain nodes?

texts:
I am wondering whether a 51% attack would be simplified by being able to remotely crash miner nodes. Consider the following scenario:

Malicious mining pool A controls 16% percent of the mining power and is capable to remotely crash other mining nodes or cut them off from the network.
Mining pool A now decides to crash 70% of the other mining nodes, leaving it with more than 50% of the remaining mining power in the network.
Can mining pool A now launch a 51% attack? If so, when will the difficulty be adjusted to account for the massively reduced mining power?

What is unclear to me here is the relationship between the massively reduced mining power, the adjusted difficulty and a 51% attack.

Mining pool A now controls 51% of the remaining mining power, but still has to mine blocks with a difficulty based on a way bigger network. So while a 51% attack might work eventually, the network is going to be jammed for a certain timeframe first. It is unclear to me how long that
timeframe is?


texts: Test Network - Understanding how Ether is Generated

texts:
I have a test network set up (mostly for learning purposes) using a unique network ID and seed node.  After calling 'geth init' and not pre-allocating anything to any wallets, the network has no ether and no transactions are currently pending.

Question One

So, a miner starts with with miner.start().  After just a little bit of time, they're generating ether into their wallets.  How does this happen?  To my understanding, mining is the processes of performing the verification hashes to make a transaction go through, and they are rewarded with the transaction fees.  If there are NO transactions pending, how does mining work?

Question Two

Say I wanted to pre-allocate 20% of ALL possible ether.  Is there a way in the genesis file to do this?  You can specify how much ether is allocated to an individual account, but you cannot specify the total available ether pool.


texts: Build a hash from a string and a number uint256 on Solidity

texts:
A Smart Contract needs to check the uniqueness of a number inside a serie. The serie is specified by a string, and the number by a uint256 type. Is there any easy way on Solidity to compute a hash from these two mixed parameters?

This hash will be very handy to identify uniquely the corresponding items, better than using the string and the number. What will be the best type for the resulting hash? A string or a bytes32? Thx!


texts: Contract method: Error: Provider not set or invalid

texts:
I'm building a Dapp using MetaMask. However, I'm getting an error when I try to call a method on my contract.

Here's the simplified code:

var web3 = new Web3(web3.currentProvider);
var contract = new web3.eth.Contract(contractData.abi);
contract.options.address = address;
contract.methods.getName().call().then(name => console.log(name))

This throws the following error:

Unhandled rejection Error: Provider not set or invalid

Digging through the debugger, it seems that the RequestManager doesn't have a provider set. However, I can't figure out how that provider should be set?


texts: Warning: Variable is shadowed in inline assembly by an instruction of the same name

texts:
I'm facing this warning on one of our solidity scripts
(compiler version - 0.4.18), this is a snippet on which I receive the warning

function () external payable onlyDuringSale isInitialized {
  create(msg.sender);
}

function create(address _recipient) public payable onlyDuringSale isInitialized {....}

Changing the function name to Create resolves the warning.

Can someone please explain why?

Thanks


texts: transfer(amount) failed even when it is not a contract

texts:
address payable receiver;

receiver.transfer(amount);

The receiver is NOT an contract, and the amount is only 0.4 ether, the contract is holding sufficient ether in its balance.

I understood that the latest solidity limits the transfer to 2300 gas, and it should be sufficient for the above operation. But why the above failed?


texts: How can I launch public alternative (not private) chain on Ethereum protocol

texts: What if I want to launch independent network using Ethereum protocol because current prices are too high for my purposes. Is that possible without forking and maintaining new codebase using geth or eth or ethereumj? What is the best tool for this?