<?php

namespace Test\Unit;

use Test\TestCase;
use Web3\Providers\HttpProvider;
use Web3\Contract;
use Web3\Utils;
use Web3\Contracts\Ethabi;
use Web3\Formatters\IntegerFormatter;
use phpseclib\Math\BigInteger as BigNumber;

class ContractTest extends TestCase
{
    /**
     * contract
     *
     * @var \Web3\Contract
     */
    protected $contract;

    /**
     * async contract
     *
     * @var \Web3\Contract
     */
    protected $asyncContract;

    /**
     * testAbi
     * GameToken abi from https://github.com/sc0Vu/GameToken
     *
     * @var string
     */
    protected $testAbi = '[
        {
          "constant": true,
          "inputs": [],
          "name": "name",
          "outputs": [
            {
              "name": "",
              "type": "string"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": false,
          "inputs": [
            {
              "name": "_spender",
              "type": "address"
            },
            {
              "name": "_value",
              "type": "uint256"
            }
          ],
          "name": "approve",
          "outputs": [
            {
              "name": "success",
              "type": "bool"
            }
          ],
          "payable": false,
          "stateMutability": "nonpayable",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [],
          "name": "totalSupply",
          "outputs": [
            {
              "name": "",
              "type": "uint256"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": false,
          "inputs": [
            {
              "name": "_from",
              "type": "address"
            },
            {
              "name": "_to",
              "type": "address"
            },
            {
              "name": "_value",
              "type": "uint256"
            }
          ],
          "name": "transferFrom",
          "outputs": [
            {
              "name": "success",
              "type": "bool"
            }
          ],
          "payable": false,
          "stateMutability": "nonpayable",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [],
          "name": "decimals",
          "outputs": [
            {
              "name": "",
              "type": "uint8"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [],
          "name": "standard",
          "outputs": [
            {
              "name": "",
              "type": "string"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [
            {
              "name": "",
              "type": "address"
            }
          ],
          "name": "balanceOf",
          "outputs": [
            {
              "name": "",
              "type": "uint256"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [],
          "name": "symbol",
          "outputs": [
            {
              "name": "",
              "type": "string"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "constant": false,
          "inputs": [
            {
              "name": "_to",
              "type": "address"
            },
            {
              "name": "_value",
              "type": "uint256"
            }
          ],
          "name": "transfer",
          "outputs": [],
          "payable": false,
          "stateMutability": "nonpayable",
          "type": "function"
        },
        {
          "constant": true,
          "inputs": [
            {
              "name": "",
              "type": "address"
            },
            {
              "name": "",
              "type": "address"
            }
          ],
          "name": "allowance",
          "outputs": [
            {
              "name": "",
              "type": "uint256"
            }
          ],
          "payable": false,
          "stateMutability": "view",
          "type": "function"
        },
        {
          "inputs": [
            {
              "name": "initialSupply",
              "type": "uint256"
            },
            {
              "name": "tokenName",
              "type": "string"
            },
            {
              "name": "decimalUnits",
              "type": "uint8"
            },
            {
              "name": "tokenSymbol",
              "type": "string"
            }
          ],
          "payable": false,
          "stateMutability": "nonpayable",
          "type": "constructor"
        },
        {
          "anonymous": false,
          "inputs": [
            {
              "indexed": true,
              "name": "from",
              "type": "address"
            },
            {
              "indexed": true,
              "name": "to",
              "type": "address"
            },
            {
              "indexed": false,
              "name": "value",
              "type": "uint256"
            }
          ],
          "name": "Transfer",
          "type": "event"
        },
        {
          "anonymous": false,
          "inputs": [
            {
              "indexed": true,
              "name": "_owner",
              "type": "address"
            },
            {
              "indexed": true,
              "name": "_spender",
              "type": "address"
            },
            {
              "indexed": false,
              "name": "_value",
              "type": "uint256"
            }
          ],
          "name": "Approval",
          "type": "event"
        }
    ]';

    /**
     * testBytecode
     * GameToken abi from https://github.com/sc0Vu/GameToken
     *
     * @var string
     */
    protected $testBytecode = ' ';

    /**
     * testUserAbi
     * User abi from https://github.com/BlockHR/contracts
     * 
     * @var string
     */
    protected $testUserAbi = '[
      {
        "constant": false,
        "inputs": [
          {
            "name": "ethAddress",
            "type": "address"
          }
        ],
        "name": "getUser",
        "outputs": [
          {
            "name": "firstName",
            "type": "string"
          },
          {
            "name": "lastName",
            "type": "string"
          },
          {
            "name": "age",
            "type": "uint256"
          }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
      },
      {
        "constant": false,
        "inputs": [
          {
            "name": "ethAddress",
            "type": "address"
          },
          {
            "name": "firstName",
            "type": "string"
          },
          {
            "name": "lastName",
            "type": "string"
          },
          {
            "name": "age",
            "type": "uint256"
          }
        ],
        "name": "addUser",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
      },
      {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
      },
      {
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "fallback"
      },
      {
        "anonymous": false,
        "inputs": [
          {
            "indexed": true,
            "name": "ethAddress",
            "type": "address"
          },
          {
            "indexed": false,
            "name": "firstName",
            "type": "string"
          },
          {
            "indexed": false,
            "name": "lastName",
            "type": "string"
          },
          {
            "indexed": false,
            "name": "age",
            "type": "uint256"
          }
        ],
        "name": "AddUser",
        "type": "event"
      }
    ]';

    /**
     * testUserBytecode
     * User bytecode from https://github.com/BlockHR/contracts
     * 
     * @var string
     */
    protected $testUserBytecode = ' ';

    /**
     * accounts
     * 
     * @var array
     */
    protected $accounts;

    /**
     * contractAddress
     * 
     * @var string
     */
    protected $contractAddress;

    /**
     * setUp
     *
     * @return void
     */
    public function setUp(): void
    {
        parent::setUp();

        $this->contract = new Contract($this->web3->provider, $this->testAbi);
        $this->contract->eth->accounts(function ($err, $accounts) {
            if ($err === null) {
                if (isset($accounts)) {
                    $this->accounts = $accounts;
                    return;
                }
            }
        });
        $this->asyncContract = new Contract($this->asyncHttpProvider, $this->testAbi);
    }

    /**
     * testInstance
     * 
     * @return void
     */
    public function testInstance()
    {
        $contract = new Contract($this->testHost, $this->testAbi);

        $this->assertTrue($contract->provider instanceof HttpProvider);
    }

    /**
     * testSetProvider
     * 
     * @return void
     */
    public function testSetProvider()
    {
        $contract = $this->contract;
        $contract->provider = new HttpProvider('http://localhost:8545');

        $this->assertEquals($contract->provider->host, 'http://localhost:8545');

        $contract->provider = null;

        $this->assertEquals($contract->provider->host, 'http://localhost:8545');
    }

    /**
     * testDeploy
     * 
     * @return void
     */
    public function testDeploy()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $account = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $account = $this->accounts[0];
        }
        $contract->bytecode($this->testBytecode)->new(1000000, 'Game Token', 1, 'GT', [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });
    }

    /**
     * testSend
     * 
     * @return void
     */
    public function testSend()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        $contract->bytecode($this->testBytecode)->new(1000000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }
        $contract->at($this->contractAddress)->send('transfer', $toAccount, 16, [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, $fromAccount, $toAccount) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use ($fromAccount, $toAccount, $contract) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $topics = $transaction->logs[0]->topics;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";

                    // validate topics
                    $this->assertEquals($contract->ethabi->encodeEventSignature($this->contract->events['Transfer']), $topics[0]);
                    $this->assertEquals('0x' . IntegerFormatter::format($fromAccount), $topics[1]);
                    $this->assertEquals('0x' . IntegerFormatter::format($toAccount), $topics[2]);
                }
            });
        });
    }

    /**
     * testCall
     * 
     * @return void
     */
    public function testCall()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        $contract->bytecode($this->testBytecode)->new(10000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }
        $contract->at($this->contractAddress)->call('balanceOf', $fromAccount, [
            'from' => $fromAccount
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                // $bn = Utils::toBn($result);
                // $this->assertEquals($bn->toString(), '10000', 'Balance should be 10000.');
                $this->assertTrue($result !== null);
            }
        });
        // test issue 143
        $contract->at($this->contractAddress)->call('balanceOf', $fromAccount, function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                // $bn = Utils::toBn($result);
                // $this->assertEquals($bn->toString(), '10000', 'Balance should be 10000.');
                $this->assertTrue($result !== null);
            }
        });
    }

    /**
     * testEstimateGas
     * 
     * @return void
     */
    public function testEstimateGas()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        $contract->bytecode($this->testBytecode)->new(10000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        $contract->bytecode($this->testBytecode)->estimateGas(10000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                echo "\nEstimate gas: " . $result->toString() . "\n";
                $this->assertTrue($result !== null);
            }
        });

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }
        $contract->at($this->contractAddress)->estimateGas('balanceOf', $fromAccount, [
            'from' => $fromAccount
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                // infura api gg
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                echo "\nEstimate gas: " . $result->toString() . "\n";
                $this->assertTrue($result !== null);
            }
        });
    }

    /**
     * testGetData
     * 
     * @return void
     */
    public function testGetData()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        $contract->bytecode($this->testBytecode)->new(10000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        $constructorData = $contract->bytecode($this->testBytecode)->getData(10000, 'Game Token', 1, 'GT');

        // $this->assertEquals(' ', $constructorData);

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }

        $balanceOfData = $contract->at($this->contractAddress)->getData('balanceOf', $fromAccount);

        $this->assertEquals('70a08231000000000000000000000000' . Utils::stripZero($fromAccount), $balanceOfData);
    }

    /**
     * testDecodeMethodReturn
     * 
     * @return void
     */
    public function testDecodeMethodReturn()
    {
        $contract = $this->contract;
        $contract->abi($this->testUserAbi);

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        // Deploy user contract.
        $contract->bytecode($this->testUserBytecode)->new([
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }

        // Add user.
        $contract->at($this->contractAddress)->send('addUser', $toAccount, 'Peter', 'Lai', 18, [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, $fromAccount, $toAccount) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use ($fromAccount, $toAccount, $contract) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $topics = $transaction->logs[0]->topics;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";

                    // validate topics
                    $this->assertEquals($contract->ethabi->encodeEventSignature($this->contract->events['AddUser']), $topics[0]);
                    $this->assertEquals('0x' . IntegerFormatter::format($toAccount), $topics[1]);
                }
            });
        });

        // Get user.
        $contract->call('getUser', $toAccount, [
            'from' => $fromAccount
        ], function ($err, $result) use ($contract, $fromAccount, $toAccount) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                $this->assertEquals($result['firstName'], 'Peter');
                $this->assertEquals($result['lastName'], 'Lai');
                $this->assertEquals($result['age']->toString(), '18');
            }
        });
    }

    /**
     * testIssue85
     *
     * @return void
     */
    public function testIssue85()
    {
        $bytecode = ' ';
        $abi = '[
            {
                "constant": true,
                "inputs": [],
                "name": "getBytes",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getBytes32",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes32"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getDynamicData",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    },
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getBoolean",
                "outputs": [
                    {
                        "name": "",
                        "type": "bool"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getInteger",
                "outputs": [
                    {
                        "name": "",
                        "type": "int256"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getTwoBytes32",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes32"
                    },
                    {
                        "name": "",
                        "type": "bytes32"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getBytesVeryLong",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getDynamicDataMixedOne",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    },
                    {
                        "name": "",
                        "type": "bytes32"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getBytes1",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes1"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getDynamicDataMixedTwo",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes32"
                    },
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "getBytesLong",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "pure",
                "type": "function"
            },
            {
                "inputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "constructor"
              }
        ]';
        $functions = [
            [
                'name' => 'getBoolean',
                'test' => function ($value) {
                    return is_bool($value);
                }
            ], [
                'name' => 'getInteger',
                'test' => function ($value) {
                    return ($value instanceof BigNumber);
                }
            ], [
                'name' => 'getBytes1',
                'test' => function ($value) {
                    return Utils::isHex($value) && mb_strlen($value) === 4;
                }
            ], [
                'name' => 'getBytes32',
                'test' => function ($value) {
                    return Utils::isHex($value) && mb_strlen($value) === 66;
                }
            ], [
                'name' => 'getBytesLong',
                'test' => function ($value) {
                    return Utils::isHex($value);
                }
            ], [
                'name' => 'getDynamicData',
                'test' => function ($value) {
                    return Utils::isHex($value);
                }
            ], [
                'name' => 'getDynamicDataMixedOne',
                'test' => function ($value) {
                    return Utils::isHex($value);
                }
            ], [
                'name' => 'getDynamicDataMixedTwo',
                'test' => function ($value) {
                    return Utils::isHex($value);
                }
            ], [
                'name' => 'getTwoBytes32',
                'test' => function ($value) {
                    return Utils::isHex($value) && mb_strlen($value) === 66;
                }
            ]
          ];
        $contractAddress = "";

        if (!isset($this->accounts[0])) {
            $account = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $account = $this->accounts[0];
        }
        $contract = new Contract($this->web3->provider, $abi);
        $contract->bytecode($bytecode)->new([
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, &$contractAddress) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use (&$contractAddress) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });
        $contract->at($contractAddress);

        foreach ($functions as $function) {
            $contract->call($function['name'], [], 'latest', function ($err, $res) use ($function) {
                if ($err !== null) {
                    echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                    return;
                }
                foreach ($res as $r) {
                    if (!call_user_func($function['test'], $r)) {
                        var_dump($r);
                    }
                    $this->assertTrue(call_user_func($function['test'], $r));
                }
            });
        }
    }

    /**
     * testIssue125
     *
     * @return void
     */
    public function testIssue125()
    {
        $bytecode = '0x608060405234801561001057600080fd5b506103bb806100206000396000f3fe608060405260043610610046576000357c01000000000000000000000000000000000000000000000000000000009004806373d4a13a1461004b578063ab62f0e1146100db575b600080fd5b34801561005757600080fd5b506100606101a3565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100a0578082015181840152602081019050610085565b50505050905090810190601f1680156100cd5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100e757600080fd5b506101a1600480360360208110156100fe57600080fd5b810190808035906020019064010000000081111561011b57600080fd5b82018360208201111561012d57600080fd5b8035906020019184600183028401116401000000008311171561014f57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050610241565b005b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102395780601f1061020e57610100808354040283529160200191610239565b820191906000526020600020905b81548152906001019060200180831161021c57829003601f168201915b505050505081565b80600090805190602001906102579291906102ea565b50806040518082805190602001908083835b60208310151561028e5780518252602082019150602081019050602083039250610269565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405180910390207fae08ae866f3211e692b7cdd30e8b6ec658a153397150437cb873f95239953a5460405160405180910390a250565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032b57805160ff1916838001178555610359565b82800160010185558215610359579182015b8281111561035857825182559160200191906001019061033d565b5b509050610366919061036a565b5090565b61038c91905b80821115610388576000816000905550600101610370565b5090565b9056fea165627a7a72305820bb836a29a397513a3f2e2199520262ef5978d3a3d7e3d3532da41064d39177e30029';
        $abi = '[
            {
                "constant": false,
                "inputs": [
                    {
                        "name": "_data",
                        "type": "bytes"
                    }
                ],
                "name": "setData",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "name": "_data",
                        "type": "bytes"
                    }
                ],
                "name": "SetData",
                "type": "event"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "data",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }
        ]';
        $contractAddress = "";

        if (!isset($this->accounts[0])) {
            $account = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $account = $this->accounts[0];
        }
        $contract = new Contract($this->web3->provider, $abi);
        $contract->bytecode($bytecode)->new([
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, &$contractAddress) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use (&$contractAddress) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });
        $contract->at($contractAddress);

        $contract->call('data', function ($err, $res) {
            if ($err !== null) {
                echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                return;
            }
            $this->assertEquals('0', $res[0]);
        });

        $contract->send('setData', '0x44aec9b900000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000021000000000000000000000000000000000000000000000000000000000000000b', [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                var_dump('Error' . $err->getMessage());
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                $this->assertTrue($transaction !== null);
            });
        });

        $contract->call('data', function ($err, $res) {
            if ($err !== null) {
                echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                return;
            }
            $this->assertEquals('0x44aec9b900000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000021000000000000000000000000000000000000000000000000000000000000000b', $res[0]);
        });
    }

    /**
     * testIssue134
     * 
     * @return void
     */
    public function testIssue134()
    {
        $bytecode = '0x608060405234801561001057600080fd5b50610487806100206000396000f3fe60806040526004361061005c576000357c01000000000000000000000000000000000000000000000000000000009004806373d4a13a146100615780638381f58a146100f15780639a73c4091461011c578063c3fad957146101ee575b600080fd5b34801561006d57600080fd5b50610076610229565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b657808201518184015260208101905061009b565b50505050905090810190601f1680156100e35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100fd57600080fd5b506101066102c7565b6040518082815260200191505060405180910390f35b34801561012857600080fd5b506101ec6004803603604081101561013f57600080fd5b81019080803590602001909291908035906020019064010000000081111561016657600080fd5b82018360208201111561017857600080fd5b8035906020019184600183028401116401000000008311171561019a57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102cd565b005b3480156101fa57600080fd5b506102276004803603602081101561021157600080fd5b810190808035906020019092919050505061037f565b005b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102bf5780601f10610294576101008083540402835291602001916102bf565b820191906000526020600020905b8154815290600101906020018083116102a257829003601f168201915b505050505081565b60015481565b80600090805190602001906102e39291906103b6565b5081600181905550806040518082805190602001908083835b60208310151561032157805182526020820191506020810190506020830392506102fc565b6001836020036101000a0380198251168184511680821785525050505050509050019150506040518091039020827f95d23dc1ab7ea37e46bd697006b873f80ffecb4cb4ae085c7cc60a977ba7f2f560405160405180910390a35050565b80600181905550807f9d9c58c068c2bc9cb27d4e5c437f624ccbf4910ba8893ffd03ee311830becab160405160405180910390a250565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103f757805160ff1916838001178555610425565b82800160010185558215610425579182015b82811115610424578251825591602001919060010190610409565b5b5090506104329190610436565b5090565b61045891905b8082111561045457600081600090555060010161043c565b5090565b9056fea165627a7a72305820830ee43c52ac89b1fbc68647e1893aea17aa8ca132532723176508a6bc4586c90029';
        $abi = '[
            {
                "constant": true,
                "inputs": [],
                "name": "data",
                "outputs": [
                    {
                        "name": "",
                        "type": "bytes"
                    }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            },
            {
                "constant": true,
                "inputs": [],
                "name": "number",
                "outputs": [
                    {
                        "name": "",
                        "type": "uint256"
                    }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            },
            {
                "constant": false,
                "inputs": [
                    {
                        "name": "_number",
                        "type": "uint256"
                    },
                    {
                        "name": "_data",
                        "type": "bytes"
                    }
                ],
                "name": "say",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "constant": false,
                "inputs": [
                    {
                        "name": "_number",
                        "type": "uint256"
                    }
                ],
                "name": "say",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "name": "_number",
                        "type": "uint256"
                    }
                ],
                "name": "Say",
                "type": "event"
            },
            {
                "anonymous": false,
                "inputs": [
                    {
                        "indexed": true,
                        "name": "_number",
                        "type": "uint256"
                    },
                    {
                        "indexed": true,
                        "name": "_data",
                        "type": "bytes"
                    }
                ],
                "name": "Say",
                "type": "event"
            }
        ]';
        $testNumber = 16;
        $testData = "0x01234";
        $contractAddress = "";
        $contract = new Contract($this->web3->provider, $abi);

        if (!isset($this->accounts[0])) {
            $account = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $account = $this->accounts[0];
        }
        $contract = new Contract($this->web3->provider, $abi);
        $contract->bytecode($bytecode)->new([
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, &$contractAddress) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use (&$contractAddress) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });
        $contract->at($contractAddress);

        // test for send transaction and get data
        $contract->send('say', $testNumber, $testData, [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, $testNumber, $testData) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use ($testNumber, $testData, $contract) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $topics = $transaction->logs[0]->topics;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";

                    // validate topics
                    $this->assertEquals($contract->ethabi->encodeEventSignature($contract->events['Say']), $topics[0]);
                    $this->assertEquals('0x' . IntegerFormatter::format($testNumber), $topics[1], $topics[2]);
                }
                $contract->call('number', function ($err, $res) use ($testNumber) {
                    if ($err !== null) {
                        echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                        return;
                    }
                    $this->assertEquals((string) $testNumber, $res[0]->toString());
                });
            });
        });
        $testNumber++;

        $contract->send('say', $testNumber, [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, $testNumber) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use ($testNumber, $contract) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $topics = $transaction->logs[0]->topics;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";

                    // validate topics
                    // $this->assertEquals($contract->ethabi->encodeEventSignature($contract->events['Say']), $topics[0]);
                    $this->assertEquals('0x' . IntegerFormatter::format($testNumber), $topics[1]);
                }
                $blockNumber = Utils::toBn($transaction->blockNumber);
                $contract->call('number', Utils::toHex($blockNumber, true), function ($err, $res) use ($testNumber) {
                    if ($err !== null) {
                        echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                        return;
                    }
                    $this->assertEquals((string) $testNumber, $res[0]->toString());
                });
                $blockNumber = $blockNumber->subtract(Utils::toBn(1));
                $contract->call('number', Utils::toHex($blockNumber, true), function ($err, $res) use ($testNumber) {
                    if ($err !== null) {
                        echo 'Error when call ' . $function['name'] . '. Message: ' . $err->getMessage() . "\n";
                        return;
                    }
                    $this->assertEquals((string) $testNumber-1, $res[0]->toString());
                });
            });
        });

        // test for estimate gas
        $contract->estimateGas("say", $testNumber, $testData, [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                echo "\nEstimate gas: " . $result->toString() . "\n";
                $this->assertTrue($result !== null);
            }
        });

        $contract->estimateGas("say", $testNumber, [
            'from' => $account,
            'gas' => '0x200b20'
        ], function ($err, $result) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                echo "\nEstimate gas: " . $result->toString() . "\n";
                $this->assertTrue($result !== null);
            }
        });
    }

    /**
     * testAsync
     * 
     * @return void
     */
    public function testAsync()
    {
        $contract = $this->contract;

        if (!isset($this->accounts[0])) {
            $fromAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c1';
        } else {
            $fromAccount = $this->accounts[0];
        }
        if (!isset($this->accounts[1])) {
            $toAccount = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        } else {
            $toAccount = $this->accounts[1];
        }
        $contract->bytecode($this->testBytecode)->new(1000000, 'Game Token', 1, 'GT', [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $contract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $this->contractAddress = $transaction->contractAddress;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";
                }
            });
        });

        if (!isset($this->contractAddress)) {
            $this->contractAddress = '0x407d73d8a49eeb85d32cf465507dd71d507100c2';
        }
        $asyncContract = $this->asyncContract;
        $promise1 = $asyncContract->at($this->contractAddress)->send('transfer', $toAccount, 16, [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract, $fromAccount, $toAccount, $asyncContract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if ($result) {
                echo "\nTransaction has made:) id: " . $result . "\n";
            }
            $transactionId = $result;
            $this->assertTrue((preg_match('/^0x[a-f0-9]{64}$/', $transactionId) === 1));

            $promise = $asyncContract->eth->getTransactionReceipt($transactionId, function ($err, $transaction) use ($fromAccount, $toAccount, $contract) {
                if ($err !== null) {
                    return $this->fail($err);
                }
                if ($transaction) {
                    $topics = $transaction->logs[0]->topics;
                    echo "\nTransaction has mined:) block number: " . $transaction->blockNumber . "\n";

                    // validate topics
                    $this->assertEquals($contract->ethabi->encodeEventSignature($this->contract->events['Transfer']), $topics[0]);
                    $this->assertEquals('0x' . IntegerFormatter::format($fromAccount), $topics[1]);
                    $this->assertEquals('0x' . IntegerFormatter::format($toAccount), $topics[2]);
                }
            });
            $this->assertTrue($promise instanceof \React\Promise\PromiseInterface);
            \React\Async\await($promise);
        });
        $this->assertTrue($promise1 instanceof \React\Promise\PromiseInterface);

        $promise2 = $asyncContract->at($this->contractAddress)->call('balanceOf', $fromAccount, [
            'from' => $fromAccount
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                // $bn = Utils::toBn($result);
                // $this->assertEquals($bn->toString(), '10000', 'Balance should be 10000.');
                $this->assertTrue($result !== null);
            }
        });

        $this->assertTrue($promise2 instanceof \React\Promise\PromiseInterface);

        $promise3 = $asyncContract->bytecode($this->testBytecode)->estimateGas('balanceOf', $toAccount, [
            'from' => $fromAccount,
            'gas' => '0x200b20'
        ], function ($err, $result) use ($contract) {
            if ($err !== null) {
                return $this->fail($err->getMessage());
            }
            if (isset($result)) {
                echo "\nEstimate gas: " . $result->toString() . "\n";
                $this->assertTrue($result !== null);
            }
        });
        \React\Async\await(\React\Async\parallel([
            function () use ($promise1) { return $promise1; },
            function () use ($promise2) { return $promise2; },
            function () use ($promise3) { return $promise3; },
        ]));
    }
}