├── .gitignore ├── db ├── database.sqlite └── db.ts ├── README.md ├── common ├── utils.ts ├── clover-types.ts └── api.ts ├── tsconfig.json ├── tests ├── e2e-tests │ ├── migrations │ │ └── 1_initial_migration.js │ ├── util │ │ └── get-code-hash.js │ ├── contracts │ │ ├── Migrations.sol │ │ ├── Multicall.sol │ │ ├── WETH.sol │ │ ├── CLV.sol │ │ ├── USDC.sol │ │ ├── USDT.sol │ │ ├── UniswapV2Factory.sol │ │ └── UNI.sol │ ├── test │ │ ├── installation_data.json │ │ └── test-uniswap.js │ └── truffle-config.js ├── gas-tests │ ├── migrations │ │ └── 1_initial_migration.js │ ├── contracts │ │ ├── Cache.sol │ │ ├── Migrations.sol │ │ └── Ballot.sol │ ├── solc │ │ ├── Ballot.abi │ │ ├── Ballot.bin │ │ └── Ballot.opcode │ ├── test │ │ ├── test-transfer-fee.js │ │ └── test-contract.js │ └── truffle-config.js ├── inner-contract-tests │ ├── migrations │ │ └── 1_initial_migration.js │ ├── contracts │ │ ├── Inner.sol │ │ └── Migrations.sol │ ├── test │ │ └── test-inner-contract.js │ └── truffle-config.js ├── common │ ├── clover-types.js │ └── clover-rpc.js ├── test-web3api.ts ├── bsc-tests │ └── test-bsc.js ├── test-deprecated.ts ├── account-bind-tests │ └── test-account-bind.js ├── test-rpc-constants.ts ├── test-balance.ts ├── test-nonce.ts ├── rococo-tests │ └── test-rococo.js ├── tps-tests │ ├── test-web3-tps.js │ └── test-polkadot-tps.js ├── test-contract.ts ├── test-revert-reason.ts ├── test-gas.ts ├── test-revert-receipt.ts ├── test-contract-methods.ts ├── util.ts ├── test-block.ts ├── test-bloom.ts └── test-subscription.ts ├── package.json └── explorer └── blocks.ts /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .idea/ 3 | -------------------------------------------------------------------------------- /db/database.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clover-network/clover-sdk/HEAD/db/database.sqlite -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clover-sdk 2 | Clover SDK is a javascript library that help developers to interact with Clover chain 3 | -------------------------------------------------------------------------------- /common/utils.ts: -------------------------------------------------------------------------------- 1 | export function sleep(ms) { 2 | return new Promise(resolve => setTimeout(resolve, ms)) 3 | } 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": [ "es2015" ], 4 | "esModuleInterop": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /tests/e2e-tests/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/gas-tests/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/inner-contract-tests/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/e2e-tests/util/get-code-hash.js: -------------------------------------------------------------------------------- 1 | var Web3 = require('web3') 2 | const artifact = require('../build/contracts/UniswapV2Pair.json') 3 | const initCodeHash = Web3.utils.keccak256(artifact.bytecode) 4 | console.log(initCodeHash) 5 | -------------------------------------------------------------------------------- /tests/common/clover-types.js: -------------------------------------------------------------------------------- 1 | const cloverTypes = { 2 | Amount: 'i128', 3 | Keys: 'SessionKeys3', 4 | AmountOf: 'Amount', 5 | Balance: 'u128', 6 | Rate: 'FixedU128', 7 | Ratio: 'FixedU128', 8 | EcdsaSignature: '[u8; 65]', 9 | EvmAddress: 'H160', 10 | } 11 | 12 | module.exports = cloverTypes; 13 | -------------------------------------------------------------------------------- /tests/inner-contract-tests/contracts/Inner.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.5.16; 2 | 3 | contract Demo1 { 4 | uint public data; 5 | function setData(uint _data) public { 6 | data = _data; 7 | } 8 | } 9 | 10 | contract Demo2 { 11 | function toSetData(Demo1 demo1, uint _data) public { 12 | demo1.setData(_data); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/gas-tests/contracts/Cache.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.22 <0.7.0; 2 | contract Cache { 3 | constructor () public {} 4 | 5 | mapping(address=>uint256) public data; 6 | 7 | function setValue(uint256 _value) public { 8 | data[msg.sender] = _value; 9 | } 10 | 11 | function getValue(address addr) public view returns (uint256) { 12 | return data[addr]; 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: CLOVER 2 | pragma solidity >=0.4.22 <0.8.0; 3 | 4 | contract Migrations { 5 | address public owner = msg.sender; 6 | uint public last_completed_migration; 7 | 8 | modifier restricted() { 9 | require( 10 | msg.sender == owner, 11 | "This function is restricted to the contract's owner" 12 | ); 13 | _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/gas-tests/contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.22 <0.8.0; 3 | 4 | contract Migrations { 5 | address public owner = msg.sender; 6 | uint public last_completed_migration; 7 | 8 | modifier restricted() { 9 | require( 10 | msg.sender == owner, 11 | "This function is restricted to the contract's owner" 12 | ); 13 | _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/inner-contract-tests/contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.22 <0.8.0; 3 | 4 | contract Migrations { 5 | address public owner = msg.sender; 6 | uint public last_completed_migration; 7 | 8 | modifier restricted() { 9 | require( 10 | msg.sender == owner, 11 | "This function is restricted to the contract's owner" 12 | ); 13 | _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/gas-tests/solc/Ballot.abi: -------------------------------------------------------------------------------- 1 | [{"inputs":[{"internalType":"uint256","name":"_numProposals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":false,"inputs":[{"internalType":"address","name":"voter","type":"address"}],"name":"giveRightToVote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"toProposal","type":"uint256"}],"name":"vote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"winningProposal","outputs":[{"internalType":"uint256","name":"_winningProposal","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}] -------------------------------------------------------------------------------- /tests/test-web3api.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | import { describeWithClover, customRequest } from "./util"; 4 | 5 | describeWithClover("Clover RPC (Web3Api)", (context) => { 6 | 7 | step("should get client version", async function () { 8 | const version = await context.web3.eth.getNodeInfo(); 9 | expect(version).to.be.equal("clover/v2.1/fc-rpc-0.9.0"); 10 | }); 11 | 12 | step("should remote sha3", async function () { 13 | const data = context.web3.utils.stringToHex("hello"); 14 | const hash = await customRequest(context.web3, "web3_sha3", [data]); 15 | const local_hash = context.web3.utils.sha3("hello"); 16 | expect(hash.result).to.be.equal(local_hash); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /tests/bsc-tests/test-bsc.js: -------------------------------------------------------------------------------- 1 | const { BncClient } = require("@binance-chain/javascript-sdk"); 2 | const Web3 = require("web3") 3 | // mainnet 4 | // const web3 = new Web3('https://bsc-dataseed1.binance.org:443'); 5 | // testnet 6 | const web3 = new Web3('https://data-seed-prebsc-2-s3.binance.org:8545/'); 7 | 8 | async function run(account) { 9 | try { 10 | //const client = new BncClient("") 11 | //client.initChain() 12 | console.log(account); 13 | const before = await web3.eth.getBalance(account); 14 | console.log(`before transfer: ${account}, has balance ${web3.utils.fromWei(before, "ether")}`); 15 | } catch (e) { 16 | console.log(e) 17 | } 18 | } 19 | 20 | run("0xf39F2Fda4b0c942A85b03760D9C0dB51b7963492") 21 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "clover-sdk", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha --timeout 60000 -r ts-node/register 'tests/**/*.ts'" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "@binance-chain/javascript-sdk": "^4.1.1", 13 | "@polkadot/api": "4.4.1", 14 | "@polkadot/util-crypto": "^6.0.5", 15 | "@types/chai": "^4.2.11", 16 | "@types/mocha": "^8.0.0", 17 | "bignumber.js": "^9.0.1", 18 | "chai": "^4.2.0", 19 | "knex": "^0.21.13", 20 | "lodash": "^4.17.20", 21 | "mocha": "^8.0.1", 22 | "mocha-steps": "^1.3.0", 23 | "rimraf": "^3.0.2", 24 | "sqlite3": "^5.0.0", 25 | "ts-node": "^8.10.2", 26 | "typescript": "^3.9.6", 27 | "web3": "^1.2.9" 28 | }, 29 | "devDependencies": {} 30 | } 31 | -------------------------------------------------------------------------------- /tests/test-deprecated.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { customRequest, describeWithClover } from "./util"; 3 | 4 | describeWithClover("Clover RPC (Deprecated)", (context) => { 5 | // List of deprecated methods 6 | [ 7 | { method: "eth_getCompilers", params: [] }, 8 | { method: "eth_compileLLL", params: ["(returnlll (suicide (caller)))"] }, 9 | { 10 | method: "eth_compileSolidity", 11 | params: ["contract test { function multiply(uint a) returns(uint d) {return a * 7;}}"], 12 | }, 13 | { method: "eth_compileSerpent", params: ["/* some serpent */"] }, 14 | ].forEach(({ method, params }) => { 15 | it(`${method} should be deprecated`, async function () { 16 | expect(await customRequest(context.web3, method, params)).to.deep.equal({ 17 | id: 1, 18 | jsonrpc: "2.0", 19 | error: { message: `Method not found`, code: -32601 }, 20 | }); 21 | }); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /common/clover-types.ts: -------------------------------------------------------------------------------- 1 | export const cloverTypes = { 2 | Amount: 'i128', 3 | Keys: 'SessionKeys3', 4 | AmountOf: 'Amount', 5 | Balance: 'u128', 6 | CurrencyId: { 7 | _enum: ['CLV', 'CUSDT', 'DOT', 'CETH'] 8 | }, 9 | CurrencyIdOf: 'CurrencyId', 10 | CurrencyTypeEnum: { 11 | _enum: ['CLV', 'CUSDT', 'DOT', 'CETH'] 12 | }, 13 | PairKey: 'u64', 14 | Rate: 'FixedU128', 15 | Ratio: 'FixedU128', 16 | Price: 'FixedU128', 17 | Share: 'u128', 18 | OracleKey: 'CurrencyId', 19 | CurrencyInfo: { 20 | id: 'CurrencyId', 21 | name: 'CurrencyTypeEnum' 22 | }, 23 | ExchangeInfo: { 24 | balance: 'Balance', 25 | routes: 'Vec' 26 | }, 27 | PoolId: { 28 | _enum: { 29 | Swap: 'u64' 30 | } 31 | }, 32 | EcdsaSignature: '[u8; 65]', 33 | EvmAddress: 'H160', 34 | } 35 | -------------------------------------------------------------------------------- /tests/account-bind-tests/test-account-bind.js: -------------------------------------------------------------------------------- 1 | const API = require("@polkadot/api") 2 | 3 | async function getBalance(address) { 4 | const wsProvider = new API.WsProvider('wss://api-ivy.clover.finance'); 5 | const api = await API.ApiPromise.create({ 6 | provider: wsProvider, 7 | types: { 8 | Amount: 'i128', 9 | Keys: 'SessionKeys4', 10 | AmountOf: 'Amount', 11 | Balance: 'u128', 12 | Rate: 'FixedU128', 13 | Ratio: 'FixedU128', 14 | EcdsaSignature: '[u8; 65]', 15 | EvmAddress: 'H160', 16 | }, 17 | }); 18 | const { parentHash } = await api.rpc.chain.getHeader(); 19 | const { 20 | data: { free: balance }, 21 | } = await api.query.system.account.at(parentHash, address); 22 | return balance.toString(); 23 | } 24 | 25 | getBalance('5DZabq7G2m12g1GUuqs66CCAVcmzdWRkXsGxpi4dgXFEcLEb').then(console.log) -------------------------------------------------------------------------------- /tests/test-rpc-constants.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { describeWithClover } from "./util"; 3 | 4 | // All test for the RPC 5 | 6 | describeWithClover("Clover RPC (Constant)", (context) => { 7 | it("should have 0 hashrate", async function () { 8 | expect(await context.web3.eth.getHashrate()).to.equal(0); 9 | }); 10 | 11 | it("should have chainId 42", async function () { 12 | // The chainId is defined by the Substrate Chain Id, default to 42 13 | expect(await context.web3.eth.getChainId()).to.equal(1337); 14 | }); 15 | 16 | it.skip("should have no account", async function () { 17 | expect(await context.web3.eth.getAccounts()).to.eql([]); 18 | }); 19 | 20 | it("block author should be 0x0000000000000000000000000000000000000000", async function () { 21 | // This address `0x1234567890` is hardcoded into the runtime find_author 22 | // as we are running manual sealing consensus. 23 | expect(await context.web3.eth.getCoinbase()).to.equal("0x0000000000000000000000000000000000000000"); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /tests/e2e-tests/test/installation_data.json: -------------------------------------------------------------------------------- 1 | { 2 | "private_key": { 3 | "alice": "90ee1d1e71c3df9ed4da37f253b3d10332cbbc0ad1903273267b40566753c978", 4 | "bob": "6cd70fe7846ca8b6149c2e3fa1060016ca2eb36b4c2a28cdbc5b711acbe5f079", 5 | "charlie": "c886baf9ed0552a130bd013594535a79eaa06a99397c168a230e91612cf41d58" 6 | }, 7 | "public_key": { 8 | "alice": "0x2193517101eB10EF22F2FA67eF452F66c51839d3", 9 | "bob": "0x3dF434112ffA3E10B031373fCe7BB4489BE1ccA4", 10 | "charlie": "0xc630E269076E6dF48597206Efb106b975bF4386a" 11 | }, 12 | "contract_address": { 13 | "weth": "0xfD1af441b0d20d9dC91A4D6A9ab9fa9e82Fe681a", 14 | "uniswap_v2_factory": "0x38ABb31f8219D6072c2Da09A2bf85d49431562bA", 15 | "multicall": "0xBaec187C129A9662256728Dd37204a5F79664eFa", 16 | "uniswap_v2_router": "0x17AF50C35BaF6e2874472ee365cC35697422EfE9", 17 | "clv": "0x384DD9770Bd4a928767ed7F7F9E9Cb94737169a6", 18 | "uni": "0x627172cFE76DB051399a14c0c8798B0c81291A45" 19 | } 20 | } -------------------------------------------------------------------------------- /common/api.ts: -------------------------------------------------------------------------------- 1 | import Web3 from "web3" 2 | import { WsProvider, ApiPromise } from "@polkadot/api" 3 | import { cloverTypes } from "./clover-types" 4 | 5 | const WEB3_RPC = "http://localhost:8545" 6 | const POLKADOT_WS = "ws://localhost:9944" 7 | 8 | export enum ApiProvider { 9 | Web3, 10 | Polkadot 11 | } 12 | 13 | let providers = { 14 | web3: null, 15 | polkadot: null 16 | } 17 | 18 | export async function getApi(provider: ApiProvider): Promise { 19 | switch (provider) { 20 | case ApiProvider.Web3: { 21 | if (!providers.web3) { 22 | providers.web3 = new Web3(WEB3_RPC) 23 | } 24 | return Promise.resolve(providers.web3) 25 | } 26 | case ApiProvider.Polkadot: { 27 | if (!providers.polkadot) { 28 | const wsProvider = new WsProvider(POLKADOT_WS); 29 | providers.polkadot = ApiPromise.create({ 30 | provider: wsProvider, 31 | types: cloverTypes 32 | }); 33 | } 34 | return providers.polkadot 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /tests/test-balance.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 5 | 6 | describeWithClover("Clover RPC (Balance)", (context) => { 7 | const GENESIS_ACCOUNT_BALANCE = "1000000000000000000000"; 8 | const TEST_ACCOUNT = "0x1111111111111111111111111111111111111111"; 9 | 10 | step("genesis balance is setup correctly", async function () { 11 | expect(await context.web3.eth.getBalance(GENESIS_ACCOUNT)).to.equal(GENESIS_ACCOUNT_BALANCE); 12 | }); 13 | 14 | step("balance to be updated after transfer", async function () { 15 | this.timeout(15000); 16 | 17 | const tx = await context.web3.eth.accounts.signTransaction({ 18 | from: GENESIS_ACCOUNT, 19 | to: TEST_ACCOUNT, 20 | value: "0x200", // Must me higher than ExistentialDeposit (500) 21 | gasPrice: "0x01", 22 | gas: "0x100000", 23 | }, GENESIS_ACCOUNT_PRIVATE_KEY); 24 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 25 | await createAndFinalizeBlock(context.web3); 26 | // 999999999999999978488 + 512 + 21000 (gas price) = 1000000000000000000000 27 | expect(await context.web3.eth.getBalance(GENESIS_ACCOUNT)).to.equal("999999999999999978488"); 28 | expect(await context.web3.eth.getBalance(TEST_ACCOUNT)).to.equal("512"); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /explorer/blocks.ts: -------------------------------------------------------------------------------- 1 | import { ApiProvider, getApi } from "../common/api" 2 | import Web3 from "web3" 3 | import { knex } from "../db/db" 4 | import { sleep } from "../common/utils" 5 | 6 | async function run() { 7 | const web3: Web3 = await getApi(ApiProvider.Web3) 8 | while (true) { 9 | const queryBlock = await knex("status").max("current_block_number as number") 10 | const maxBlock = queryBlock[0].number === null ? -1 : queryBlock[0].number 11 | const chainBlock = await web3.eth.getBlockNumber() 12 | if (maxBlock >= chainBlock) { 13 | await sleep(3000) 14 | continue 15 | } 16 | let block = await web3.eth.getBlock(maxBlock + 1) 17 | if (block.transactions.length > 0) { 18 | await knex.insert({ 19 | block_number: block.number, 20 | miner: block.miner, 21 | hash: block.hash, 22 | gas_used: block.gasUsed, 23 | trx_num: block.transactions.length, 24 | create_time: block.timestamp 25 | }).into("blocks") 26 | } 27 | if (maxBlock === -1) { 28 | await knex.insert({current_block_number: 0}).into("status") 29 | } else { 30 | await knex.table('status') 31 | .where({current_block_number: maxBlock}) 32 | .update({current_block_number: maxBlock + 1}); 33 | } 34 | } 35 | } 36 | 37 | run() 38 | -------------------------------------------------------------------------------- /tests/test-nonce.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 5 | 6 | describeWithClover("Clover RPC (Nonce)", (context) => { 7 | const TEST_ACCOUNT = "0x1111111111111111111111111111111111111111"; 8 | 9 | step("get nonce", async function () { 10 | this.timeout(10_000); 11 | const tx = await context.web3.eth.accounts.signTransaction({ 12 | from: GENESIS_ACCOUNT, 13 | to: TEST_ACCOUNT, 14 | value: "0x200", // Must me higher than ExistentialDeposit (500) 15 | gasPrice: "0x01", 16 | gas: "0x100000", 17 | }, GENESIS_ACCOUNT_PRIVATE_KEY); 18 | 19 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'earliest')).to.eq(0); 20 | 21 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 22 | 23 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'latest')).to.eq(0); 24 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'pending')).to.eq(1); 25 | 26 | await createAndFinalizeBlock(context.web3); 27 | 28 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'latest')).to.eq(1); 29 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'pending')).to.eq(1); 30 | expect(await context.web3.eth.getTransactionCount(GENESIS_ACCOUNT, 'earliest')).to.eq(0); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /db/db.ts: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const dbPath = path.resolve(__dirname, './database.sqlite') 3 | 4 | export const knex = require('knex') ({ 5 | client: 'sqlite3', 6 | connection: { 7 | filename: dbPath, 8 | }, 9 | useNullAsDefault: true 10 | }) 11 | 12 | function buildBlocks() { 13 | return knex.schema.hasTable('blocks').then((exists) => { 14 | if (!exists) { 15 | return knex.schema.createTable('blocks', (table) => { 16 | table.increments("id").primary() 17 | table.integer("block_number").unique() 18 | table.string("miner") 19 | table.string("hash") 20 | table.integer("gas_used") 21 | table.integer("trx_num") 22 | table.timestamp("create_time") 23 | }).catch((error) => { 24 | console.error(`Error creating table: ${error}`) 25 | }) 26 | } 27 | }) 28 | } 29 | 30 | function buildStatus() { 31 | return knex.schema.hasTable('status').then((exists) => { 32 | if (!exists) { 33 | return knex.schema.createTable('status', (table) => { 34 | table.increments("id").primary() 35 | table.integer("current_block_number") 36 | table.timestamp("create_time").defaultTo(knex.fn.now()) 37 | }).catch((error) => { 38 | console.error(`Error creating table: ${error}`) 39 | }) 40 | } 41 | }) 42 | } 43 | 44 | export async function buildTables() { 45 | await buildBlocks() 46 | await buildStatus() 47 | } 48 | 49 | buildTables() 50 | -------------------------------------------------------------------------------- /tests/rococo-tests/test-rococo.js: -------------------------------------------------------------------------------- 1 | const API = require("@polkadot/api"); 2 | const crypto = require("@polkadot/util-crypto"); 3 | const _ = require('lodash'); 4 | 5 | async function run() { 6 | const wsProvider = new API.WsProvider('wss://rococo-rpc.polkadot.io'); 7 | const api = await API.ApiPromise.create({ 8 | provider: wsProvider 9 | }); 10 | await crypto.cryptoWaitReady(); 11 | 12 | const { 13 | data: { free: balance }, 14 | } = await api.query.system.account('5CyNzgo7Paw8ymPioEJcfqnAoGgkftVspyFWjtCQuArcLSFw'); 15 | console.log(balance.toString()) 16 | 17 | /**const leases = await api.query.slots.leases.entries() 18 | _.forEach(leases,lease => { 19 | console.log(`leas info is: ${lease.toString()}`) 20 | })**/ 21 | 22 | // lease period is 14400, 14400 * 6 = 86400 = 1 day. in future, should be 6 month 23 | const leasePeriod = api.consts.slots.leasePeriod 24 | console.log(leasePeriod.toString()) 25 | 26 | const funds = await api.query.crowdloan.funds.entries() 27 | _.forEach(funds,fundInfo => { 28 | console.log(`fund info is: ${fundInfo.toString()}`) 29 | }) 30 | 31 | const auctionCounter = await api.query.auctions.auctionCounter() 32 | console.log(`currently, there are total ${auctionCounter.toString()} auctions`) 33 | const auctionInfo = await api.query.auctions.auctionInfo() 34 | console.log(`currently, the auctions are: ${auctionInfo.toString()}`) 35 | 36 | /**const paras = await api.query.registrar.paras.entries() 37 | _.forEach(paras,paraInfo => { 38 | console.log(`para info is: ${paraInfo.toString()}`) 39 | })**/ 40 | } 41 | 42 | run() -------------------------------------------------------------------------------- /tests/gas-tests/contracts/Ballot.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.22 <0.7.0; 2 | contract Ballot { 3 | 4 | struct Voter { 5 | uint weight; 6 | bool voted; 7 | uint vote; 8 | } 9 | struct Proposal { 10 | uint voteCount; 11 | } 12 | 13 | address chairperson; 14 | mapping(address => Voter) voters; 15 | Proposal[] proposals; 16 | 17 | constructor(uint _numProposals) public { 18 | chairperson = msg.sender; 19 | voters[chairperson].weight = 2; 20 | proposals.length = _numProposals; 21 | } 22 | 23 | function giveRightToVote(address voter) public { 24 | require( 25 | msg.sender == chairperson, 26 | "Only chairperson can give right to vote." 27 | ); 28 | require( 29 | !voters[voter].voted, 30 | "The voter already voted." 31 | ); 32 | require(voters[voter].weight == 0); 33 | voters[voter].weight = 1; 34 | } 35 | 36 | function vote(uint toProposal) public { 37 | Voter storage sender = voters[msg.sender]; 38 | require(sender.weight != 0, "Has no right to vote"); 39 | require(!sender.voted, "Already voted."); 40 | sender.voted = true; 41 | sender.vote = toProposal; 42 | proposals[toProposal].voteCount += sender.weight; 43 | } 44 | 45 | function winningProposal() public view returns (uint _winningProposal) { 46 | uint256 winningVoteCount = 0; 47 | for (uint p = 0; p < proposals.length; p++) 48 | if (proposals[p].voteCount > winningVoteCount) { 49 | winningVoteCount = proposals[p].voteCount; 50 | _winningProposal = p; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tests/gas-tests/test/test-transfer-fee.js: -------------------------------------------------------------------------------- 1 | const expect = require("chai").expect 2 | const step = require("mocha-steps").step 3 | const Web3 = require("web3") 4 | const BigNumber = require('bignumber.js'); 5 | 6 | const TIMEOUT = require("../truffle-config").mocha.timeout 7 | const web3 = new Web3("http://localhost:8545") 8 | const GENESIS_ACCOUNT = "0xe6206C7f064c7d77C6d8e3eD8601c9AA435419cE" 9 | const GENESIS_ACCOUNT_PRIVATE_KEY = "0xa504b64992e478a6846670237a68ad89b6e42e90de0490273e28e74f084c03c8" 10 | const TEST_ACCOUNT = "0x2193517101eB10EF22F2FA67eF452F66c51839d3" 11 | 12 | async function transfer(account, etherValue) { 13 | const before = await web3.eth.getBalance(account); 14 | console.log(`before receive: ${account}, has balance ${before}`) 15 | const signedTransaction = await web3.eth.accounts.signTransaction({ 16 | from: GENESIS_ACCOUNT, 17 | to: account, 18 | value: web3.utils.toWei(etherValue.toString(), "ether"), 19 | gasPrice: web3.utils.toWei("1", "gwei"), 20 | gas: "0x5208", 21 | }, GENESIS_ACCOUNT_PRIVATE_KEY); 22 | await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) 23 | const after = await web3.eth.getBalance(account); 24 | console.log(`after receive: ${account}, has balance ${after}`) 25 | } 26 | 27 | describe("Test transfer", () => { 28 | step("Balance should be correct after transaction", async function () { 29 | const before = await web3.eth.getBalance(GENESIS_ACCOUNT); 30 | console.log(`before send: ${GENESIS_ACCOUNT}, has balance ${before}`) 31 | await transfer(TEST_ACCOUNT, 200) 32 | const after = await web3.eth.getBalance(GENESIS_ACCOUNT); 33 | console.log(`after send: ${GENESIS_ACCOUNT}, has balance ${after}`) 34 | const afterBN = new BigNumber(after).plus(new BigNumber("21000000000000")).plus(web3.utils.toWei("200", "ether")); 35 | expect(afterBN.toString()).to.equal(new BigNumber(before).toString()); 36 | }).timeout(TIMEOUT) 37 | }); 38 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/Multicall.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Etherscan.io on 2019-06-10 3 | */ 4 | 5 | pragma solidity >=0.5.0; 6 | pragma experimental ABIEncoderV2; 7 | 8 | /// @title Multicall - Aggregate results from multiple read-only function calls 9 | /// @author Michael Elliot 10 | /// @author Joshua Levine 11 | /// @author Nick Johnson 12 | 13 | contract Multicall { 14 | struct Call { 15 | address target; 16 | bytes callData; 17 | } 18 | function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { 19 | blockNumber = block.number; 20 | returnData = new bytes[](calls.length); 21 | for(uint256 i = 0; i < calls.length; i++) { 22 | (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); 23 | require(success); 24 | returnData[i] = ret; 25 | } 26 | } 27 | // Helper functions 28 | function getEthBalance(address addr) public view returns (uint256 balance) { 29 | balance = addr.balance; 30 | } 31 | function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) { 32 | blockHash = blockhash(blockNumber); 33 | } 34 | function getLastBlockHash() public view returns (bytes32 blockHash) { 35 | blockHash = blockhash(block.number - 1); 36 | } 37 | function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { 38 | timestamp = block.timestamp; 39 | } 40 | function getCurrentBlockDifficulty() public view returns (uint256 difficulty) { 41 | difficulty = block.difficulty; 42 | } 43 | function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) { 44 | gaslimit = block.gaslimit; 45 | } 46 | function getCurrentBlockCoinbase() public view returns (address coinbase) { 47 | coinbase = block.coinbase; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/WETH.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.22 <0.6.0; 2 | 3 | contract WETH { 4 | string public name = "Wrapped Ether"; 5 | string public symbol = "WETH"; 6 | uint8 public decimals = 18; 7 | 8 | event Approval(address indexed src, address indexed guy, uint wad); 9 | event Transfer(address indexed src, address indexed dst, uint wad); 10 | event Deposit(address indexed dst, uint wad); 11 | event Withdrawal(address indexed src, uint wad); 12 | 13 | mapping (address => uint) public balanceOf; 14 | mapping (address => mapping (address => uint)) public allowance; 15 | 16 | function() external payable { 17 | deposit(); 18 | } 19 | function deposit() public payable { 20 | balanceOf[msg.sender] += msg.value; 21 | emit Deposit(msg.sender, msg.value); 22 | } 23 | function withdraw(uint wad) public { 24 | require(balanceOf[msg.sender] >= wad); 25 | balanceOf[msg.sender] -= wad; 26 | msg.sender.transfer(wad); 27 | emit Withdrawal(msg.sender, wad); 28 | } 29 | 30 | function totalSupply() public view returns (uint) { 31 | return address(this).balance; 32 | } 33 | 34 | function approve(address guy, uint wad) public returns (bool) { 35 | allowance[msg.sender][guy] = wad; 36 | emit Approval(msg.sender, guy, wad); 37 | return true; 38 | } 39 | 40 | function transfer(address dst, uint wad) public returns (bool) { 41 | return transferFrom(msg.sender, dst, wad); 42 | } 43 | 44 | function transferFrom(address src, address dst, uint wad) 45 | public 46 | returns (bool) 47 | { 48 | require(balanceOf[src] >= wad); 49 | 50 | if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { 51 | require(allowance[src][msg.sender] >= wad); 52 | allowance[src][msg.sender] -= wad; 53 | } 54 | 55 | balanceOf[src] -= wad; 56 | balanceOf[dst] += wad; 57 | 58 | emit Transfer(src, dst, wad); 59 | 60 | return true; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/tps-tests/test-web3-tps.js: -------------------------------------------------------------------------------- 1 | const Web3 = require("web3") 2 | const web3 = new Web3("http://localhost:8545") 3 | const GENESIS_ACCOUNT = "0xe6206C7f064c7d77C6d8e3eD8601c9AA435419cE" 4 | const GENESIS_ACCOUNT_PRIVATE_KEY = "0xa504b64992e478a6846670237a68ad89b6e42e90de0490273e28e74f084c03c8" 5 | const TEST_ACCOUNT = "0x2193517101eB10EF22F2FA67eF452F66c51839d3" 6 | let sent = 0; 7 | let finished = 0; 8 | 9 | function sleep(ms) { 10 | return new Promise(resolve => setTimeout(resolve, ms)); 11 | } 12 | 13 | async function transfer(to, etherValue, nonce, from, fromKey) { 14 | try { 15 | sent++; 16 | const signedTransaction = await web3.eth.accounts.signTransaction({ 17 | from: from, 18 | to: to, 19 | value: web3.utils.toWei(etherValue.toString(), "ether"), 20 | gasPrice: web3.utils.toWei("1", "gwei"), 21 | gas: "0x5208", 22 | nonce: nonce 23 | }, fromKey); 24 | await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction); 25 | finished++; 26 | console.log(`finished ${finished}`); 27 | return nonce; 28 | } catch (e) { 29 | sent--; 30 | console.log(`Transaction with ${nonce} failed`, e.toString()); 31 | await sleep(1000); 32 | if (!e.toString().includes("TemporarilyBanned") && !e.toString().includes("AlreadyImported")) { 33 | transfer(to, etherValue, nonce, from, fromKey); 34 | } 35 | } 36 | } 37 | 38 | async function doTransfer() { 39 | const queue = []; 40 | let nonce = 0; 41 | const sender = web3.eth.accounts.create(); 42 | const count = await web3.eth.getTransactionCount(GENESIS_ACCOUNT); 43 | await transfer(sender.address, 10, count, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY); 44 | const start = new Date().getTime(); 45 | while (nonce < 5000) { 46 | if (sent - finished > 120) { 47 | await sleep(1000); 48 | const tps = finished * 1000 / (new Date().getTime() - start); 49 | console.log(`tps: ${tps}`) 50 | } else { 51 | queue.push(transfer(TEST_ACCOUNT, 0.001, nonce, sender.address, sender.privateKey)); 52 | nonce++; 53 | } 54 | } 55 | return Promise.all(queue); 56 | } 57 | 58 | doTransfer().then(() => { 59 | console.log("done"); 60 | }) 61 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/CLV.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.4.18; 2 | 3 | contract CLV { 4 | string public name = "CLV"; 5 | string public symbol = "CLV"; 6 | uint8 public decimals = 18; 7 | 8 | event Approval(address indexed src, address indexed guy, uint wad); 9 | event Transfer(address indexed src, address indexed dst, uint wad); 10 | event Deposit(address indexed dst, uint wad); 11 | event Withdrawal(address indexed src, uint wad); 12 | 13 | mapping (address => uint) public balanceOf; 14 | mapping (address => mapping (address => uint)) public allowance; 15 | 16 | constructor(uint256 myTotalSupply) public { 17 | balanceOf[msg.sender] = myTotalSupply; 18 | } 19 | 20 | function() external payable { 21 | deposit(); 22 | } 23 | function deposit() public payable { 24 | balanceOf[msg.sender] += msg.value; 25 | emit Deposit(msg.sender, msg.value); 26 | } 27 | function withdraw(uint wad) public { 28 | require(balanceOf[msg.sender] >= wad); 29 | balanceOf[msg.sender] -= wad; 30 | msg.sender.transfer(wad); 31 | emit Withdrawal(msg.sender, wad); 32 | } 33 | 34 | function totalSupply() public view returns (uint) { 35 | return address(this).balance; 36 | } 37 | 38 | function approve(address guy, uint wad) public returns (bool) { 39 | allowance[msg.sender][guy] = wad; 40 | emit Approval(msg.sender, guy, wad); 41 | return true; 42 | } 43 | 44 | function transfer(address dst, uint wad) public returns (bool) { 45 | return transferFrom(msg.sender, dst, wad); 46 | } 47 | 48 | function transferFrom(address src, address dst, uint wad) 49 | public 50 | returns (bool) 51 | { 52 | require(balanceOf[src] >= wad); 53 | 54 | if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { 55 | require(allowance[src][msg.sender] >= wad); 56 | allowance[src][msg.sender] -= wad; 57 | } 58 | 59 | balanceOf[src] -= wad; 60 | balanceOf[dst] += wad; 61 | 62 | emit Transfer(src, dst, wad); 63 | 64 | return true; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /tests/test-contract.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | 3 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 4 | 5 | describeWithClover("Clover RPC (Contract)", (context) => { 6 | // Solidity: contract test { function multiply(uint a) public pure returns(uint d) {return a * 7;}} 7 | const TEST_CONTRACT_BYTECODE = 8 | "0x6080604052348015600f57600080fd5b5060ae8061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063c6888fa114602d575b600080fd5b605660048036036020811015604157600080fd5b8101908080359060200190929190505050606c565b6040518082815260200191505060405180910390f35b600060078202905091905056fea265627a7a72315820f06085b229f27f9ad48b2ff3dd9714350c1698a37853a30136fa6c5a7762af7364736f6c63430005110032"; 9 | const FIRST_CONTRACT_ADDRESS = "0xc2bf5f29a4384b1ab0c063e1c666f02121b6084a"; 10 | // Those test are ordered. In general this should be avoided, but due to the time it takes 11 | // to spin up a frontier node, it saves a lot of time. 12 | 13 | it("contract creation should return transaction hash", async function () { 14 | this.timeout(15000); 15 | const tx = await context.web3.eth.accounts.signTransaction( 16 | { 17 | from: GENESIS_ACCOUNT, 18 | data: TEST_CONTRACT_BYTECODE, 19 | value: "0x00", 20 | gasPrice: "0x01", 21 | gas: "0x100000", 22 | }, 23 | GENESIS_ACCOUNT_PRIVATE_KEY 24 | ); 25 | 26 | expect(await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction])).to.deep.equal({ 27 | id: 1, 28 | jsonrpc: "2.0", 29 | result: "0x7e1e4df9dee2d1dde18c7911562ec3bd82da0e6862b1176bf351b4a0379ff4ab", 30 | }); 31 | 32 | // Verify the contract is not yet stored 33 | expect(await customRequest(context.web3, "eth_getCode", [FIRST_CONTRACT_ADDRESS])).to.deep.equal({ 34 | id: 1, 35 | jsonrpc: "2.0", 36 | result: "0x", 37 | }); 38 | 39 | // Verify the contract is stored after the block is produced 40 | await createAndFinalizeBlock(context.web3); 41 | expect(await customRequest(context.web3, "eth_getCode", [FIRST_CONTRACT_ADDRESS])).to.deep.equal({ 42 | id: 1, 43 | jsonrpc: "2.0", 44 | result: 45 | "0x6080604052348015600f57600080fd5b506004361060285760003560e01c8063c6888fa114602d575b600080fd5b605660048036036020811015604157600080fd5b8101908080359060200190929190505050606c565b6040518082815260200191505060405180910390f35b600060078202905091905056fea265627a7a72315820f06085b229f27f9ad48b2ff3dd9714350c1698a37853a30136fa6c5a7762af7364736f6c63430005110032", 46 | }); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /tests/tps-tests/test-polkadot-tps.js: -------------------------------------------------------------------------------- 1 | const API = require("@polkadot/api"); 2 | const cloverTypes = require("../common/clover-types"); 3 | const cloverRpc = require("../common/clover-rpc"); 4 | const crypto = require("@polkadot/util-crypto"); 5 | const _ = require('lodash'); 6 | let finished = 0; 7 | let start = new Date().getTime(); 8 | 9 | function getTestAccounts(keyring, num) { 10 | const accounts = _.chain(Array(num)).fill(1).map((v, idx) => { 11 | return keyring.addFromUri(`//test/${idx}`, { name: `test ${idx}` }); 12 | }).value(); 13 | return accounts 14 | } 15 | 16 | async function run(numTx) { 17 | const wsProvider = new API.WsProvider('ws://localhost:9944'); 18 | const api = await API.ApiPromise.create({ 19 | provider: wsProvider, 20 | types: cloverTypes, 21 | rpc: cloverRpc 22 | }); 23 | await crypto.cryptoWaitReady(); 24 | const keyring = new API.Keyring({ type: 'sr25519' }); 25 | const alice = keyring.addFromUri('//Alice'); 26 | 27 | const { parentHash } = await api.rpc.chain.getHeader(); 28 | let nonce = await api.rpc.system.accountNextIndex(alice.address); 29 | const balance = await api.query.system.account.at(parentHash, alice.address); 30 | console.log(`Alice's balance at ${parentHash.toHex()} was ${balance.data.free}`); 31 | let accounts = getTestAccounts(keyring, 1); 32 | finished = 0; 33 | start = new Date().getTime(); 34 | const tx = [...Array(numTx).keys()].map(i => sendTx(api, alice, accounts[0].address, "1000000000000", _.parseInt(nonce) + i)); 35 | return Promise.all(tx); 36 | } 37 | 38 | function sendTx(api, from, to, amount, nonce) { 39 | return new Promise(async (resolve, reject) => { 40 | const unsub = await api.tx.balances 41 | .transfer(to, amount) 42 | .signAndSend(from, { 43 | nonce, 44 | }, ({ events = [], status }) => { 45 | if (status.isInBlock) { 46 | finished++; 47 | const tps = finished * 1000 / (new Date().getTime() - start); 48 | console.log(`tps: ${tps}`); 49 | unsub(); 50 | } else if (status.isFinalized) { 51 | } 52 | }); 53 | }); 54 | } 55 | 56 | async function getBalance(address) { 57 | const wsProvider = new API.WsProvider('wss://api.clover.finance'); 58 | const api = await API.ApiPromise.create({ 59 | provider: wsProvider, 60 | types: cloverTypes, 61 | rpc: cloverRpc 62 | }); 63 | await crypto.cryptoWaitReady(); 64 | let account = await api.query.system.account(address); 65 | console.log(account.data.free.toHuman()); 66 | return account.data.free; 67 | } 68 | 69 | run(10000).then(() => { 70 | console.log("done"); 71 | process.exit(0); 72 | }); 73 | -------------------------------------------------------------------------------- /tests/test-revert-reason.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 5 | import { AbiItem } from "web3-utils"; 6 | 7 | describeWithClover("Clover RPC (Revert Reason)", (context) => { 8 | 9 | let contractAddress; 10 | 11 | // contract ExplicitRevertReason { 12 | // function max10(uint256 a) public returns (uint256) { 13 | // if (a > 10) 14 | // revert("Value must not be greater than 10."); 15 | // return a; 16 | // } 17 | // } 18 | const REVERT_W_MESSAGE_BYTECODE = "0x608060405234801561001057600080fd5b50610127806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80638361ff9c14602d575b600080fd5b605660048036036020811015604157600080fd5b8101908080359060200190929190505050606c565b6040518082815260200191505060405180910390f35b6000600a82111560c7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806100d06022913960400191505060405180910390fd5b81905091905056fe56616c7565206d757374206e6f742062652067726561746572207468616e2031302ea2646970667358221220e63c9905b696e005347b92b4a24ac548a70b1fa80b9d8d2c0499b795503a1b4a64736f6c634300060c0033"; 19 | 20 | const TEST_CONTRACT_ABI = { 21 | constant: true, 22 | inputs: [{ internalType: "uint256", name: "a", type: "uint256" }], 23 | name: "max10", 24 | outputs: [{ internalType: "uint256", name: "b", type: "uint256" }], 25 | payable: false, 26 | stateMutability: "pure", 27 | type: "function", 28 | } as AbiItem; 29 | 30 | before("create the contract", async function () { 31 | this.timeout(15000); 32 | const tx = await context.web3.eth.accounts.signTransaction( 33 | { 34 | from: GENESIS_ACCOUNT, 35 | data: REVERT_W_MESSAGE_BYTECODE, 36 | value: "0x00", 37 | gasPrice: "0x01", 38 | gas: "0x100000", 39 | }, 40 | GENESIS_ACCOUNT_PRIVATE_KEY 41 | ); 42 | const r = await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 43 | await createAndFinalizeBlock(context.web3); 44 | const receipt = await context.web3.eth.getTransactionReceipt(r.result); 45 | contractAddress = receipt.contractAddress; 46 | }); 47 | 48 | it("should fail with revert reason", async function () { 49 | const contract = new context.web3.eth.Contract([TEST_CONTRACT_ABI], contractAddress, { 50 | from: GENESIS_ACCOUNT, 51 | gasPrice: "0x01", 52 | }); 53 | try { 54 | await contract.methods.max10(30).call(); 55 | } catch (error) { 56 | expect(error.message).to.be.eq( 57 | "Returned error: VM Exception while processing transaction: revert Value must not be greater than 10." 58 | ); 59 | } 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /tests/test-gas.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | 3 | import { createAndFinalizeBlock, describeWithClover, GENESIS_ACCOUNT } from "./util"; 4 | import { AbiItem } from "web3-utils"; 5 | 6 | describeWithClover("Clover RPC (Gas)", (context) => { 7 | // Solidity: contract test { function multiply(uint a) public pure returns(uint d) {return a * 7;}} 8 | const TEST_CONTRACT_BYTECODE = 9 | "0x6080604052348015600f57600080fd5b5060ae8061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063c6888fa114602d575b600080fd5b605660048036036020811015604157600080fd5b8101908080359060200190929190505050606c565b6040518082815260200191505060405180910390f35b600060078202905091905056fea265627a7a72315820f06085b229f27f9ad48b2ff3dd9714350c1698a37853a30136fa6c5a7762af7364736f6c63430005110032"; 10 | 11 | const TEST_CONTRACT_ABI = { 12 | constant: true, 13 | inputs: [{ internalType: "uint256", name: "a", type: "uint256" }], 14 | name: "multiply", 15 | outputs: [{ internalType: "uint256", name: "d", type: "uint256" }], 16 | payable: false, 17 | stateMutability: "pure", 18 | type: "function", 19 | } as AbiItem; 20 | 21 | const FIRST_CONTRACT_ADDRESS = "0xc2bf5f29a4384b1ab0c063e1c666f02121b6084a"; // Those test are ordered. In general this should be avoided, but due to the time it takes // to spin up a frontier node, it saves a lot of time. 22 | 23 | it("eth_estimateGas for contract creation", async function () { 24 | expect( 25 | await context.web3.eth.estimateGas({ 26 | from: GENESIS_ACCOUNT, 27 | data: TEST_CONTRACT_BYTECODE, 28 | }) 29 | ).to.equal(91019); 30 | }); 31 | 32 | it.skip("block gas limit over 5M", async function () { 33 | expect((await context.web3.eth.getBlock("latest")).gasLimit).to.be.above(5000000); 34 | }); 35 | 36 | // Testing the gas limit protection, hardcoded to 25M 37 | it.skip("gas limit should decrease on next block if gas unused", async function () { 38 | this.timeout(15000); 39 | 40 | const gasLimit = (await context.web3.eth.getBlock("latest")).gasLimit; 41 | await createAndFinalizeBlock(context.web3); 42 | 43 | // Gas limit is expected to have decreased as the gasUsed by the block is lower than 2/3 of the previous gas limit 44 | const newGasLimit = (await context.web3.eth.getBlock("latest")).gasLimit; 45 | expect(newGasLimit).to.be.below(gasLimit); 46 | }); 47 | 48 | // Testing the gas limit protection, hardcoded to 25M 49 | it.skip("gas limit should increase on next block if gas fully used", async function () { 50 | // TODO: fill a block with many heavy transaction to simulate lot of gas. 51 | }); 52 | 53 | it("eth_estimateGas for contract call", async function () { 54 | const contract = new context.web3.eth.Contract([TEST_CONTRACT_ABI], FIRST_CONTRACT_ADDRESS, { 55 | from: GENESIS_ACCOUNT, 56 | gasPrice: "0x01", 57 | }); 58 | 59 | expect(await contract.methods.multiply(3).estimateGas()).to.equal(21204); 60 | }); 61 | 62 | it("eth_estimateGas without gas_limit should pass", async function () { 63 | const contract = new context.web3.eth.Contract([TEST_CONTRACT_ABI], FIRST_CONTRACT_ADDRESS, { 64 | from: GENESIS_ACCOUNT 65 | }); 66 | 67 | expect(await contract.methods.multiply(3).estimateGas()).to.equal(21204); 68 | }); 69 | 70 | }); 71 | -------------------------------------------------------------------------------- /tests/gas-tests/test/test-contract.js: -------------------------------------------------------------------------------- 1 | const expect = require("chai").expect 2 | const step = require("mocha-steps").step 3 | const Web3 = require("web3") 4 | const execSync = require("child_process").execSync 5 | 6 | const TIMEOUT = require("../truffle-config").mocha.timeout 7 | const cache = require("../build/contracts/Cache.json") 8 | const ballot = require("../build/contracts/Ballot.json") 9 | 10 | const web3Clover = new Web3("http://localhost:8545") 11 | const web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/bd6d2612b6c8462a99385dc5c89cfd41")) 12 | const GENESIS_ACCOUNT = "0xe6206C7f064c7d77C6d8e3eD8601c9AA435419cE" 13 | const GENESIS_ACCOUNT_PRIVATE_KEY = "0xa504b64992e478a6846670237a68ad89b6e42e90de0490273e28e74f084c03c8" 14 | 15 | async function estimateGas(web3, abi, bytecode, arguments) { 16 | let contract = new web3.eth.Contract(abi) 17 | let gas = await contract.deploy({data: bytecode, arguments: arguments}).estimateGas({ 18 | from: GENESIS_ACCOUNT 19 | }) 20 | return gas 21 | } 22 | 23 | async function deployContract(web3, abi, bytecode, arguments) { 24 | let contract = new web3.eth.Contract(abi) 25 | let transaction = contract.deploy({data: bytecode, arguments: arguments}) 26 | let gas = await transaction.estimateGas({ 27 | from: GENESIS_ACCOUNT 28 | }) 29 | let options = { 30 | value: "0x00", 31 | data: transaction.encodeABI(), 32 | gas : gas 33 | } 34 | let signedTransaction = await web3.eth.accounts.signTransaction(options, GENESIS_ACCOUNT_PRIVATE_KEY) 35 | let result = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) 36 | return result 37 | } 38 | 39 | describe("Test contract", () => { 40 | /*it('should compile contract successfully', async () => { 41 | execSync('truffle compile'); 42 | }).timeout(TIMEOUT)*/ 43 | step("Estimate contract gas should be same", async function () { 44 | const arguments = [3] 45 | let cloverGas = await estimateGas(web3Clover, ballot.abi, ballot.bytecode, arguments) 46 | let gas = await estimateGas(web3, ballot.abi, ballot.bytecode, arguments) 47 | console.log(`clover gas: ${cloverGas}, eth gas: ${gas}`) 48 | expect(cloverGas).to.equal(gas); 49 | }).timeout(TIMEOUT) 50 | 51 | it.skip("Deploy contract (uint constructor) should succeed", async () => { 52 | const arguments = [3] 53 | let cloverContract = await deployContract(web3Clover, ballot.abi, ballot.bytecode, arguments) 54 | let contract = await deployContract(web3, ballot.abi, ballot.bytecode, arguments) 55 | console.log('clover contract deployed successfully: ', cloverContract) 56 | expect(cloverContract.gasUsed).to.equal(contract.gasUsed); 57 | }).timeout(TIMEOUT) 58 | 59 | it.skip("Deploy contract (empty constructor) should succeed", async () => { 60 | const arguments = [] 61 | let cloverContract = await deployContract(web3Clover, cache.abi, cache.bytecode, arguments) 62 | let contract = await deployContract(web3, cache.abi, cache.bytecode, arguments) 63 | console.log('clover contract deployed successfully: ', cloverContract) 64 | expect(cloverContract.gasUsed).to.equal(contract.gasUsed); 65 | }).timeout(TIMEOUT) 66 | }); 67 | -------------------------------------------------------------------------------- /tests/gas-tests/solc/Ballot.bin: -------------------------------------------------------------------------------- 1 | 608060405234801561001057600080fd5b506040516106a03803806106a08339818101604052602081101561003357600080fd5b8101908080519060200190929190505050336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506002600160008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000181905550806002816100fb9190610102565b5050610155565b81548183558181111561012957818360005260206000209182019101610128919061012e565b5b505050565b61015291905b8082111561014e5760008082016000905550600101610134565b5090565b90565b61053c806101646000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80630121b93f14610046578063609ff1bd146100745780639e7b8d6114610092575b600080fd5b6100726004803603602081101561005c57600080fd5b81019080803590602001909291905050506100d6565b005b61007c61026f565b6040518082815260200191505060405180910390f35b6100d4600480360360208110156100a857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102de565b005b6000600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600001541415610194576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f486173206e6f20726967687420746f20766f746500000000000000000000000081525060200191505060405180910390fd5b8060010160009054906101000a900460ff1615610219576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f416c726561647920766f7465642e00000000000000000000000000000000000081525060200191505060405180910390fd5b60018160010160006101000a81548160ff02191690831515021790555081816002018190555080600001546002838154811061025157fe5b90600052602060002001600001600082825401925050819055505050565b6000806000905060008090505b6002805490508110156102d957816002828154811061029757fe5b906000526020600020016000015411156102cc57600281815481106102b857fe5b906000526020600020016000015491508092505b808060010191505061027c565b505090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610383576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806104e06028913960400191505060405180910390fd5b600160008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010160009054906101000a900460ff1615610446576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f54686520766f74657220616c726561647920766f7465642e000000000000000081525060200191505060405180910390fd5b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001541461049557600080fd5b60018060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001819055505056fe4f6e6c79206368616972706572736f6e2063616e206769766520726967687420746f20766f74652ea265627a7a723158203b913d22a26a1b073ac937d6577fca807a7c4dc9324878a5aaae86c5294dc36d64736f6c63430005100032 -------------------------------------------------------------------------------- /tests/common/clover-rpc.js: -------------------------------------------------------------------------------- 1 | const cloverRpc = { 2 | incentive: { 3 | getAllPools: { 4 | description: 'get all pools', 5 | params: [], 6 | type: 'Vec<(CurrencyTypeEnum, CurrencyTypeEnum, String, String)>', 7 | }, 8 | }, 9 | clover: { 10 | getCurrencies: { 11 | description: 'get currencies', 12 | params: [], 13 | type: 'Vec<(CurrencyInfo)>', 14 | }, 15 | getBalance: { 16 | description: 'get balance', 17 | params: [ 18 | { 19 | name: 'account', 20 | type: 'String', 21 | }, 22 | { 23 | name: 'currencyId', 24 | type: 'CurrencyTypeEnum', 25 | isOptional: true, 26 | }, 27 | ], 28 | type: 'Vec<(CurrencyTypeEnum, String)>', 29 | }, 30 | getLiquidity: { 31 | description: 'get liquidity', 32 | params: [ 33 | { 34 | name: 'account', 35 | type: 'String', 36 | isOptional: true, 37 | }, 38 | ], 39 | type: 'Vec<(CurrencyTypeEnum, CurrencyTypeEnum, String, String, String, String, String)>', 40 | }, 41 | currencyPair: { 42 | description: 'currency pairs', 43 | params: [], 44 | type: 'Vec<(CurrencyTypeEnum, CurrencyTypeEnum)>', 45 | }, 46 | targetAmountAvailable: { 47 | description: 'target amount available', 48 | params: [ 49 | { 50 | name: 'tokenType', 51 | type: 'CurrencyTypeEnum', 52 | }, 53 | { 54 | name: 'targetTokenType', 55 | type: 'CurrencyTypeEnum', 56 | }, 57 | { 58 | name: 'amount', 59 | type: 'Balance', 60 | }, 61 | ], 62 | type: 'SwapResultInfo', 63 | }, 64 | supplyAmountNeeded: { 65 | description: 'supply amount needed', 66 | params: [ 67 | { 68 | name: 'tokenType', 69 | type: 'CurrencyTypeEnum', 70 | }, 71 | { 72 | name: 'targetTokenType', 73 | type: 'CurrencyTypeEnum', 74 | }, 75 | { 76 | name: 'amount', 77 | type: 'Balance', 78 | }, 79 | ], 80 | type: 'SwapResultInfo', 81 | }, 82 | toAddLiquidity: { 83 | description: 'to add liquidity', 84 | params: [ 85 | { 86 | name: 'fromTokenType', 87 | type: 'CurrencyTypeEnum', 88 | }, 89 | { 90 | name: 'toTokenType', 91 | type: 'CurrencyTypeEnum', 92 | }, 93 | { 94 | name: 'amountFrom', 95 | type: 'Balance', 96 | }, 97 | { 98 | name: 'amountTo', 99 | type: 'Balance', 100 | }, 101 | ], 102 | type: 'Vec', 103 | }, 104 | 105 | getAccountStakingInfo: { 106 | description: 'deposited token', 107 | params: [ 108 | { 109 | name: 'account', 110 | type: 'String', 111 | }, 112 | { 113 | name: 'currency_first', 114 | type: 'CurrencyTypeEnum', 115 | }, 116 | { 117 | name: 'currency_second', 118 | type: 'CurrencyTypeEnum', 119 | }, 120 | ], 121 | type: 'Vec', 122 | }, 123 | }, 124 | }; 125 | 126 | module.exports = cloverRpc; 127 | -------------------------------------------------------------------------------- /tests/test-revert-receipt.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | 3 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 4 | 5 | describeWithClover("Clover RPC (Constructor Revert)", (context) => { 6 | // ``` 7 | // pragma solidity >=0.4.22 <0.7.0; 8 | // 9 | // contract WillFail { 10 | // constructor() public { 11 | // require(false); 12 | // } 13 | // } 14 | // ``` 15 | const FAIL_BYTECODE = '6080604052348015600f57600080fd5b506000601a57600080fd5b603f8060276000396000f3fe6080604052600080fdfea26469706673582212209f2bb2a4cf155a0e7b26bd34bb01e9b645a92c82e55c5dbdb4b37f8c326edbee64736f6c63430006060033'; 16 | const GOOD_BYTECODE = '6080604052348015600f57600080fd5b506001601a57600080fd5b603f8060276000396000f3fe6080604052600080fdfea2646970667358221220c70bc8b03cdfdf57b5f6c4131b836f9c2c4df01b8202f530555333f2a00e4b8364736f6c63430006060033'; 17 | 18 | it("should provide a tx receipt after successful deployment", async function () { 19 | this.timeout(15000); 20 | const GOOD_TX_HASH = '0xae813c533aac0719fbca4db6e3bb05cfb5859bdeaaa7dc5c9dbd24083301be8d'; 21 | 22 | const tx = await context.web3.eth.accounts.signTransaction( 23 | { 24 | from: GENESIS_ACCOUNT, 25 | data: GOOD_BYTECODE, 26 | value: "0x00", 27 | gasPrice: "0x01", 28 | gas: "0x100000", 29 | }, 30 | GENESIS_ACCOUNT_PRIVATE_KEY 31 | ); 32 | 33 | expect( 34 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]) 35 | ).to.deep.equal({ 36 | id: 1, 37 | jsonrpc: "2.0", 38 | result: GOOD_TX_HASH, 39 | }); 40 | 41 | // Verify the receipt exists after the block is created 42 | await createAndFinalizeBlock(context.web3); 43 | const receipt = await context.web3.eth.getTransactionReceipt(GOOD_TX_HASH); 44 | expect(receipt).to.include({ 45 | blockNumber: 1, 46 | contractAddress: '0xC2Bf5F29a4384b1aB0C063e1c666f02121B6084a', 47 | cumulativeGasUsed: 67231, 48 | from: '0x6be02d1d3665660d22ff9624b7be0551ee1ac91b', 49 | gasUsed: 67231, 50 | to: null, 51 | transactionHash: '0xae813c533aac0719fbca4db6e3bb05cfb5859bdeaaa7dc5c9dbd24083301be8d', 52 | transactionIndex: 0, 53 | status: true 54 | }); 55 | }); 56 | 57 | it("should provide a tx receipt after failed deployment", async function () { 58 | this.timeout(15000); 59 | // Transaction hash depends on which nonce we're using 60 | //const FAIL_TX_HASH = '0x89a956c4631822f407b3af11f9251796c276655860c892919f848699ed570a8d'; //nonce 1 61 | const FAIL_TX_HASH = '0x640df9deb183d565addc45bdc8f95b30c7c03ce7e69df49456be9929352e4347'; //nonce 2 62 | 63 | const tx = await context.web3.eth.accounts.signTransaction( 64 | { 65 | from: GENESIS_ACCOUNT, 66 | data: FAIL_BYTECODE, 67 | value: "0x00", 68 | gasPrice: "0x01", 69 | gas: "0x100000", 70 | }, 71 | GENESIS_ACCOUNT_PRIVATE_KEY 72 | ); 73 | 74 | expect( 75 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]) 76 | ).to.deep.equal({ 77 | id: 1, 78 | jsonrpc: "2.0", 79 | result: FAIL_TX_HASH, 80 | }); 81 | 82 | await createAndFinalizeBlock(context.web3); 83 | const receipt = await context.web3.eth.getTransactionReceipt(FAIL_TX_HASH); 84 | expect(receipt).to.include({ 85 | blockNumber: 2, 86 | contractAddress: '0x5c4242beB94dE30b922f57241f1D02f36e906915', 87 | cumulativeGasUsed: 54600, 88 | from: '0x6be02d1d3665660d22ff9624b7be0551ee1ac91b', 89 | gasUsed: 54600, 90 | to: null, 91 | transactionHash: '0x640df9deb183d565addc45bdc8f95b30c7c03ce7e69df49456be9929352e4347', 92 | transactionIndex: 0, 93 | status: false 94 | }); 95 | }); 96 | }); 97 | -------------------------------------------------------------------------------- /tests/inner-contract-tests/test/test-inner-contract.js: -------------------------------------------------------------------------------- 1 | const expect = require("chai").expect 2 | const step = require("mocha-steps").step 3 | const Web3 = require("web3") 4 | 5 | const TIMEOUT = require("../truffle-config").mocha.timeout 6 | const demo1 = require("../build/contracts/Demo1.json") 7 | const demo2 = require("../build/contracts/Demo2.json") 8 | 9 | const web3Clover = new Web3("http://localhost:8545") 10 | //const web3Clover = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/bd6d2612b6c8462a99385dc5c89cfd41")) 11 | const GENESIS_ACCOUNT = "0xe6206C7f064c7d77C6d8e3eD8601c9AA435419cE" 12 | const GENESIS_ACCOUNT_PRIVATE_KEY = "0xa504b64992e478a6846670237a68ad89b6e42e90de0490273e28e74f084c03c8" 13 | 14 | async function deployContract(web3, abi, bytecode, arguments) { 15 | let contract = new web3.eth.Contract(abi) 16 | let transaction = contract.deploy({data: bytecode, arguments: arguments}) 17 | let gas = await transaction.estimateGas({ 18 | from: GENESIS_ACCOUNT 19 | }) 20 | let options = { 21 | value: "0x00", 22 | data: transaction.encodeABI(), 23 | gas : gas 24 | } 25 | let signedTransaction = await web3.eth.accounts.signTransaction(options, GENESIS_ACCOUNT_PRIVATE_KEY) 26 | let result = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) 27 | return result 28 | } 29 | 30 | describe("Test contract", () => { 31 | let deployDemo1; 32 | step("Deploy contract (demo 1) should succeed", async () => { 33 | deployDemo1 = await deployContract(web3Clover, demo1.abi, demo1.bytecode, []) 34 | console.log('demo1 deployed successfully: ', deployDemo1) 35 | 36 | /**const demo1Contract = new web3Clover.eth.Contract(demo1.abi, deployDemo1.contractAddress) 37 | const tx_builder = demo1Contract.methods.setData(2) 38 | let gas = await tx_builder.estimateGas({ 39 | from: GENESIS_ACCOUNT, 40 | }) 41 | console.log(gas) 42 | const signTransaction = { 43 | gas: gas, 44 | gasPrice: web3Clover.utils.toWei("1", "gwei"), 45 | data: tx_builder.encodeABI(), 46 | from: GENESIS_ACCOUNT, 47 | to: deployDemo1.contractAddress 48 | } 49 | 50 | let signedTransaction = await web3Clover.eth.accounts.signTransaction(signTransaction, GENESIS_ACCOUNT_PRIVATE_KEY) 51 | let receipt = await web3Clover.eth.sendSignedTransaction(signedTransaction.rawTransaction) 52 | console.log(receipt)**/ 53 | }).timeout(TIMEOUT) 54 | 55 | step("Deploy contract (demo 2) should succeed", async () => { 56 | let deployDemo2 = await deployContract(web3Clover, demo2.abi, demo2.bytecode, []) 57 | console.log('demo2 deployed successfully: ', deployDemo2) 58 | const demo2Contract = new web3Clover.eth.Contract(demo2.abi, deployDemo2.contractAddress) 59 | 60 | const tx_builder = demo2Contract.methods.toSetData(deployDemo1.contractAddress, 5) 61 | let gas = await tx_builder.estimateGas({ 62 | from: GENESIS_ACCOUNT, 63 | }) 64 | 65 | const signTransaction = { 66 | gas: gas, 67 | gasPrice: web3Clover.utils.toWei("1", "gwei"), 68 | data: tx_builder.encodeABI(), 69 | from: GENESIS_ACCOUNT, 70 | to: deployDemo2.contractAddress 71 | } 72 | 73 | let signedTransaction = await web3Clover.eth.accounts.signTransaction(signTransaction, GENESIS_ACCOUNT_PRIVATE_KEY) 74 | let receipt = await web3Clover.eth.sendSignedTransaction(signedTransaction.rawTransaction) 75 | console.log(receipt) 76 | }).timeout(TIMEOUT) 77 | }); 78 | -------------------------------------------------------------------------------- /tests/test-contract-methods.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | 3 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 4 | import { AbiItem } from "web3-utils"; 5 | 6 | describeWithClover("Clover RPC (Contract Methods)", (context) => { 7 | // Solidity: contract test { function multiply(uint a) public pure returns(uint d) {return a * 7;}} 8 | const TEST_CONTRACT_BYTECODE = 9 | "0x6080604052348015600f57600080fd5b5060ae8061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063c6888fa114602d575b600080fd5b605660048036036020811015604157600080fd5b8101908080359060200190929190505050606c565b6040518082815260200191505060405180910390f35b600060078202905091905056fea265627a7a72315820f06085b229f27f9ad48b2ff3dd9714350c1698a37853a30136fa6c5a7762af7364736f6c63430005110032"; 10 | 11 | const TEST_CONTRACT_ABI = { 12 | constant: true, 13 | inputs: [{ internalType: "uint256", name: "a", type: "uint256" }], 14 | name: "multiply", 15 | outputs: [{ internalType: "uint256", name: "d", type: "uint256" }], 16 | payable: false, 17 | stateMutability: "pure", 18 | type: "function", 19 | } as AbiItem; 20 | 21 | const FIRST_CONTRACT_ADDRESS = "0xc2bf5f29a4384b1ab0c063e1c666f02121b6084a"; // Those test are ordered. In general this should be avoided, but due to the time it takes // to spin up a frontier node, it saves a lot of time. 22 | 23 | before("create the contract", async function () { 24 | this.timeout(15000); 25 | const tx = await context.web3.eth.accounts.signTransaction( 26 | { 27 | from: GENESIS_ACCOUNT, 28 | data: TEST_CONTRACT_BYTECODE, 29 | value: "0x00", 30 | gasPrice: "0x01", 31 | gas: "0x100000", 32 | }, 33 | GENESIS_ACCOUNT_PRIVATE_KEY 34 | ); 35 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 36 | await createAndFinalizeBlock(context.web3); 37 | }); 38 | 39 | it("get transaction by hash", async () => { 40 | const latestBlock = await context.web3.eth.getBlock("latest"); 41 | expect(latestBlock.transactions.length).to.equal(1); 42 | 43 | const tx_hash = latestBlock.transactions[0]; 44 | const tx = await context.web3.eth.getTransaction(tx_hash); 45 | expect(tx.hash).to.equal(tx_hash); 46 | }); 47 | 48 | it("should return contract method result", async function () { 49 | const contract = new context.web3.eth.Contract([TEST_CONTRACT_ABI], FIRST_CONTRACT_ADDRESS, { 50 | from: GENESIS_ACCOUNT, 51 | gasPrice: "0x01", 52 | }); 53 | 54 | expect(await contract.methods.multiply(3).call()).to.equal("21"); 55 | }); 56 | 57 | // Requires error handling 58 | it("should fail for missing parameters", async function () { 59 | const contract = new context.web3.eth.Contract([{ ...TEST_CONTRACT_ABI, inputs: [] }], FIRST_CONTRACT_ADDRESS, { 60 | from: GENESIS_ACCOUNT, 61 | gasPrice: "0x01", 62 | }); 63 | await contract.methods 64 | .multiply() 65 | .call() 66 | .catch((err) => 67 | expect(err.message).to.equal(`Returned error: evm revert: Reverted`) 68 | ); 69 | }); 70 | 71 | // Requires error handling 72 | it("should fail for too many parameters", async function () { 73 | const contract = new context.web3.eth.Contract( 74 | [ 75 | { 76 | ...TEST_CONTRACT_ABI, 77 | inputs: [ 78 | { internalType: "uint256", name: "a", type: "uint256" }, 79 | { internalType: "uint256", name: "b", type: "uint256" }, 80 | ], 81 | }, 82 | ], 83 | FIRST_CONTRACT_ADDRESS, 84 | { 85 | from: GENESIS_ACCOUNT, 86 | gasPrice: "0x01", 87 | } 88 | ); 89 | await contract.methods 90 | .multiply(3, 4) 91 | .call() 92 | .catch((err) => 93 | expect(err.message).to.equal(`Returned error: evm revert: Reverted`) 94 | ); 95 | }); 96 | 97 | // Requires error handling 98 | it("should fail for invalid parameters", async function () { 99 | const contract = new context.web3.eth.Contract( 100 | [{ ...TEST_CONTRACT_ABI, inputs: [{ internalType: "address", name: "a", type: "address" }] }], 101 | FIRST_CONTRACT_ADDRESS, 102 | { from: GENESIS_ACCOUNT, gasPrice: "0x01" } 103 | ); 104 | await contract.methods 105 | .multiply("0x0123456789012345678901234567890123456789") 106 | .call() 107 | .catch((err) => 108 | expect(err.message).to.equal(`Returned error: evm revert: Reverted`) 109 | ); 110 | }); 111 | }); 112 | -------------------------------------------------------------------------------- /tests/gas-tests/truffle-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Use this file to configure your truffle project. It's seeded with some 3 | * common settings for different networks and features like migrations, 4 | * compilation and testing. Uncomment the ones you need or modify 5 | * them to suit your project as necessary. 6 | * 7 | * More information about configuration can be found at: 8 | * 9 | * trufflesuite.com/docs/advanced/configuration 10 | * 11 | * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider) 12 | * to sign your transactions before they're sent to a remote public node. Infura accounts 13 | * are available for free at: infura.io/register. 14 | * 15 | * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate 16 | * public/private key pairs. If you're publishing your code to GitHub make sure you load this 17 | * phrase from a file you've .gitignored so it doesn't accidentally become public. 18 | * 19 | */ 20 | 21 | // const HDWalletProvider = require('@truffle/hdwallet-provider'); 22 | // const infuraKey = "fj4jll3k....."; 23 | // 24 | // const fs = require('fs'); 25 | // const mnemonic = fs.readFileSync(".secret").toString().trim(); 26 | 27 | module.exports = { 28 | /** 29 | * Networks define how you connect to your ethereum client and let you set the 30 | * defaults web3 uses to send transactions. If you don't specify one truffle 31 | * will spin up a development blockchain for you on port 9545 when you 32 | * run `develop` or `test`. You can ask a truffle command to use a specific 33 | * network from the command line, e.g 34 | * 35 | * $ truffle test --network 36 | */ 37 | 38 | networks: { 39 | // Useful for testing. The `development` name is special - truffle uses it by default 40 | // if it's defined here and no other network is specified at the command line. 41 | // You should run a client (like ganache-cli, geth or parity) in a separate terminal 42 | // tab if you use this network and you must also set the `host`, `port` and `network_id` 43 | // options below to some value. 44 | // 45 | // development: { 46 | // host: "127.0.0.1", // Localhost (default: none) 47 | // port: 8545, // Standard Ethereum port (default: none) 48 | // network_id: "*", // Any network (default: none) 49 | // }, 50 | // Another network with more advanced options... 51 | // advanced: { 52 | // port: 8777, // Custom port 53 | // network_id: 1342, // Custom network 54 | // gas: 8500000, // Gas sent with each transaction (default: ~6700000) 55 | // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) 56 | // from:
, // Account to send txs from (default: accounts[0]) 57 | // websockets: true // Enable EventEmitter interface for web3 (default: false) 58 | // }, 59 | // Useful for deploying to a public network. 60 | // NB: It's important to wrap the provider as a function. 61 | // ropsten: { 62 | // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), 63 | // network_id: 3, // Ropsten's id 64 | // gas: 5500000, // Ropsten has a lower block limit than mainnet 65 | // confirmations: 2, // # of confs to wait between deployments. (default: 0) 66 | // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 67 | // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) 68 | // }, 69 | // Useful for private networks 70 | // private: { 71 | // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), 72 | // network_id: 2111, // This network is yours, in the cloud. 73 | // production: true // Treats this network as if it was a public net. (default: false) 74 | // } 75 | }, 76 | 77 | // Set default mocha options here, use special reporters etc. 78 | mocha: { 79 | timeout: 100000 80 | }, 81 | 82 | // Configure your compilers 83 | compilers: { 84 | solc: { 85 | version: "0.5.16", // Fetch exact version from solc-bin (default: truffle's version) 86 | // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) 87 | settings: { // See the solidity docs for advice about optimization and evmVersion 88 | optimizer: { 89 | enabled: false, 90 | runs: 200 91 | }, 92 | evmVersion: "istanbul" 93 | } 94 | } 95 | } 96 | }; 97 | -------------------------------------------------------------------------------- /tests/e2e-tests/truffle-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Use this file to configure your truffle project. It's seeded with some 3 | * common settings for different networks and features like migrations, 4 | * compilation and testing. Uncomment the ones you need or modify 5 | * them to suit your project as necessary. 6 | * 7 | * More information about configuration can be found at: 8 | * 9 | * trufflesuite.com/docs/advanced/configuration 10 | * 11 | * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider) 12 | * to sign your transactions before they're sent to a remote public node. Infura accounts 13 | * are available for free at: infura.io/register. 14 | * 15 | * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate 16 | * public/private key pairs. If you're publishing your code to GitHub make sure you load this 17 | * phrase from a file you've .gitignored so it doesn't accidentally become public. 18 | * 19 | */ 20 | 21 | // const HDWalletProvider = require('@truffle/hdwallet-provider'); 22 | // const infuraKey = "fj4jll3k....."; 23 | // 24 | // const fs = require('fs'); 25 | // const mnemonic = fs.readFileSync(".secret").toString().trim(); 26 | 27 | module.exports = { 28 | /** 29 | * Networks define how you connect to your ethereum client and let you set the 30 | * defaults web3 uses to send transactions. If you don't specify one truffle 31 | * will spin up a development blockchain for you on port 9545 when you 32 | * run `develop` or `test`. You can ask a truffle command to use a specific 33 | * network from the command line, e.g 34 | * 35 | * $ truffle test --network 36 | */ 37 | 38 | networks: { 39 | // Useful for testing. The `development` name is special - truffle uses it by default 40 | // if it's defined here and no other network is specified at the command line. 41 | // You should run a client (like ganache-cli, geth or parity) in a separate terminal 42 | // tab if you use this network and you must also set the `host`, `port` and `network_id` 43 | // options below to some value. 44 | // 45 | // development: { 46 | // host: "127.0.0.1", // Localhost (default: none) 47 | // port: 8545, // Standard Ethereum port (default: none) 48 | // network_id: "*", // Any network (default: none) 49 | // }, 50 | // Another network with more advanced options... 51 | // advanced: { 52 | // port: 8777, // Custom port 53 | // network_id: 1342, // Custom network 54 | // gas: 8500000, // Gas sent with each transaction (default: ~6700000) 55 | // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) 56 | // from:
, // Account to send txs from (default: accounts[0]) 57 | // websockets: true // Enable EventEmitter interface for web3 (default: false) 58 | // }, 59 | // Useful for deploying to a public network. 60 | // NB: It's important to wrap the provider as a function. 61 | // ropsten: { 62 | // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), 63 | // network_id: 3, // Ropsten's id 64 | // gas: 5500000, // Ropsten has a lower block limit than mainnet 65 | // confirmations: 2, // # of confs to wait between deployments. (default: 0) 66 | // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 67 | // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) 68 | // }, 69 | // Useful for private networks 70 | // private: { 71 | // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), 72 | // network_id: 2111, // This network is yours, in the cloud. 73 | // production: true // Treats this network as if it was a public net. (default: false) 74 | // } 75 | }, 76 | 77 | // Set default mocha options here, use special reporters etc. 78 | mocha: { 79 | timeout: 100000 80 | }, 81 | 82 | // Configure your compilers 83 | compilers: { 84 | solc: { 85 | version: "0.5.16", // Fetch exact version from solc-bin (default: truffle's version) 86 | // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) 87 | // settings: { // See the solidity docs for advice about optimization and evmVersion 88 | // optimizer: { 89 | // enabled: false, 90 | // runs: 200 91 | // }, 92 | // evmVersion: "byzantium" 93 | // } 94 | } 95 | } 96 | }; 97 | -------------------------------------------------------------------------------- /tests/inner-contract-tests/truffle-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Use this file to configure your truffle project. It's seeded with some 3 | * common settings for different networks and features like migrations, 4 | * compilation and testing. Uncomment the ones you need or modify 5 | * them to suit your project as necessary. 6 | * 7 | * More information about configuration can be found at: 8 | * 9 | * trufflesuite.com/docs/advanced/configuration 10 | * 11 | * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider) 12 | * to sign your transactions before they're sent to a remote public node. Infura accounts 13 | * are available for free at: infura.io/register. 14 | * 15 | * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate 16 | * public/private key pairs. If you're publishing your code to GitHub make sure you load this 17 | * phrase from a file you've .gitignored so it doesn't accidentally become public. 18 | * 19 | */ 20 | 21 | // const HDWalletProvider = require('@truffle/hdwallet-provider'); 22 | // const infuraKey = "fj4jll3k....."; 23 | // 24 | // const fs = require('fs'); 25 | // const mnemonic = fs.readFileSync(".secret").toString().trim(); 26 | 27 | module.exports = { 28 | /** 29 | * Networks define how you connect to your ethereum client and let you set the 30 | * defaults web3 uses to send transactions. If you don't specify one truffle 31 | * will spin up a development blockchain for you on port 9545 when you 32 | * run `develop` or `test`. You can ask a truffle command to use a specific 33 | * network from the command line, e.g 34 | * 35 | * $ truffle test --network 36 | */ 37 | 38 | networks: { 39 | // Useful for testing. The `development` name is special - truffle uses it by default 40 | // if it's defined here and no other network is specified at the command line. 41 | // You should run a client (like ganache-cli, geth or parity) in a separate terminal 42 | // tab if you use this network and you must also set the `host`, `port` and `network_id` 43 | // options below to some value. 44 | // 45 | // development: { 46 | // host: "127.0.0.1", // Localhost (default: none) 47 | // port: 8545, // Standard Ethereum port (default: none) 48 | // network_id: "*", // Any network (default: none) 49 | // }, 50 | // Another network with more advanced options... 51 | // advanced: { 52 | // port: 8777, // Custom port 53 | // network_id: 1342, // Custom network 54 | // gas: 8500000, // Gas sent with each transaction (default: ~6700000) 55 | // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) 56 | // from:
, // Account to send txs from (default: accounts[0]) 57 | // websockets: true // Enable EventEmitter interface for web3 (default: false) 58 | // }, 59 | // Useful for deploying to a public network. 60 | // NB: It's important to wrap the provider as a function. 61 | // ropsten: { 62 | // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), 63 | // network_id: 3, // Ropsten's id 64 | // gas: 5500000, // Ropsten has a lower block limit than mainnet 65 | // confirmations: 2, // # of confs to wait between deployments. (default: 0) 66 | // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 67 | // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) 68 | // }, 69 | // Useful for private networks 70 | // private: { 71 | // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), 72 | // network_id: 2111, // This network is yours, in the cloud. 73 | // production: true // Treats this network as if it was a public net. (default: false) 74 | // } 75 | }, 76 | 77 | // Set default mocha options here, use special reporters etc. 78 | mocha: { 79 | timeout: 10000000 80 | }, 81 | 82 | // Configure your compilers 83 | compilers: { 84 | solc: { 85 | // version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version) 86 | // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) 87 | // settings: { // See the solidity docs for advice about optimization and evmVersion 88 | // optimizer: { 89 | // enabled: false, 90 | // runs: 200 91 | // }, 92 | // evmVersion: "byzantium" 93 | // } 94 | } 95 | } 96 | }; 97 | -------------------------------------------------------------------------------- /tests/util.ts: -------------------------------------------------------------------------------- 1 | import Web3 from "web3"; 2 | import { JsonRpcResponse } from "web3-core-helpers"; 3 | import { spawn, ChildProcess } from "child_process"; 4 | 5 | export const PORT = 19931; 6 | export const RPC_PORT = 19932; 7 | export const WS_PORT = 19933; 8 | 9 | export const DISPLAY_LOG = process.env.CLOVER_LOG || false; 10 | export const CLOVER_LOG = process.env.CLOVER_LOG || "info"; 11 | 12 | export const BINARY_PATH = process.env.CLOVER; 13 | export const SPAWNING_TIME = 60000; 14 | 15 | export const GENESIS_ACCOUNT = "0x6be02d1d3665660d22ff9624b7be0551ee1ac91b"; 16 | export const GENESIS_ACCOUNT_PRIVATE_KEY = "0x99B3C12287537E38C90A9219D4CB074A89A16E9CDB20BF85728EBD97C343E342"; 17 | 18 | export async function customRequest(web3: Web3, method: string, params: any[]) { 19 | return new Promise((resolve, reject) => { 20 | (web3.currentProvider as any).send( 21 | { 22 | jsonrpc: "2.0", 23 | id: 1, 24 | method, 25 | params, 26 | }, 27 | (error: Error | null, result?: JsonRpcResponse) => { 28 | if (error) { 29 | reject( 30 | `Failed to send custom request (${method} (${params.join(",")})): ${ 31 | error.message || error.toString() 32 | }` 33 | ); 34 | } 35 | resolve(result); 36 | } 37 | ); 38 | }); 39 | } 40 | 41 | function sleep(ms) { 42 | return new Promise(resolve => setTimeout(resolve, ms)); 43 | } 44 | 45 | // Wait a block to finalize. 46 | // It will include all previously executed transactions since the last finalized block. 47 | export async function createAndFinalizeBlock(web3: Web3) { 48 | const currentBlock = await web3.eth.getBlockNumber(); 49 | while(true) { 50 | try { 51 | const newBlock = await web3.eth.getBlock(currentBlock + 1); 52 | if (newBlock) { 53 | break; 54 | } 55 | } catch (err) { 56 | await sleep(1000); 57 | } 58 | } 59 | } 60 | 61 | export async function startCloverNode(provider?: string): Promise<{ web3: Web3; binary: ChildProcess }> { 62 | 63 | var web3; 64 | if (!provider || provider == 'http') { 65 | web3 = new Web3(`http://localhost:${RPC_PORT}`); 66 | } 67 | 68 | const cmd = BINARY_PATH; 69 | const args = [ 70 | `--dev`, 71 | `--validator`, 72 | `--execution=Native`, // Faster execution using native 73 | `--rpc-cors=all`, 74 | `--unsafe-rpc-external`, 75 | `--unsafe-ws-external`, 76 | `-l${CLOVER_LOG}`, 77 | `--port=${PORT}`, 78 | `--rpc-port=${RPC_PORT}`, 79 | `--ws-port=${WS_PORT}`, 80 | `--tmp`, 81 | ]; 82 | const binary = spawn(cmd, args); 83 | 84 | binary.on("error", (err) => { 85 | if ((err as any).errno == "ENOENT") { 86 | console.error( 87 | `\x1b[31mMissing Frontier binary (${BINARY_PATH}).\nPlease compile the Clover project:\ncargo build\x1b[0m` 88 | ); 89 | } else { 90 | console.error(err); 91 | } 92 | process.exit(1); 93 | }); 94 | 95 | const binaryLogs = []; 96 | await new Promise((resolve) => { 97 | const timer = setTimeout(() => { 98 | console.error(`\x1b[31m Failed to start Clover Node.\x1b[0m`); 99 | console.error(`Command: ${cmd} ${args.join(" ")}`); 100 | console.error(`Logs:`); 101 | console.error(binaryLogs.map((chunk) => chunk.toString()).join("\n")); 102 | process.exit(1); 103 | }, SPAWNING_TIME - 2000); 104 | 105 | const onData = async (chunk) => { 106 | if (DISPLAY_LOG) { 107 | console.log(chunk.toString()); 108 | } 109 | binaryLogs.push(chunk); 110 | if (chunk.toString().match(/Next epoch starts/)) { 111 | if (!provider || provider == "http") { 112 | // This is needed as the EVM runtime needs to warmup with a first call 113 | await web3.eth.getChainId(); 114 | } 115 | 116 | clearTimeout(timer); 117 | if (!DISPLAY_LOG) { 118 | binary.stderr.off("data", onData); 119 | binary.stdout.off("data", onData); 120 | } 121 | // console.log(`\x1b[31m Starting RPC\x1b[0m`); 122 | resolve(); 123 | } 124 | }; 125 | binary.stderr.on("data", onData); 126 | binary.stdout.on("data", onData); 127 | }); 128 | 129 | if (provider == 'ws') { 130 | web3 = new Web3(`ws://localhost:${WS_PORT}`); 131 | } 132 | 133 | return { web3, binary }; 134 | } 135 | 136 | export function describeWithClover(title: string, cb: (context: { web3: Web3 }) => void, provider?: string) { 137 | describe(title, () => { 138 | let context: { web3: Web3 } = { web3: null }; 139 | let binary: ChildProcess; 140 | // Making sure the Clover node has started 141 | before("Starting Clover Test Node", async function () { 142 | this.timeout(SPAWNING_TIME); 143 | const init = await startCloverNode(provider); 144 | context.web3 = init.web3; 145 | binary = init.binary; 146 | }); 147 | 148 | after(async function () { 149 | //console.log(`\x1b[31m Killing RPC\x1b[0m`); 150 | binary.kill(); 151 | }); 152 | 153 | cb(context); 154 | }); 155 | } 156 | -------------------------------------------------------------------------------- /tests/test-block.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover } from "./util"; 5 | 6 | describeWithClover("Clover RPC (Block)", (context) => { 7 | let previousBlock; 8 | // Those tests are dependant of each other in the given order. 9 | // The reason is to avoid having to restart the node each time 10 | // Running them individually will result in failure 11 | 12 | it("should return genesis block", async function () { 13 | const block = await context.web3.eth.getBlock(0); 14 | expect(block).to.include({ 15 | author: "0x0000000000000000000000000000000000000000", 16 | difficulty: "0", 17 | extraData: "0x", 18 | gasLimit: 0, 19 | gasUsed: 0, 20 | logsBloom: 21 | "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 22 | miner: "0x0000000000000000000000000000000000000000", 23 | number: 0, 24 | receiptsRoot: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", 25 | size: 501, 26 | timestamp: 0, 27 | totalDifficulty: null, 28 | }); 29 | 30 | expect((block as any).sealFields).to.eql([ 31 | "0x0000000000000000000000000000000000000000000000000000000000000000", 32 | "0x0000000000000000", 33 | ]); 34 | expect(block.hash).to.be.a("string").lengthOf(66); 35 | expect(block.parentHash).to.be.a("string").lengthOf(66); 36 | expect(block.timestamp).to.be.a("number"); 37 | }); 38 | 39 | step("should have empty uncles and correct sha3Uncles", async function () { 40 | const block = await context.web3.eth.getBlock(0); 41 | expect(block.uncles).to.be.a("array").empty; 42 | expect(block.sha3Uncles).to.equal("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"); 43 | }); 44 | 45 | step("should have empty transactions and correct transactionRoot", async function () { 46 | const block = await context.web3.eth.getBlock(0); 47 | expect(block.transactions).to.be.a("array").empty; 48 | expect(block).to.include({ 49 | transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", 50 | }); 51 | }); 52 | 53 | let firstBlockCreated = false; 54 | step("should be at block 1 after block production", async function () { 55 | this.timeout(15000); 56 | await createAndFinalizeBlock(context.web3); 57 | expect(await context.web3.eth.getBlockNumber()).to.greaterThan(1); 58 | firstBlockCreated = true; 59 | }); 60 | 61 | step("should have valid timestamp after block production", async function () { 62 | const block = await context.web3.eth.getBlock("latest"); 63 | expect(block.timestamp).to.be.greaterThan(0); 64 | }); 65 | 66 | step("retrieve block information", async function () { 67 | expect(firstBlockCreated).to.be.true; 68 | 69 | const block = await context.web3.eth.getBlock(1); 70 | expect(block).to.include({ 71 | author: "0x15fdd31c61141abd04a99fd6822c8558854ccde3", 72 | difficulty: "0", 73 | extraData: "0x", 74 | gasLimit: 0, 75 | gasUsed: 0, 76 | //hash: "0x14fe6f7c93597f79b901f8b5d7a84277a90915b8d355959b587e18de34f1dc17", 77 | logsBloom: 78 | "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 79 | miner: "0x15fdd31C61141abd04A99FD6822c8558854ccDe3", 80 | number: 1, 81 | //parentHash: "0x04540257811b46d103d9896e7807040e7de5080e285841c5430d1a81588a0ce4", 82 | receiptsRoot: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", 83 | size: 507, 84 | totalDifficulty: null, 85 | //transactions: [], 86 | transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", 87 | //uncles: [] 88 | }); 89 | previousBlock = block; 90 | 91 | expect(block.transactions).to.be.a("array").empty; 92 | expect(block.uncles).to.be.a("array").empty; 93 | expect((block as any).sealFields).to.eql([ 94 | "0x0000000000000000000000000000000000000000000000000000000000000000", 95 | "0x0000000000000000", 96 | ]); 97 | expect(block.hash).to.be.a("string").lengthOf(66); 98 | expect(block.parentHash).to.be.a("string").lengthOf(66); 99 | expect(block.timestamp).to.be.a("number"); 100 | }); 101 | 102 | step("get block by hash", async function() { 103 | const latest_block = await context.web3.eth.getBlock("latest"); 104 | const block = await context.web3.eth.getBlock(latest_block.hash); 105 | expect(block.hash).to.be.eq(latest_block.hash); 106 | }); 107 | 108 | step("get block by number", async function() { 109 | const block = await context.web3.eth.getBlock(1); 110 | expect(block).not.null; 111 | }); 112 | 113 | step("should include previous block hash as parent", async function () { 114 | await createAndFinalizeBlock(context.web3); 115 | const block = await context.web3.eth.getBlock(2); 116 | expect(block.hash).to.not.equal(previousBlock.hash); 117 | expect(block.parentHash).to.equal(previousBlock.hash); 118 | }); 119 | }); 120 | -------------------------------------------------------------------------------- /tests/gas-tests/solc/Ballot.opcode: -------------------------------------------------------------------------------- 1 | PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x40 MLOAD PUSH2 0x6A0 CODESIZE SUB DUP1 PUSH2 0x6A0 DUP4 CODECOPY DUP2 DUP2 ADD PUSH1 0x40 MSTORE PUSH1 0x20 DUP2 LT ISZERO PUSH2 0x33 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP2 ADD SWAP1 DUP1 DUP1 MLOAD SWAP1 PUSH1 0x20 ADD SWAP1 SWAP3 SWAP2 SWAP1 POP POP POP CALLER PUSH1 0x0 DUP1 PUSH2 0x100 EXP DUP2 SLOAD DUP2 PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF MUL NOT AND SWAP1 DUP4 PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND MUL OR SWAP1 SSTORE POP PUSH1 0x2 PUSH1 0x1 PUSH1 0x0 DUP1 PUSH1 0x0 SWAP1 SLOAD SWAP1 PUSH2 0x100 EXP SWAP1 DIV PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 KECCAK256 PUSH1 0x0 ADD DUP2 SWAP1 SSTORE POP DUP1 PUSH1 0x2 DUP2 PUSH2 0xFB SWAP2 SWAP1 PUSH2 0x102 JUMP JUMPDEST POP POP PUSH2 0x155 JUMP JUMPDEST DUP2 SLOAD DUP2 DUP4 SSTORE DUP2 DUP2 GT ISZERO PUSH2 0x129 JUMPI DUP2 DUP4 PUSH1 0x0 MSTORE PUSH1 0x20 PUSH1 0x0 KECCAK256 SWAP2 DUP3 ADD SWAP2 ADD PUSH2 0x128 SWAP2 SWAP1 PUSH2 0x12E JUMP JUMPDEST JUMPDEST POP POP POP JUMP JUMPDEST PUSH2 0x152 SWAP2 SWAP1 JUMPDEST DUP1 DUP3 GT ISZERO PUSH2 0x14E JUMPI PUSH1 0x0 DUP1 DUP3 ADD PUSH1 0x0 SWAP1 SSTORE POP PUSH1 0x1 ADD PUSH2 0x134 JUMP JUMPDEST POP SWAP1 JUMP JUMPDEST SWAP1 JUMP JUMPDEST PUSH2 0x53C DUP1 PUSH2 0x164 PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x10 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH2 0x41 JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0x121B93F EQ PUSH2 0x46 JUMPI DUP1 PUSH4 0x609FF1BD EQ PUSH2 0x74 JUMPI DUP1 PUSH4 0x9E7B8D61 EQ PUSH2 0x92 JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH2 0x72 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH2 0x5C JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP2 ADD SWAP1 DUP1 DUP1 CALLDATALOAD SWAP1 PUSH1 0x20 ADD SWAP1 SWAP3 SWAP2 SWAP1 POP POP POP PUSH2 0xD6 JUMP JUMPDEST STOP JUMPDEST PUSH2 0x7C PUSH2 0x26F JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH2 0xD4 PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH2 0xA8 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP2 ADD SWAP1 DUP1 DUP1 CALLDATALOAD PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND SWAP1 PUSH1 0x20 ADD SWAP1 SWAP3 SWAP2 SWAP1 POP POP POP PUSH2 0x2DE JUMP JUMPDEST STOP JUMPDEST PUSH1 0x0 PUSH1 0x1 PUSH1 0x0 CALLER PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 KECCAK256 SWAP1 POP PUSH1 0x0 DUP2 PUSH1 0x0 ADD SLOAD EQ ISZERO PUSH2 0x194 JUMPI PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD DUP1 DUP1 PUSH1 0x20 ADD DUP3 DUP2 SUB DUP3 MSTORE PUSH1 0x14 DUP2 MSTORE PUSH1 0x20 ADD DUP1 PUSH32 0x486173206E6F20726967687420746F20766F7465000000000000000000000000 DUP2 MSTORE POP PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST DUP1 PUSH1 0x1 ADD PUSH1 0x0 SWAP1 SLOAD SWAP1 PUSH2 0x100 EXP SWAP1 DIV PUSH1 0xFF AND ISZERO PUSH2 0x219 JUMPI PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD DUP1 DUP1 PUSH1 0x20 ADD DUP3 DUP2 SUB DUP3 MSTORE PUSH1 0xE DUP2 MSTORE PUSH1 0x20 ADD DUP1 PUSH32 0x416C726561647920766F7465642E000000000000000000000000000000000000 DUP2 MSTORE POP PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST PUSH1 0x1 DUP2 PUSH1 0x1 ADD PUSH1 0x0 PUSH2 0x100 EXP DUP2 SLOAD DUP2 PUSH1 0xFF MUL NOT AND SWAP1 DUP4 ISZERO ISZERO MUL OR SWAP1 SSTORE POP DUP2 DUP2 PUSH1 0x2 ADD DUP2 SWAP1 SSTORE POP DUP1 PUSH1 0x0 ADD SLOAD PUSH1 0x2 DUP4 DUP2 SLOAD DUP2 LT PUSH2 0x251 JUMPI INVALID JUMPDEST SWAP1 PUSH1 0x0 MSTORE PUSH1 0x20 PUSH1 0x0 KECCAK256 ADD PUSH1 0x0 ADD PUSH1 0x0 DUP3 DUP3 SLOAD ADD SWAP3 POP POP DUP2 SWAP1 SSTORE POP POP POP JUMP JUMPDEST PUSH1 0x0 DUP1 PUSH1 0x0 SWAP1 POP PUSH1 0x0 DUP1 SWAP1 POP JUMPDEST PUSH1 0x2 DUP1 SLOAD SWAP1 POP DUP2 LT ISZERO PUSH2 0x2D9 JUMPI DUP2 PUSH1 0x2 DUP3 DUP2 SLOAD DUP2 LT PUSH2 0x297 JUMPI INVALID JUMPDEST SWAP1 PUSH1 0x0 MSTORE PUSH1 0x20 PUSH1 0x0 KECCAK256 ADD PUSH1 0x0 ADD SLOAD GT ISZERO PUSH2 0x2CC JUMPI PUSH1 0x2 DUP2 DUP2 SLOAD DUP2 LT PUSH2 0x2B8 JUMPI INVALID JUMPDEST SWAP1 PUSH1 0x0 MSTORE PUSH1 0x20 PUSH1 0x0 KECCAK256 ADD PUSH1 0x0 ADD SLOAD SWAP2 POP DUP1 SWAP3 POP JUMPDEST DUP1 DUP1 PUSH1 0x1 ADD SWAP2 POP POP PUSH2 0x27C JUMP JUMPDEST POP POP SWAP1 JUMP JUMPDEST PUSH1 0x0 DUP1 SWAP1 SLOAD SWAP1 PUSH2 0x100 EXP SWAP1 DIV PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND CALLER PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND EQ PUSH2 0x383 JUMPI PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD DUP1 DUP1 PUSH1 0x20 ADD DUP3 DUP2 SUB DUP3 MSTORE PUSH1 0x28 DUP2 MSTORE PUSH1 0x20 ADD DUP1 PUSH2 0x4E0 PUSH1 0x28 SWAP2 CODECOPY PUSH1 0x40 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST PUSH1 0x1 PUSH1 0x0 DUP3 PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 KECCAK256 PUSH1 0x1 ADD PUSH1 0x0 SWAP1 SLOAD SWAP1 PUSH2 0x100 EXP SWAP1 DIV PUSH1 0xFF AND ISZERO PUSH2 0x446 JUMPI PUSH1 0x40 MLOAD PUSH32 0x8C379A000000000000000000000000000000000000000000000000000000000 DUP2 MSTORE PUSH1 0x4 ADD DUP1 DUP1 PUSH1 0x20 ADD DUP3 DUP2 SUB DUP3 MSTORE PUSH1 0x18 DUP2 MSTORE PUSH1 0x20 ADD DUP1 PUSH32 0x54686520766F74657220616C726561647920766F7465642E0000000000000000 DUP2 MSTORE POP PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 REVERT JUMPDEST PUSH1 0x0 PUSH1 0x1 PUSH1 0x0 DUP4 PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 KECCAK256 PUSH1 0x0 ADD SLOAD EQ PUSH2 0x495 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x1 DUP1 PUSH1 0x0 DUP4 PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND PUSH20 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND DUP2 MSTORE PUSH1 0x20 ADD SWAP1 DUP2 MSTORE PUSH1 0x20 ADD PUSH1 0x0 KECCAK256 PUSH1 0x0 ADD DUP2 SWAP1 SSTORE POP POP JUMP INVALID 0x4F PUSH15 0x6C79206368616972706572736F6E20 PUSH4 0x616E2067 PUSH10 0x76652072696768742074 PUSH16 0x20766F74652EA265627A7A723158203B SWAP2 RETURNDATASIZE 0x22 LOG2 PUSH11 0x1B073AC937D6577FCA807A PUSH29 0x4DC9324878A5AAAE86C5294DC36D64736F6C6343000510003200000000 -------------------------------------------------------------------------------- /tests/e2e-tests/test/test-uniswap.js: -------------------------------------------------------------------------------- 1 | const expect = require("chai").expect 2 | const step = require("mocha-steps").step 3 | const Web3 = require("web3") 4 | const fs = require('fs'); 5 | 6 | const TIMEOUT = require("../truffle-config").mocha.timeout 7 | const web3 = new Web3("wss://api-2.clover.finance") 8 | const GENESIS_ACCOUNT = "0xe6206C7f064c7d77C6d8e3eD8601c9AA435419cE" 9 | // analyst math decrease risk pool citizen hunt unusual little slam fragile arrive 10 | const GENESIS_ACCOUNT_PRIVATE_KEY = "0xa504b64992e478a6846670237a68ad89b6e42e90de0490273e28e74f084c03c8" 11 | const DEPLOY = require("./installation_data.json") 12 | 13 | async function deployContract(deployAccount, deployAccountKey, abi, bytecode, arguments) { 14 | let contract = new web3.eth.Contract(abi) 15 | let transaction = contract.deploy({data: bytecode, arguments: arguments}) 16 | let gas = await transaction.estimateGas({ 17 | from: deployAccount 18 | }) 19 | let options = { 20 | value: "0x00", 21 | data: transaction.encodeABI(), 22 | gasPrice: web3.utils.toWei("50", "gwei"), 23 | gas : gas 24 | } 25 | let signedTransaction = await web3.eth.accounts.signTransaction(options, deployAccountKey) 26 | let receipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) 27 | return receipt 28 | } 29 | 30 | async function transfer(account, etherValue) { 31 | const before = await web3.eth.getBalance(account); 32 | console.log(`before transfer: ${account}, has balance ${web3.utils.fromWei(before, "ether")}`); 33 | const nonce = await web3.eth.getTransactionCount(GENESIS_ACCOUNT); 34 | const signedTransaction = await web3.eth.accounts.signTransaction({ 35 | from: GENESIS_ACCOUNT, 36 | to: account, 37 | value: web3.utils.toWei(etherValue.toString(), "ether"), 38 | gasPrice: web3.utils.toWei("50", "gwei"), 39 | gas: "0x5208", 40 | nonce: nonce 41 | }, GENESIS_ACCOUNT_PRIVATE_KEY); 42 | await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction) 43 | const after = await web3.eth.getBalance(account); 44 | console.log(`after transfer: ${account}, has balance ${web3.utils.fromWei(after, "ether")}`) 45 | } 46 | 47 | function sleep(ms) { 48 | return new Promise(resolve => setTimeout(resolve, ms)); 49 | } 50 | 51 | function write_data(object) { 52 | const message = JSON.stringify(object, null, 4) 53 | return new Promise(function(resolve, reject) { 54 | fs.writeFile("./tests/e2e-tests/test/installation_data.json", message, (err) => { 55 | if (err) throw err; 56 | resolve(); 57 | }); 58 | }); 59 | } 60 | 61 | async function createAndFinalizeBlock() { 62 | const currentBlock = await web3.eth.getBlockNumber() 63 | while(true) { 64 | try { 65 | const newBlock = await web3.eth.getBlock(currentBlock + 1) 66 | if (newBlock) { 67 | break 68 | } 69 | } catch (err) { 70 | await sleep(1000) 71 | } 72 | } 73 | } 74 | 75 | describe("Test transfer", () => { 76 | 77 | step("Deploy uniswap erc 20", async function () { 78 | const json = require("../build/contracts/uni/Uni.json") 79 | const bytecode = json.bytecode 80 | const abi = json.abi 81 | const deployer = DEPLOY.public_key.charlie 82 | const receipt = await deployContract(deployer, DEPLOY.private_key.charlie, abi, bytecode, [deployer, deployer, new Date().getTime()]) 83 | DEPLOY.contract_address.uni = receipt.contractAddress 84 | console.log(`uniswap erc20 token deployed at address: ${receipt.contractAddress}`) 85 | await write_data(DEPLOY) 86 | }).timeout(TIMEOUT) 87 | 88 | step("Deploy uniswap v2 factory", async function () { 89 | const json = require("../build/contracts/UniswapV2Factory.json") 90 | const bytecode = json.bytecode 91 | const abi = json.abi 92 | const deployer = DEPLOY.public_key.alice 93 | const receipt = await deployContract(deployer, DEPLOY.private_key.alice, abi, bytecode, [deployer]) 94 | DEPLOY.contract_address.uniswap_v2_factory = receipt.contractAddress 95 | console.log(`uniswap v2 factory deployed at address: ${receipt.contractAddress}`) 96 | 97 | const contract = new web3.eth.Contract(abi, receipt.contractAddress); 98 | const feeToSetter = await contract.methods.feeToSetter().call() 99 | expect(feeToSetter).to.equal(deployer) 100 | 101 | await write_data(DEPLOY) 102 | }).timeout(TIMEOUT) 103 | 104 | step("Deploy weth", async function () { 105 | const json = require("../build/contracts/WETH.json") 106 | const bytecode = json.bytecode 107 | const abi = json.abi 108 | const deployer = DEPLOY.public_key.alice 109 | const receipt = await deployContract(deployer, DEPLOY.private_key.alice, abi, bytecode, []) 110 | DEPLOY.contract_address.weth = receipt.contractAddress 111 | console.log(`weth deployed at address: ${receipt.contractAddress}`) 112 | 113 | const contract = new web3.eth.Contract(abi, receipt.contractAddress); 114 | const name = await contract.methods.name().call() 115 | const symbol = await contract.methods.symbol().call() 116 | const totalSupply = await contract.methods.totalSupply().call() 117 | console.log(`weth name: ${name}, symbol: ${symbol}, total supply: ${totalSupply}`) 118 | 119 | await write_data(DEPLOY) 120 | }).timeout(TIMEOUT) 121 | 122 | step("Deploy uniswap v2 router", async function () { 123 | const json = require("../build/contracts/UniswapV2Router02.json") 124 | const bytecode = json.bytecode 125 | const abi = json.abi 126 | const deployer = DEPLOY.public_key.alice 127 | const receipt = await deployContract(deployer, DEPLOY.private_key.alice, abi, bytecode, [DEPLOY.contract_address.uniswap_v2_factory, DEPLOY.contract_address.weth]) 128 | DEPLOY.contract_address.uniswap_v2_router = receipt.contractAddress 129 | console.log(`uniswap v2 router deployed at address: ${receipt.contractAddress}`) 130 | 131 | const contract = new web3.eth.Contract(abi, receipt.contractAddress) 132 | const factoryAddr = await contract.methods.factory().call() 133 | const wethAddr = await contract.methods.WETH().call() 134 | expect(factoryAddr).to.equal(DEPLOY.contract_address.uniswap_v2_factory) 135 | expect(wethAddr).to.equal(DEPLOY.contract_address.weth) 136 | console.log(`router with factory address: ${factoryAddr}, and weth address: ${wethAddr}`) 137 | 138 | await write_data(DEPLOY) 139 | }).timeout(TIMEOUT) 140 | 141 | step("Deploy multicall", async function () { 142 | const json = require("../build/contracts/Multicall.json") 143 | const bytecode = json.bytecode 144 | const abi = json.abi 145 | const deployer = DEPLOY.public_key.alice 146 | const receipt = await deployContract(deployer, DEPLOY.private_key.alice, abi, bytecode, []) 147 | DEPLOY.contract_address.multicall = receipt.contractAddress 148 | console.log(`multicall deployed at address: ${receipt.contractAddress}`) 149 | 150 | await write_data(DEPLOY) 151 | }).timeout(TIMEOUT) 152 | 153 | step("Deploy clv", async function () { 154 | const json = require("../build/contracts/CLV.json") 155 | const bytecode = json.bytecode 156 | const abi = json.abi 157 | const deployer = DEPLOY.public_key.alice 158 | const receipt = await deployContract(deployer, DEPLOY.private_key.alice, abi, bytecode, [web3.utils.toWei("50000", "ether")]) 159 | DEPLOY.contract_address.clv = receipt.contractAddress 160 | console.log(`clv deployed at address: ${receipt.contractAddress}`) 161 | 162 | await write_data(DEPLOY) 163 | }).timeout(TIMEOUT) 164 | }); 165 | -------------------------------------------------------------------------------- /tests/test-bloom.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 5 | 6 | describeWithClover("Clover RPC (Bloom)", (context) => { 7 | const TEST_CONTRACT_BYTECODE = 8 | "0x608060405234801561001057600080fd5b50610041337fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff61004660201b60201c565b610291565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156100e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b6101028160025461020960201b610c7c1790919060201c565b60028190555061015d816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461020960201b610c7c1790919060201c565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600080828401905083811015610287576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b610e3a806102a06000396000f3fe608060405234801561001057600080fd5b50600436106100885760003560e01c806370a082311161005b57806370a08231146101fd578063a457c2d714610255578063a9059cbb146102bb578063dd62ed3e1461032157610088565b8063095ea7b31461008d57806318160ddd146100f357806323b872dd146101115780633950935114610197575b600080fd5b6100d9600480360360408110156100a357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610399565b604051808215151515815260200191505060405180910390f35b6100fb6103b7565b6040518082815260200191505060405180910390f35b61017d6004803603606081101561012757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506103c1565b604051808215151515815260200191505060405180910390f35b6101e3600480360360408110156101ad57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061049a565b604051808215151515815260200191505060405180910390f35b61023f6004803603602081101561021357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061054d565b6040518082815260200191505060405180910390f35b6102a16004803603604081101561026b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610595565b604051808215151515815260200191505060405180910390f35b610307600480360360408110156102d157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610662565b604051808215151515815260200191505060405180910390f35b6103836004803603604081101561033757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610680565b6040518082815260200191505060405180910390f35b60006103ad6103a6610707565b848461070f565b6001905092915050565b6000600254905090565b60006103ce848484610906565b61048f846103da610707565b61048a85604051806060016040528060288152602001610d7060289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610440610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b61070f565b600190509392505050565b60006105436104a7610707565b8461053e85600160006104b8610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610c7c90919063ffffffff16565b61070f565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60006106586105a2610707565b8461065385604051806060016040528060258152602001610de160259139600160006105cc610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b61070f565b6001905092915050565b600061067661066f610707565b8484610906565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610795576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180610dbd6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561081b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610d286022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141561098c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180610d986025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610a12576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610d056023913960400191505060405180910390fd5b610a7d81604051806060016040528060268152602001610d4a602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610b10816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610c7c90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610c69576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610c2e578082015181840152602081019050610c13565b50505050905090810190601f168015610c5b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610cfa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72315820c7a5ffabf642bda14700b2de42f8c57b36621af020441df825de45fd2b3e1c5c64736f6c63430005100032"; 9 | 10 | async function sendTransaction(context) { 11 | const tx = await context.web3.eth.accounts.signTransaction( 12 | { 13 | from: GENESIS_ACCOUNT, 14 | data: TEST_CONTRACT_BYTECODE, 15 | value: "0x00", 16 | gasPrice: "0x01", 17 | gas: "0x4F930", 18 | }, 19 | GENESIS_ACCOUNT_PRIVATE_KEY 20 | ); 21 | 22 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 23 | return tx; 24 | } 25 | 26 | step("receipt data should be in bloom", async function () { 27 | let tx = await sendTransaction(context); 28 | await createAndFinalizeBlock(context.web3); 29 | // check transaction bloom 30 | tx = await context.web3.eth.getTransactionReceipt(tx.transactionHash); 31 | expect(context.web3.utils.isInBloom(tx.logsBloom, tx.logs[0].address)).to.be.true; 32 | for(var topic of tx.logs[0].topics) { 33 | expect(context.web3.utils.isInBloom(tx.logsBloom, topic)).to.be.true; 34 | } 35 | // check block bloom 36 | const block = await context.web3.eth.getBlock(tx.blockNumber); 37 | expect(context.web3.utils.isInBloom(block.logsBloom, tx.logs[0].address)).to.be.true; 38 | for(var topic of tx.logs[0].topics) { 39 | expect(context.web3.utils.isInBloom(block.logsBloom, topic)).to.be.true; 40 | } 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/USDC.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Etherscan.io on 2018-08-03 3 | */ 4 | 5 | pragma solidity ^0.4.24; 6 | 7 | // File: zos-lib/contracts/upgradeability/Proxy.sol 8 | 9 | /** 10 | * @title Proxy 11 | * @dev Implements delegation of calls to other contracts, with proper 12 | * forwarding of return values and bubbling of failures. 13 | * It defines a fallback function that delegates all calls to the address 14 | * returned by the abstract _implementation() internal function. 15 | */ 16 | contract Proxy { 17 | /** 18 | * @dev Fallback function. 19 | * Implemented entirely in `_fallback`. 20 | */ 21 | function () payable external { 22 | _fallback(); 23 | } 24 | 25 | /** 26 | * @return The Address of the implementation. 27 | */ 28 | function _implementation() internal view returns (address); 29 | 30 | /** 31 | * @dev Delegates execution to an implementation contract. 32 | * This is a low level function that doesn't return to its internal call site. 33 | * It will return to the external caller whatever the implementation returns. 34 | * @param implementation Address to delegate. 35 | */ 36 | function _delegate(address implementation) internal { 37 | assembly { 38 | // Copy msg.data. We take full control of memory in this inline assembly 39 | // block because it will not return to Solidity code. We overwrite the 40 | // Solidity scratch pad at memory position 0. 41 | calldatacopy(0, 0, calldatasize) 42 | 43 | // Call the implementation. 44 | // out and outsize are 0 because we don't know the size yet. 45 | let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) 46 | 47 | // Copy the returned data. 48 | returndatacopy(0, 0, returndatasize) 49 | 50 | switch result 51 | // delegatecall returns 0 on error. 52 | case 0 { revert(0, returndatasize) } 53 | default { return(0, returndatasize) } 54 | } 55 | } 56 | 57 | /** 58 | * @dev Function that is run as the first thing in the fallback function. 59 | * Can be redefined in derived contracts to add functionality. 60 | * Redefinitions must call super._willFallback(). 61 | */ 62 | function _willFallback() internal { 63 | } 64 | 65 | /** 66 | * @dev fallback implementation. 67 | * Extracted to enable manual triggering. 68 | */ 69 | function _fallback() internal { 70 | _willFallback(); 71 | _delegate(_implementation()); 72 | } 73 | } 74 | 75 | // File: openzeppelin-solidity/contracts/AddressUtils.sol 76 | 77 | /** 78 | * Utility library of inline functions on addresses 79 | */ 80 | library AddressUtils { 81 | 82 | /** 83 | * Returns whether the target address is a contract 84 | * @dev This function will return false if invoked during the constructor of a contract, 85 | * as the code is not actually created until after the constructor finishes. 86 | * @param addr address to check 87 | * @return whether the target address is a contract 88 | */ 89 | function isContract(address addr) internal view returns (bool) { 90 | uint256 size; 91 | // XXX Currently there is no better way to check if there is a contract in an address 92 | // than to check the size of the code at that address. 93 | // See https://ethereum.stackexchange.com/a/14016/36603 94 | // for more details about how this works. 95 | // TODO Check this again before the Serenity release, because all addresses will be 96 | // contracts then. 97 | // solium-disable-next-line security/no-inline-assembly 98 | assembly { size := extcodesize(addr) } 99 | return size > 0; 100 | } 101 | 102 | } 103 | 104 | // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol 105 | 106 | /** 107 | * @title UpgradeabilityProxy 108 | * @dev This contract implements a proxy that allows to change the 109 | * implementation address to which it will delegate. 110 | * Such a change is called an implementation upgrade. 111 | */ 112 | contract UpgradeabilityProxy is Proxy { 113 | /** 114 | * @dev Emitted when the implementation is upgraded. 115 | * @param implementation Address of the new implementation. 116 | */ 117 | event Upgraded(address implementation); 118 | 119 | /** 120 | * @dev Storage slot with the address of the current implementation. 121 | * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is 122 | * validated in the constructor. 123 | */ 124 | bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; 125 | 126 | /** 127 | * @dev Contract constructor. 128 | * @param _implementation Address of the initial implementation. 129 | */ 130 | constructor(address _implementation) public { 131 | assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); 132 | 133 | _setImplementation(_implementation); 134 | } 135 | 136 | /** 137 | * @dev Returns the current implementation. 138 | * @return Address of the current implementation 139 | */ 140 | function _implementation() internal view returns (address impl) { 141 | bytes32 slot = IMPLEMENTATION_SLOT; 142 | assembly { 143 | impl := sload(slot) 144 | } 145 | } 146 | 147 | /** 148 | * @dev Upgrades the proxy to a new implementation. 149 | * @param newImplementation Address of the new implementation. 150 | */ 151 | function _upgradeTo(address newImplementation) internal { 152 | _setImplementation(newImplementation); 153 | emit Upgraded(newImplementation); 154 | } 155 | 156 | /** 157 | * @dev Sets the implementation address of the proxy. 158 | * @param newImplementation Address of the new implementation. 159 | */ 160 | function _setImplementation(address newImplementation) private { 161 | require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); 162 | 163 | bytes32 slot = IMPLEMENTATION_SLOT; 164 | 165 | assembly { 166 | sstore(slot, newImplementation) 167 | } 168 | } 169 | } 170 | 171 | // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol 172 | 173 | /** 174 | * @title AdminUpgradeabilityProxy 175 | * @dev This contract combines an upgradeability proxy with an authorization 176 | * mechanism for administrative tasks. 177 | * All external functions in this contract must be guarded by the 178 | * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity 179 | * feature proposal that would enable this to be done automatically. 180 | */ 181 | contract AdminUpgradeabilityProxy is UpgradeabilityProxy { 182 | /** 183 | * @dev Emitted when the administration has been transferred. 184 | * @param previousAdmin Address of the previous admin. 185 | * @param newAdmin Address of the new admin. 186 | */ 187 | event AdminChanged(address previousAdmin, address newAdmin); 188 | 189 | /** 190 | * @dev Storage slot with the admin of the contract. 191 | * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is 192 | * validated in the constructor. 193 | */ 194 | bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; 195 | 196 | /** 197 | * @dev Modifier to check whether the `msg.sender` is the admin. 198 | * If it is, it will run the function. Otherwise, it will delegate the call 199 | * to the implementation. 200 | */ 201 | modifier ifAdmin() { 202 | if (msg.sender == _admin()) { 203 | _; 204 | } else { 205 | _fallback(); 206 | } 207 | } 208 | 209 | /** 210 | * Contract constructor. 211 | * It sets the `msg.sender` as the proxy administrator. 212 | * @param _implementation address of the initial implementation. 213 | */ 214 | constructor(address _implementation) UpgradeabilityProxy(_implementation) public { 215 | assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); 216 | 217 | _setAdmin(msg.sender); 218 | } 219 | 220 | /** 221 | * @return The address of the proxy admin. 222 | */ 223 | function admin() external view ifAdmin returns (address) { 224 | return _admin(); 225 | } 226 | 227 | /** 228 | * @return The address of the implementation. 229 | */ 230 | function implementation() external view ifAdmin returns (address) { 231 | return _implementation(); 232 | } 233 | 234 | /** 235 | * @dev Changes the admin of the proxy. 236 | * Only the current admin can call this function. 237 | * @param newAdmin Address to transfer proxy administration to. 238 | */ 239 | function changeAdmin(address newAdmin) external ifAdmin { 240 | require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); 241 | emit AdminChanged(_admin(), newAdmin); 242 | _setAdmin(newAdmin); 243 | } 244 | 245 | /** 246 | * @dev Upgrade the backing implementation of the proxy. 247 | * Only the admin can call this function. 248 | * @param newImplementation Address of the new implementation. 249 | */ 250 | function upgradeTo(address newImplementation) external ifAdmin { 251 | _upgradeTo(newImplementation); 252 | } 253 | 254 | /** 255 | * @dev Upgrade the backing implementation of the proxy and call a function 256 | * on the new implementation. 257 | * This is useful to initialize the proxied contract. 258 | * @param newImplementation Address of the new implementation. 259 | * @param data Data to send as msg.data in the low level call. 260 | * It should include the signature and the parameters of the function to be 261 | * called, as described in 262 | * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. 263 | */ 264 | function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin { 265 | _upgradeTo(newImplementation); 266 | require(address(this).call.value(msg.value)(data)); 267 | } 268 | 269 | /** 270 | * @return The admin slot. 271 | */ 272 | function _admin() internal view returns (address adm) { 273 | bytes32 slot = ADMIN_SLOT; 274 | assembly { 275 | adm := sload(slot) 276 | } 277 | } 278 | 279 | /** 280 | * @dev Sets the address of the proxy admin. 281 | * @param newAdmin Address of the new proxy admin. 282 | */ 283 | function _setAdmin(address newAdmin) internal { 284 | bytes32 slot = ADMIN_SLOT; 285 | 286 | assembly { 287 | sstore(slot, newAdmin) 288 | } 289 | } 290 | 291 | /** 292 | * @dev Only fall back when the sender is not the admin. 293 | */ 294 | function _willFallback() internal { 295 | require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); 296 | super._willFallback(); 297 | } 298 | } 299 | 300 | // File: contracts/FiatTokenProxy.sol 301 | 302 | /** 303 | * Copyright CENTRE SECZ 2018 304 | * 305 | * Permission is hereby granted, free of charge, to any person obtaining a copy 306 | * of this software and associated documentation files (the "Software"), to deal 307 | * in the Software without restriction, including without limitation the rights 308 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 309 | * copies of the Software, and to permit persons to whom the Software is furnished to 310 | * do so, subject to the following conditions: 311 | * 312 | * The above copyright notice and this permission notice shall be included in all 313 | * copies or substantial portions of the Software. 314 | * 315 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 316 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 317 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 318 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 319 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 320 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 321 | */ 322 | 323 | pragma solidity ^0.4.24; 324 | 325 | 326 | /** 327 | * @title FiatTokenProxy 328 | * @dev This contract proxies FiatToken calls and enables FiatToken upgrades 329 | */ 330 | contract FiatTokenProxy is AdminUpgradeabilityProxy { 331 | constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) { 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/USDT.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Etherscan.io on 2017-11-28 3 | */ 4 | 5 | pragma solidity ^0.4.17; 6 | 7 | /** 8 | * @title SafeMath 9 | * @dev Math operations with safety checks that throw on error 10 | */ 11 | library SafeMath { 12 | function mul(uint256 a, uint256 b) internal pure returns (uint256) { 13 | if (a == 0) { 14 | return 0; 15 | } 16 | uint256 c = a * b; 17 | assert(c / a == b); 18 | return c; 19 | } 20 | 21 | function div(uint256 a, uint256 b) internal pure returns (uint256) { 22 | // assert(b > 0); // Solidity automatically throws when dividing by 0 23 | uint256 c = a / b; 24 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold 25 | return c; 26 | } 27 | 28 | function sub(uint256 a, uint256 b) internal pure returns (uint256) { 29 | assert(b <= a); 30 | return a - b; 31 | } 32 | 33 | function add(uint256 a, uint256 b) internal pure returns (uint256) { 34 | uint256 c = a + b; 35 | assert(c >= a); 36 | return c; 37 | } 38 | } 39 | 40 | /** 41 | * @title Ownable 42 | * @dev The Ownable contract has an owner address, and provides basic authorization control 43 | * functions, this simplifies the implementation of "user permissions". 44 | */ 45 | contract Ownable { 46 | address public owner; 47 | 48 | /** 49 | * @dev The Ownable constructor sets the original `owner` of the contract to the sender 50 | * account. 51 | */ 52 | function Ownable() public { 53 | owner = msg.sender; 54 | } 55 | 56 | /** 57 | * @dev Throws if called by any account other than the owner. 58 | */ 59 | modifier onlyOwner() { 60 | require(msg.sender == owner); 61 | _; 62 | } 63 | 64 | /** 65 | * @dev Allows the current owner to transfer control of the contract to a newOwner. 66 | * @param newOwner The address to transfer ownership to. 67 | */ 68 | function transferOwnership(address newOwner) public onlyOwner { 69 | if (newOwner != address(0)) { 70 | owner = newOwner; 71 | } 72 | } 73 | 74 | } 75 | 76 | /** 77 | * @title ERC20Basic 78 | * @dev Simpler version of ERC20 interface 79 | * @dev see https://github.com/ethereum/EIPs/issues/20 80 | */ 81 | contract ERC20Basic { 82 | uint public _totalSupply; 83 | function totalSupply() public constant returns (uint); 84 | function balanceOf(address who) public constant returns (uint); 85 | function transfer(address to, uint value) public; 86 | event Transfer(address indexed from, address indexed to, uint value); 87 | } 88 | 89 | /** 90 | * @title ERC20 interface 91 | * @dev see https://github.com/ethereum/EIPs/issues/20 92 | */ 93 | contract ERC20 is ERC20Basic { 94 | function allowance(address owner, address spender) public constant returns (uint); 95 | function transferFrom(address from, address to, uint value) public; 96 | function approve(address spender, uint value) public; 97 | event Approval(address indexed owner, address indexed spender, uint value); 98 | } 99 | 100 | /** 101 | * @title Basic token 102 | * @dev Basic version of StandardToken, with no allowances. 103 | */ 104 | contract BasicToken is Ownable, ERC20Basic { 105 | using SafeMath for uint; 106 | 107 | mapping(address => uint) public balances; 108 | 109 | // additional variables for use if transaction fees ever became necessary 110 | uint public basisPointsRate = 0; 111 | uint public maximumFee = 0; 112 | 113 | /** 114 | * @dev Fix for the ERC20 short address attack. 115 | */ 116 | modifier onlyPayloadSize(uint size) { 117 | require(!(msg.data.length < size + 4)); 118 | _; 119 | } 120 | 121 | /** 122 | * @dev transfer token for a specified address 123 | * @param _to The address to transfer to. 124 | * @param _value The amount to be transferred. 125 | */ 126 | function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { 127 | uint fee = (_value.mul(basisPointsRate)).div(10000); 128 | if (fee > maximumFee) { 129 | fee = maximumFee; 130 | } 131 | uint sendAmount = _value.sub(fee); 132 | balances[msg.sender] = balances[msg.sender].sub(_value); 133 | balances[_to] = balances[_to].add(sendAmount); 134 | if (fee > 0) { 135 | balances[owner] = balances[owner].add(fee); 136 | Transfer(msg.sender, owner, fee); 137 | } 138 | Transfer(msg.sender, _to, sendAmount); 139 | } 140 | 141 | /** 142 | * @dev Gets the balance of the specified address. 143 | * @param _owner The address to query the the balance of. 144 | * @return An uint representing the amount owned by the passed address. 145 | */ 146 | function balanceOf(address _owner) public constant returns (uint balance) { 147 | return balances[_owner]; 148 | } 149 | 150 | } 151 | 152 | /** 153 | * @title Standard ERC20 token 154 | * 155 | * @dev Implementation of the basic standard token. 156 | * @dev https://github.com/ethereum/EIPs/issues/20 157 | * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol 158 | */ 159 | contract StandardToken is BasicToken, ERC20 { 160 | 161 | mapping (address => mapping (address => uint)) public allowed; 162 | 163 | uint public constant MAX_UINT = 2**256 - 1; 164 | 165 | /** 166 | * @dev Transfer tokens from one address to another 167 | * @param _from address The address which you want to send tokens from 168 | * @param _to address The address which you want to transfer to 169 | * @param _value uint the amount of tokens to be transferred 170 | */ 171 | function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { 172 | var _allowance = allowed[_from][msg.sender]; 173 | 174 | // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met 175 | // if (_value > _allowance) throw; 176 | 177 | uint fee = (_value.mul(basisPointsRate)).div(10000); 178 | if (fee > maximumFee) { 179 | fee = maximumFee; 180 | } 181 | if (_allowance < MAX_UINT) { 182 | allowed[_from][msg.sender] = _allowance.sub(_value); 183 | } 184 | uint sendAmount = _value.sub(fee); 185 | balances[_from] = balances[_from].sub(_value); 186 | balances[_to] = balances[_to].add(sendAmount); 187 | if (fee > 0) { 188 | balances[owner] = balances[owner].add(fee); 189 | Transfer(_from, owner, fee); 190 | } 191 | Transfer(_from, _to, sendAmount); 192 | } 193 | 194 | /** 195 | * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. 196 | * @param _spender The address which will spend the funds. 197 | * @param _value The amount of tokens to be spent. 198 | */ 199 | function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { 200 | 201 | // To change the approve amount you first have to reduce the addresses` 202 | // allowance to zero by calling `approve(_spender, 0)` if it is not 203 | // already 0 to mitigate the race condition described here: 204 | // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 205 | require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); 206 | 207 | allowed[msg.sender][_spender] = _value; 208 | Approval(msg.sender, _spender, _value); 209 | } 210 | 211 | /** 212 | * @dev Function to check the amount of tokens than an owner allowed to a spender. 213 | * @param _owner address The address which owns the funds. 214 | * @param _spender address The address which will spend the funds. 215 | * @return A uint specifying the amount of tokens still available for the spender. 216 | */ 217 | function allowance(address _owner, address _spender) public constant returns (uint remaining) { 218 | return allowed[_owner][_spender]; 219 | } 220 | 221 | } 222 | 223 | 224 | /** 225 | * @title Pausable 226 | * @dev Base contract which allows children to implement an emergency stop mechanism. 227 | */ 228 | contract Pausable is Ownable { 229 | event Pause(); 230 | event Unpause(); 231 | 232 | bool public paused = false; 233 | 234 | 235 | /** 236 | * @dev Modifier to make a function callable only when the contract is not paused. 237 | */ 238 | modifier whenNotPaused() { 239 | require(!paused); 240 | _; 241 | } 242 | 243 | /** 244 | * @dev Modifier to make a function callable only when the contract is paused. 245 | */ 246 | modifier whenPaused() { 247 | require(paused); 248 | _; 249 | } 250 | 251 | /** 252 | * @dev called by the owner to pause, triggers stopped state 253 | */ 254 | function pause() onlyOwner whenNotPaused public { 255 | paused = true; 256 | Pause(); 257 | } 258 | 259 | /** 260 | * @dev called by the owner to unpause, returns to normal state 261 | */ 262 | function unpause() onlyOwner whenPaused public { 263 | paused = false; 264 | Unpause(); 265 | } 266 | } 267 | 268 | contract BlackList is Ownable, BasicToken { 269 | 270 | /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) /////// 271 | function getBlackListStatus(address _maker) external constant returns (bool) { 272 | return isBlackListed[_maker]; 273 | } 274 | 275 | function getOwner() external constant returns (address) { 276 | return owner; 277 | } 278 | 279 | mapping (address => bool) public isBlackListed; 280 | 281 | function addBlackList (address _evilUser) public onlyOwner { 282 | isBlackListed[_evilUser] = true; 283 | AddedBlackList(_evilUser); 284 | } 285 | 286 | function removeBlackList (address _clearedUser) public onlyOwner { 287 | isBlackListed[_clearedUser] = false; 288 | RemovedBlackList(_clearedUser); 289 | } 290 | 291 | function destroyBlackFunds (address _blackListedUser) public onlyOwner { 292 | require(isBlackListed[_blackListedUser]); 293 | uint dirtyFunds = balanceOf(_blackListedUser); 294 | balances[_blackListedUser] = 0; 295 | _totalSupply -= dirtyFunds; 296 | DestroyedBlackFunds(_blackListedUser, dirtyFunds); 297 | } 298 | 299 | event DestroyedBlackFunds(address _blackListedUser, uint _balance); 300 | 301 | event AddedBlackList(address _user); 302 | 303 | event RemovedBlackList(address _user); 304 | 305 | } 306 | 307 | contract UpgradedStandardToken is StandardToken{ 308 | // those methods are called by the legacy contract 309 | // and they must ensure msg.sender to be the contract address 310 | function transferByLegacy(address from, address to, uint value) public; 311 | function transferFromByLegacy(address sender, address from, address spender, uint value) public; 312 | function approveByLegacy(address from, address spender, uint value) public; 313 | } 314 | 315 | contract TetherToken is Pausable, StandardToken, BlackList { 316 | 317 | string public name; 318 | string public symbol; 319 | uint public decimals; 320 | address public upgradedAddress; 321 | bool public deprecated; 322 | 323 | // The contract can be initialized with a number of tokens 324 | // All the tokens are deposited to the owner address 325 | // 326 | // @param _balance Initial supply of the contract 327 | // @param _name Token Name 328 | // @param _symbol Token symbol 329 | // @param _decimals Token decimals 330 | function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public { 331 | _totalSupply = _initialSupply; 332 | name = _name; 333 | symbol = _symbol; 334 | decimals = _decimals; 335 | balances[owner] = _initialSupply; 336 | deprecated = false; 337 | } 338 | 339 | // Forward ERC20 methods to upgraded contract if this one is deprecated 340 | function transfer(address _to, uint _value) public whenNotPaused { 341 | require(!isBlackListed[msg.sender]); 342 | if (deprecated) { 343 | return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); 344 | } else { 345 | return super.transfer(_to, _value); 346 | } 347 | } 348 | 349 | // Forward ERC20 methods to upgraded contract if this one is deprecated 350 | function transferFrom(address _from, address _to, uint _value) public whenNotPaused { 351 | require(!isBlackListed[_from]); 352 | if (deprecated) { 353 | return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); 354 | } else { 355 | return super.transferFrom(_from, _to, _value); 356 | } 357 | } 358 | 359 | // Forward ERC20 methods to upgraded contract if this one is deprecated 360 | function balanceOf(address who) public constant returns (uint) { 361 | if (deprecated) { 362 | return UpgradedStandardToken(upgradedAddress).balanceOf(who); 363 | } else { 364 | return super.balanceOf(who); 365 | } 366 | } 367 | 368 | // Forward ERC20 methods to upgraded contract if this one is deprecated 369 | function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { 370 | if (deprecated) { 371 | return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); 372 | } else { 373 | return super.approve(_spender, _value); 374 | } 375 | } 376 | 377 | // Forward ERC20 methods to upgraded contract if this one is deprecated 378 | function allowance(address _owner, address _spender) public constant returns (uint remaining) { 379 | if (deprecated) { 380 | return StandardToken(upgradedAddress).allowance(_owner, _spender); 381 | } else { 382 | return super.allowance(_owner, _spender); 383 | } 384 | } 385 | 386 | // deprecate current contract in favour of a new one 387 | function deprecate(address _upgradedAddress) public onlyOwner { 388 | deprecated = true; 389 | upgradedAddress = _upgradedAddress; 390 | Deprecate(_upgradedAddress); 391 | } 392 | 393 | // deprecate current contract if favour of a new one 394 | function totalSupply() public constant returns (uint) { 395 | if (deprecated) { 396 | return StandardToken(upgradedAddress).totalSupply(); 397 | } else { 398 | return _totalSupply; 399 | } 400 | } 401 | 402 | // Issue a new amount of tokens 403 | // these tokens are deposited into the owner address 404 | // 405 | // @param _amount Number of tokens to be issued 406 | function issue(uint amount) public onlyOwner { 407 | require(_totalSupply + amount > _totalSupply); 408 | require(balances[owner] + amount > balances[owner]); 409 | 410 | balances[owner] += amount; 411 | _totalSupply += amount; 412 | Issue(amount); 413 | } 414 | 415 | // Redeem tokens. 416 | // These tokens are withdrawn from the owner address 417 | // if the balance must be enough to cover the redeem 418 | // or the call will fail. 419 | // @param _amount Number of tokens to be issued 420 | function redeem(uint amount) public onlyOwner { 421 | require(_totalSupply >= amount); 422 | require(balances[owner] >= amount); 423 | 424 | _totalSupply -= amount; 425 | balances[owner] -= amount; 426 | Redeem(amount); 427 | } 428 | 429 | function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { 430 | // Ensure transparency by hardcoding limit beyond which fees can never be added 431 | require(newBasisPoints < 20); 432 | require(newMaxFee < 50); 433 | 434 | basisPointsRate = newBasisPoints; 435 | maximumFee = newMaxFee.mul(10**decimals); 436 | 437 | Params(basisPointsRate, maximumFee); 438 | } 439 | 440 | // Called when new token are issued 441 | event Issue(uint amount); 442 | 443 | // Called when tokens are redeemed 444 | event Redeem(uint amount); 445 | 446 | // Called when contract is deprecated 447 | event Deprecate(address newAddress); 448 | 449 | // Called if contract ever adds fees 450 | event Params(uint feeBasisPoints, uint maxFee); 451 | } 452 | -------------------------------------------------------------------------------- /tests/test-subscription.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { step } from "mocha-steps"; 3 | 4 | import { createAndFinalizeBlock, describeWithClover, customRequest, GENESIS_ACCOUNT, GENESIS_ACCOUNT_PRIVATE_KEY } from "./util"; 5 | 6 | describeWithClover("Clover RPC (Subscription)", (context) => { 7 | let subscription; 8 | let logs_generated = 0; 9 | 10 | const TEST_CONTRACT_BYTECODE = 11 | "0x608060405234801561001057600080fd5b50610041337fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff61004660201b60201c565b610291565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156100e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b6101028160025461020960201b610c7c1790919060201c565b60028190555061015d816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461020960201b610c7c1790919060201c565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600080828401905083811015610287576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b610e3a806102a06000396000f3fe608060405234801561001057600080fd5b50600436106100885760003560e01c806370a082311161005b57806370a08231146101fd578063a457c2d714610255578063a9059cbb146102bb578063dd62ed3e1461032157610088565b8063095ea7b31461008d57806318160ddd146100f357806323b872dd146101115780633950935114610197575b600080fd5b6100d9600480360360408110156100a357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610399565b604051808215151515815260200191505060405180910390f35b6100fb6103b7565b6040518082815260200191505060405180910390f35b61017d6004803603606081101561012757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506103c1565b604051808215151515815260200191505060405180910390f35b6101e3600480360360408110156101ad57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061049a565b604051808215151515815260200191505060405180910390f35b61023f6004803603602081101561021357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061054d565b6040518082815260200191505060405180910390f35b6102a16004803603604081101561026b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610595565b604051808215151515815260200191505060405180910390f35b610307600480360360408110156102d157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610662565b604051808215151515815260200191505060405180910390f35b6103836004803603604081101561033757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610680565b6040518082815260200191505060405180910390f35b60006103ad6103a6610707565b848461070f565b6001905092915050565b6000600254905090565b60006103ce848484610906565b61048f846103da610707565b61048a85604051806060016040528060288152602001610d7060289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610440610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b61070f565b600190509392505050565b60006105436104a7610707565b8461053e85600160006104b8610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610c7c90919063ffffffff16565b61070f565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60006106586105a2610707565b8461065385604051806060016040528060258152602001610de160259139600160006105cc610707565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b61070f565b6001905092915050565b600061067661066f610707565b8484610906565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610795576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180610dbd6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561081b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610d286022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141561098c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180610d986025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610a12576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610d056023913960400191505060405180910390fd5b610a7d81604051806060016040528060268152602001610d4a602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bbc9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610b10816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610c7c90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610c69576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610c2e578082015181840152602081019050610c13565b50505050905090810190601f168015610c5b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610cfa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72315820c7a5ffabf642bda14700b2de42f8c57b36621af020441df825de45fd2b3e1c5c64736f6c63430005100032"; 12 | 13 | async function sendTransaction(context) { 14 | const tx = await context.web3.eth.accounts.signTransaction( 15 | { 16 | from: GENESIS_ACCOUNT, 17 | data: TEST_CONTRACT_BYTECODE, 18 | value: "0x00", 19 | gasPrice: "0x01", 20 | gas: "0x4F930", 21 | }, 22 | GENESIS_ACCOUNT_PRIVATE_KEY 23 | ); 24 | 25 | await customRequest(context.web3, "eth_sendRawTransaction", [tx.rawTransaction]); 26 | return tx; 27 | } 28 | 29 | step("should connect", async function () { 30 | await createAndFinalizeBlock(context.web3); 31 | // @ts-ignore 32 | const connected = context.web3.currentProvider.connected; 33 | expect(connected).to.equal(true); 34 | }); 35 | 36 | step("should subscribe", async function () { 37 | subscription = context.web3.eth.subscribe("newBlockHeaders", function(error, result){}); 38 | 39 | let connected = false; 40 | let subscriptionId = ""; 41 | await new Promise((resolve) => { 42 | subscription.on("connected", function (d: any) { 43 | connected = true; 44 | subscriptionId = d; 45 | resolve(); 46 | }); 47 | }); 48 | 49 | subscription.unsubscribe(); 50 | expect(connected).to.equal(true); 51 | expect(subscriptionId).to.have.lengthOf(34); 52 | }); 53 | 54 | step("should get newHeads stream", async function (done) { 55 | subscription = context.web3.eth.subscribe("newBlockHeaders", function(error, result){}); 56 | let data = null; 57 | await new Promise((resolve) => { 58 | createAndFinalizeBlock(context.web3); 59 | subscription.on("data", function (d: any) { 60 | data = d; 61 | resolve(); 62 | }); 63 | }); 64 | subscription.unsubscribe(); 65 | expect(data).to.include({ 66 | author: '0x0000000000000000000000000000000000000000', 67 | difficulty: '0', 68 | extraData: '0x', 69 | logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 70 | miner: '0x0000000000000000000000000000000000000000', 71 | number: 2, 72 | receiptsRoot: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 73 | sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 74 | transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421' 75 | }); 76 | expect((data as any).sealFields).to.eql([ 77 | "0x0000000000000000000000000000000000000000000000000000000000000000", 78 | "0x0000000000000000", 79 | ]); 80 | setTimeout(done,10000); 81 | }).timeout(20000); 82 | 83 | step("should get newPendingTransactions stream", async function (done) { 84 | subscription = context.web3.eth.subscribe("pendingTransactions", function(error, result){}); 85 | 86 | await new Promise((resolve) => { 87 | subscription.on("connected", function (d: any) { 88 | resolve(); 89 | }); 90 | }); 91 | 92 | const tx = await sendTransaction(context); 93 | let data = null; 94 | await new Promise((resolve) => { 95 | createAndFinalizeBlock(context.web3); 96 | subscription.on("data", function (d: any) { 97 | data = d; 98 | logs_generated += 1; 99 | resolve(); 100 | }); 101 | }); 102 | subscription.unsubscribe(); 103 | 104 | expect(data).to.be.not.null; 105 | expect(tx["transactionHash"]).to.be.eq(data); 106 | setTimeout(done,10000); 107 | }).timeout(20000); 108 | 109 | step("should subscribe to all logs", async function (done) { 110 | subscription = context.web3.eth.subscribe("logs", {}, function(error, result){}); 111 | 112 | await new Promise((resolve) => { 113 | subscription.on("connected", function (d: any) { 114 | resolve(); 115 | }); 116 | }); 117 | 118 | const tx = await sendTransaction(context); 119 | let data = null; 120 | await new Promise((resolve) => { 121 | createAndFinalizeBlock(context.web3); 122 | subscription.on("data", function (d: any) { 123 | data = d; 124 | logs_generated += 1; 125 | resolve(); 126 | }); 127 | }); 128 | subscription.unsubscribe(); 129 | 130 | const block = await context.web3.eth.getBlock("latest"); 131 | expect(data).to.include({ 132 | blockHash: block.hash, 133 | blockNumber: block.number, 134 | data: '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 135 | logIndex: 0, 136 | removed: false, 137 | transactionHash: block.transactions[0], 138 | transactionIndex: 0, 139 | transactionLogIndex: '0x0' 140 | }); 141 | setTimeout(done,10000); 142 | }).timeout(20000); 143 | 144 | step("should subscribe to logs by address", async function (done) { 145 | subscription = context.web3.eth.subscribe("logs", { 146 | address: "0x42e2EE7Ba8975c473157634Ac2AF4098190fc741" 147 | }, function(error, result){}); 148 | 149 | await new Promise((resolve) => { 150 | subscription.on("connected", function (d: any) { 151 | resolve(); 152 | }); 153 | }); 154 | 155 | const tx = await sendTransaction(context); 156 | let data = null; 157 | await new Promise((resolve) => { 158 | createAndFinalizeBlock(context.web3); 159 | subscription.on("data", function (d: any) { 160 | data = d; 161 | logs_generated += 1; 162 | resolve(); 163 | }); 164 | }); 165 | subscription.unsubscribe(); 166 | 167 | expect(data).to.not.be.null; 168 | setTimeout(done,10000); 169 | }).timeout(20000); 170 | 171 | step("should subscribe to logs by topic", async function (done) { 172 | subscription = context.web3.eth.subscribe("logs", { 173 | topics: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] 174 | }, function(error, result){}); 175 | 176 | await new Promise((resolve) => { 177 | subscription.on("connected", function (d: any) { 178 | resolve(); 179 | }); 180 | }); 181 | 182 | const tx = await sendTransaction(context); 183 | let data = null; 184 | await new Promise((resolve) => { 185 | createAndFinalizeBlock(context.web3); 186 | subscription.on("data", function (d: any) { 187 | data = d; 188 | logs_generated += 1; 189 | resolve(); 190 | }); 191 | }); 192 | subscription.unsubscribe(); 193 | 194 | expect(data).to.not.be.null; 195 | setTimeout(done,10000); 196 | }).timeout(20000); 197 | 198 | step("should get past events on subscription", async function (done) { 199 | subscription = context.web3.eth.subscribe("logs", { 200 | fromBlock: "0x0" 201 | }, function(error, result){}); 202 | 203 | let data = []; 204 | await new Promise((resolve) => { 205 | subscription.on("data", function (d: any) { 206 | data.push(d); 207 | if (data.length == logs_generated) { 208 | resolve(); 209 | } 210 | }); 211 | }); 212 | subscription.unsubscribe(); 213 | 214 | expect(data).to.not.be.empty; 215 | setTimeout(done,10000); 216 | }).timeout(20000); 217 | 218 | step("should support topic wildcards", async function (done) { 219 | subscription = context.web3.eth.subscribe("logs", { 220 | topics: [ 221 | null, 222 | "0x0000000000000000000000000000000000000000000000000000000000000000" 223 | ] 224 | }, function(error, result){}); 225 | 226 | await new Promise((resolve) => { 227 | subscription.on("connected", function (d: any) { 228 | resolve(); 229 | }); 230 | }); 231 | 232 | const tx = await sendTransaction(context); 233 | let data = null; 234 | await new Promise((resolve) => { 235 | createAndFinalizeBlock(context.web3); 236 | subscription.on("data", function (d: any) { 237 | data = d; 238 | logs_generated += 1; 239 | resolve(); 240 | }); 241 | }); 242 | subscription.unsubscribe(); 243 | 244 | expect(data).to.not.be.null; 245 | setTimeout(done,10000); 246 | }).timeout(20000); 247 | 248 | step("should support single values wrapped around a sequence", async function (done) { 249 | subscription = context.web3.eth.subscribe("logs", { 250 | topics: [ 251 | ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"], 252 | ["0x0000000000000000000000000000000000000000000000000000000000000000"] 253 | ] 254 | }, function(error, result){}); 255 | 256 | await new Promise((resolve) => { 257 | subscription.on("connected", function (d: any) { 258 | resolve(); 259 | }); 260 | }); 261 | 262 | const tx = await sendTransaction(context); 263 | let data = null; 264 | await new Promise((resolve) => { 265 | createAndFinalizeBlock(context.web3); 266 | subscription.on("data", function (d: any) { 267 | data = d; 268 | logs_generated += 1; 269 | resolve(); 270 | }); 271 | }); 272 | subscription.unsubscribe(); 273 | 274 | expect(data).to.not.be.null; 275 | setTimeout(done,10000); 276 | }).timeout(20000); 277 | 278 | step("should support topic conditional parameters", async function (done) { 279 | subscription = context.web3.eth.subscribe("logs", { 280 | topics: [ 281 | "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", 282 | [ 283 | "0x0000000000000000000000006be02d1d3665660d22ff9624b7be0551ee1ac91b", 284 | "0x0000000000000000000000000000000000000000000000000000000000000000" 285 | ] 286 | ] 287 | }, function(error, result){}); 288 | 289 | await new Promise((resolve) => { 290 | subscription.on("connected", function (d: any) { 291 | resolve(); 292 | }); 293 | }); 294 | 295 | const tx = await sendTransaction(context); 296 | let data = null; 297 | await new Promise((resolve) => { 298 | createAndFinalizeBlock(context.web3); 299 | subscription.on("data", function (d: any) { 300 | data = d; 301 | logs_generated += 1; 302 | resolve(); 303 | }); 304 | }); 305 | subscription.unsubscribe(); 306 | 307 | expect(data).to.not.be.null; 308 | setTimeout(done,10000); 309 | }).timeout(20000); 310 | 311 | step("should support multiple topic conditional parameters", async function (done) { 312 | subscription = context.web3.eth.subscribe("logs", { 313 | topics: [ 314 | "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", 315 | [ 316 | "0x0000000000000000000000000000000000000000000000000000000000000000", 317 | "0x0000000000000000000000006be02d1d3665660d22ff9624b7be0551ee1ac91b" 318 | ], 319 | [ 320 | "0x0000000000000000000000006be02d1d3665660d22ff9624b7be0551ee1ac91b", 321 | "0x0000000000000000000000000000000000000000000000000000000000000000" 322 | ] 323 | ] 324 | }, function(error, result){}); 325 | 326 | await new Promise((resolve) => { 327 | subscription.on("connected", function (d: any) { 328 | resolve(); 329 | }); 330 | }); 331 | 332 | const tx = await sendTransaction(context); 333 | let data = null; 334 | await new Promise((resolve) => { 335 | createAndFinalizeBlock(context.web3); 336 | subscription.on("data", function (d: any) { 337 | data = d; 338 | logs_generated += 1; 339 | resolve(); 340 | }); 341 | }); 342 | subscription.unsubscribe(); 343 | 344 | expect(data).to.not.be.null; 345 | setTimeout(done,10000); 346 | }).timeout(20000); 347 | 348 | step("should combine topic wildcards and conditional parameters", async function (done) { 349 | subscription = context.web3.eth.subscribe("logs", { 350 | topics: [ 351 | null, 352 | [ 353 | "0x0000000000000000000000006be02d1d3665660d22ff9624b7be0551ee1ac91b", 354 | "0x0000000000000000000000000000000000000000000000000000000000000000" 355 | ], 356 | null 357 | ] 358 | }, function(error, result){}); 359 | 360 | await new Promise((resolve) => { 361 | subscription.on("connected", function (d: any) { 362 | resolve(); 363 | }); 364 | }); 365 | 366 | const tx = await sendTransaction(context); 367 | let data = null; 368 | await new Promise((resolve) => { 369 | createAndFinalizeBlock(context.web3); 370 | subscription.on("data", function (d: any) { 371 | data = d; 372 | logs_generated += 1; 373 | resolve(); 374 | }); 375 | }); 376 | subscription.unsubscribe(); 377 | 378 | expect(data).to.not.be.null; 379 | setTimeout(done,10000); 380 | }).timeout(20000); 381 | }, "ws"); 382 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/UniswapV2Factory.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Etherscan.io on 2020-05-04 3 | */ 4 | 5 | pragma solidity =0.5.16; 6 | 7 | interface IUniswapV2Factory { 8 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 9 | 10 | function feeTo() external view returns (address); 11 | function feeToSetter() external view returns (address); 12 | 13 | function getPair(address tokenA, address tokenB) external view returns (address pair); 14 | function allPairs(uint) external view returns (address pair); 15 | function allPairsLength() external view returns (uint); 16 | 17 | function createPair(address tokenA, address tokenB) external returns (address pair); 18 | 19 | function setFeeTo(address) external; 20 | function setFeeToSetter(address) external; 21 | } 22 | 23 | interface IUniswapV2Pair { 24 | event Approval(address indexed owner, address indexed spender, uint value); 25 | event Transfer(address indexed from, address indexed to, uint value); 26 | 27 | function name() external pure returns (string memory); 28 | function symbol() external pure returns (string memory); 29 | function decimals() external pure returns (uint8); 30 | function totalSupply() external view returns (uint); 31 | function balanceOf(address owner) external view returns (uint); 32 | function allowance(address owner, address spender) external view returns (uint); 33 | 34 | function approve(address spender, uint value) external returns (bool); 35 | function transfer(address to, uint value) external returns (bool); 36 | function transferFrom(address from, address to, uint value) external returns (bool); 37 | 38 | function DOMAIN_SEPARATOR() external view returns (bytes32); 39 | function PERMIT_TYPEHASH() external pure returns (bytes32); 40 | function nonces(address owner) external view returns (uint); 41 | 42 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 43 | 44 | event Mint(address indexed sender, uint amount0, uint amount1); 45 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 46 | event Swap( 47 | address indexed sender, 48 | uint amount0In, 49 | uint amount1In, 50 | uint amount0Out, 51 | uint amount1Out, 52 | address indexed to 53 | ); 54 | event Sync(uint112 reserve0, uint112 reserve1); 55 | 56 | function MINIMUM_LIQUIDITY() external pure returns (uint); 57 | function factory() external view returns (address); 58 | function token0() external view returns (address); 59 | function token1() external view returns (address); 60 | function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); 61 | function price0CumulativeLast() external view returns (uint); 62 | function price1CumulativeLast() external view returns (uint); 63 | function kLast() external view returns (uint); 64 | 65 | function mint(address to) external returns (uint liquidity); 66 | function burn(address to) external returns (uint amount0, uint amount1); 67 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; 68 | function skim(address to) external; 69 | function sync() external; 70 | 71 | function initialize(address, address) external; 72 | } 73 | 74 | interface IUniswapV2ERC20 { 75 | event Approval(address indexed owner, address indexed spender, uint value); 76 | event Transfer(address indexed from, address indexed to, uint value); 77 | 78 | function name() external pure returns (string memory); 79 | function symbol() external pure returns (string memory); 80 | function decimals() external pure returns (uint8); 81 | function totalSupply() external view returns (uint); 82 | function balanceOf(address owner) external view returns (uint); 83 | function allowance(address owner, address spender) external view returns (uint); 84 | 85 | function approve(address spender, uint value) external returns (bool); 86 | function transfer(address to, uint value) external returns (bool); 87 | function transferFrom(address from, address to, uint value) external returns (bool); 88 | 89 | function DOMAIN_SEPARATOR() external view returns (bytes32); 90 | function PERMIT_TYPEHASH() external pure returns (bytes32); 91 | function nonces(address owner) external view returns (uint); 92 | 93 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 94 | } 95 | 96 | interface IERC20 { 97 | event Approval(address indexed owner, address indexed spender, uint value); 98 | event Transfer(address indexed from, address indexed to, uint value); 99 | 100 | function name() external view returns (string memory); 101 | function symbol() external view returns (string memory); 102 | function decimals() external view returns (uint8); 103 | function totalSupply() external view returns (uint); 104 | function balanceOf(address owner) external view returns (uint); 105 | function allowance(address owner, address spender) external view returns (uint); 106 | 107 | function approve(address spender, uint value) external returns (bool); 108 | function transfer(address to, uint value) external returns (bool); 109 | function transferFrom(address from, address to, uint value) external returns (bool); 110 | } 111 | 112 | interface IUniswapV2Callee { 113 | function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; 114 | } 115 | 116 | contract UniswapV2ERC20 is IUniswapV2ERC20 { 117 | using SafeMath for uint; 118 | 119 | string public constant name = 'Uniswap V2'; 120 | string public constant symbol = 'UNI-V2'; 121 | uint8 public constant decimals = 18; 122 | uint public totalSupply; 123 | mapping(address => uint) public balanceOf; 124 | mapping(address => mapping(address => uint)) public allowance; 125 | 126 | bytes32 public DOMAIN_SEPARATOR; 127 | // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); 128 | bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; 129 | mapping(address => uint) public nonces; 130 | 131 | event Approval(address indexed owner, address indexed spender, uint value); 132 | event Transfer(address indexed from, address indexed to, uint value); 133 | 134 | constructor() public { 135 | uint chainId; 136 | assembly { 137 | chainId := chainid 138 | } 139 | DOMAIN_SEPARATOR = keccak256( 140 | abi.encode( 141 | keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), 142 | keccak256(bytes(name)), 143 | keccak256(bytes('1')), 144 | chainId, 145 | address(this) 146 | ) 147 | ); 148 | } 149 | 150 | function _mint(address to, uint value) internal { 151 | totalSupply = totalSupply.add(value); 152 | balanceOf[to] = balanceOf[to].add(value); 153 | emit Transfer(address(0), to, value); 154 | } 155 | 156 | function _burn(address from, uint value) internal { 157 | balanceOf[from] = balanceOf[from].sub(value); 158 | totalSupply = totalSupply.sub(value); 159 | emit Transfer(from, address(0), value); 160 | } 161 | 162 | function _approve(address owner, address spender, uint value) private { 163 | allowance[owner][spender] = value; 164 | emit Approval(owner, spender, value); 165 | } 166 | 167 | function _transfer(address from, address to, uint value) private { 168 | balanceOf[from] = balanceOf[from].sub(value); 169 | balanceOf[to] = balanceOf[to].add(value); 170 | emit Transfer(from, to, value); 171 | } 172 | 173 | function approve(address spender, uint value) external returns (bool) { 174 | _approve(msg.sender, spender, value); 175 | return true; 176 | } 177 | 178 | function transfer(address to, uint value) external returns (bool) { 179 | _transfer(msg.sender, to, value); 180 | return true; 181 | } 182 | 183 | function transferFrom(address from, address to, uint value) external returns (bool) { 184 | if (allowance[from][msg.sender] != uint(-1)) { 185 | allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); 186 | } 187 | _transfer(from, to, value); 188 | return true; 189 | } 190 | 191 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { 192 | require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); 193 | bytes32 digest = keccak256( 194 | abi.encodePacked( 195 | '\x19\x01', 196 | DOMAIN_SEPARATOR, 197 | keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) 198 | ) 199 | ); 200 | address recoveredAddress = ecrecover(digest, v, r, s); 201 | require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); 202 | _approve(owner, spender, value); 203 | } 204 | } 205 | 206 | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { 207 | using SafeMath for uint; 208 | using UQ112x112 for uint224; 209 | 210 | uint public constant MINIMUM_LIQUIDITY = 10**3; 211 | bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); 212 | 213 | address public factory; 214 | address public token0; 215 | address public token1; 216 | 217 | uint112 private reserve0; // uses single storage slot, accessible via getReserves 218 | uint112 private reserve1; // uses single storage slot, accessible via getReserves 219 | uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves 220 | 221 | uint public price0CumulativeLast; 222 | uint public price1CumulativeLast; 223 | uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event 224 | 225 | uint private unlocked = 1; 226 | modifier lock() { 227 | require(unlocked == 1, 'UniswapV2: LOCKED'); 228 | unlocked = 0; 229 | _; 230 | unlocked = 1; 231 | } 232 | 233 | function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { 234 | _reserve0 = reserve0; 235 | _reserve1 = reserve1; 236 | _blockTimestampLast = blockTimestampLast; 237 | } 238 | 239 | function _safeTransfer(address token, address to, uint value) private { 240 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); 241 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); 242 | } 243 | 244 | event Mint(address indexed sender, uint amount0, uint amount1); 245 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 246 | event Swap( 247 | address indexed sender, 248 | uint amount0In, 249 | uint amount1In, 250 | uint amount0Out, 251 | uint amount1Out, 252 | address indexed to 253 | ); 254 | event Sync(uint112 reserve0, uint112 reserve1); 255 | 256 | constructor() public { 257 | factory = msg.sender; 258 | } 259 | 260 | // called once by the factory at time of deployment 261 | function initialize(address _token0, address _token1) external { 262 | require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check 263 | token0 = _token0; 264 | token1 = _token1; 265 | } 266 | 267 | // update reserves and, on the first call per block, price accumulators 268 | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { 269 | require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); 270 | uint32 blockTimestamp = uint32(block.timestamp % 2**32); 271 | uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired 272 | if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { 273 | // * never overflows, and + overflow is desired 274 | price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; 275 | price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; 276 | } 277 | reserve0 = uint112(balance0); 278 | reserve1 = uint112(balance1); 279 | blockTimestampLast = blockTimestamp; 280 | emit Sync(reserve0, reserve1); 281 | } 282 | 283 | // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) 284 | function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { 285 | address feeTo = IUniswapV2Factory(factory).feeTo(); 286 | feeOn = feeTo != address(0); 287 | uint _kLast = kLast; // gas savings 288 | if (feeOn) { 289 | if (_kLast != 0) { 290 | uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); 291 | uint rootKLast = Math.sqrt(_kLast); 292 | if (rootK > rootKLast) { 293 | uint numerator = totalSupply.mul(rootK.sub(rootKLast)); 294 | uint denominator = rootK.mul(5).add(rootKLast); 295 | uint liquidity = numerator / denominator; 296 | if (liquidity > 0) _mint(feeTo, liquidity); 297 | } 298 | } 299 | } else if (_kLast != 0) { 300 | kLast = 0; 301 | } 302 | } 303 | 304 | // this low-level function should be called from a contract which performs important safety checks 305 | function mint(address to) external lock returns (uint liquidity) { 306 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 307 | uint balance0 = IERC20(token0).balanceOf(address(this)); 308 | uint balance1 = IERC20(token1).balanceOf(address(this)); 309 | uint amount0 = balance0.sub(_reserve0); 310 | uint amount1 = balance1.sub(_reserve1); 311 | 312 | bool feeOn = _mintFee(_reserve0, _reserve1); 313 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 314 | if (_totalSupply == 0) { 315 | liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); 316 | _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens 317 | } else { 318 | liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); 319 | } 320 | require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); 321 | _mint(to, liquidity); 322 | 323 | _update(balance0, balance1, _reserve0, _reserve1); 324 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 325 | emit Mint(msg.sender, amount0, amount1); 326 | } 327 | 328 | // this low-level function should be called from a contract which performs important safety checks 329 | function burn(address to) external lock returns (uint amount0, uint amount1) { 330 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 331 | address _token0 = token0; // gas savings 332 | address _token1 = token1; // gas savings 333 | uint balance0 = IERC20(_token0).balanceOf(address(this)); 334 | uint balance1 = IERC20(_token1).balanceOf(address(this)); 335 | uint liquidity = balanceOf[address(this)]; 336 | 337 | bool feeOn = _mintFee(_reserve0, _reserve1); 338 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 339 | amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution 340 | amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution 341 | require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); 342 | _burn(address(this), liquidity); 343 | _safeTransfer(_token0, to, amount0); 344 | _safeTransfer(_token1, to, amount1); 345 | balance0 = IERC20(_token0).balanceOf(address(this)); 346 | balance1 = IERC20(_token1).balanceOf(address(this)); 347 | 348 | _update(balance0, balance1, _reserve0, _reserve1); 349 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 350 | emit Burn(msg.sender, amount0, amount1, to); 351 | } 352 | 353 | // this low-level function should be called from a contract which performs important safety checks 354 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { 355 | require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); 356 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 357 | require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); 358 | 359 | uint balance0; 360 | uint balance1; 361 | { // scope for _token{0,1}, avoids stack too deep errors 362 | address _token0 = token0; 363 | address _token1 = token1; 364 | require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); 365 | if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens 366 | if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens 367 | if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); 368 | balance0 = IERC20(_token0).balanceOf(address(this)); 369 | balance1 = IERC20(_token1).balanceOf(address(this)); 370 | } 371 | uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; 372 | uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; 373 | require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); 374 | { // scope for reserve{0,1}Adjusted, avoids stack too deep errors 375 | uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); 376 | uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); 377 | require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); 378 | } 379 | 380 | _update(balance0, balance1, _reserve0, _reserve1); 381 | emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); 382 | } 383 | 384 | // force balances to match reserves 385 | function skim(address to) external lock { 386 | address _token0 = token0; // gas savings 387 | address _token1 = token1; // gas savings 388 | _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); 389 | _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); 390 | } 391 | 392 | // force reserves to match balances 393 | function sync() external lock { 394 | _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); 395 | } 396 | } 397 | 398 | contract UniswapV2Factory is IUniswapV2Factory { 399 | address public feeTo; 400 | address public feeToSetter; 401 | 402 | mapping(address => mapping(address => address)) public getPair; 403 | address[] public allPairs; 404 | 405 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 406 | 407 | constructor(address _feeToSetter) public { 408 | feeToSetter = _feeToSetter; 409 | } 410 | 411 | function allPairsLength() external view returns (uint) { 412 | return allPairs.length; 413 | } 414 | 415 | function createPair(address tokenA, address tokenB) external returns (address pair) { 416 | require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); 417 | (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 418 | require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); 419 | require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient 420 | bytes memory bytecode = type(UniswapV2Pair).creationCode; 421 | bytes32 salt = keccak256(abi.encodePacked(token0, token1)); 422 | assembly { 423 | pair := create2(0, add(bytecode, 32), mload(bytecode), salt) 424 | } 425 | IUniswapV2Pair(pair).initialize(token0, token1); 426 | getPair[token0][token1] = pair; 427 | getPair[token1][token0] = pair; // populate mapping in the reverse direction 428 | allPairs.push(pair); 429 | emit PairCreated(token0, token1, pair, allPairs.length); 430 | } 431 | 432 | function setFeeTo(address _feeTo) external { 433 | require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); 434 | feeTo = _feeTo; 435 | } 436 | 437 | function setFeeToSetter(address _feeToSetter) external { 438 | require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); 439 | feeToSetter = _feeToSetter; 440 | } 441 | } 442 | 443 | // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) 444 | 445 | library SafeMath { 446 | function add(uint x, uint y) internal pure returns (uint z) { 447 | require((z = x + y) >= x, 'ds-math-add-overflow'); 448 | } 449 | 450 | function sub(uint x, uint y) internal pure returns (uint z) { 451 | require((z = x - y) <= x, 'ds-math-sub-underflow'); 452 | } 453 | 454 | function mul(uint x, uint y) internal pure returns (uint z) { 455 | require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); 456 | } 457 | } 458 | 459 | // a library for performing various math operations 460 | 461 | library Math { 462 | function min(uint x, uint y) internal pure returns (uint z) { 463 | z = x < y ? x : y; 464 | } 465 | 466 | // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) 467 | function sqrt(uint y) internal pure returns (uint z) { 468 | if (y > 3) { 469 | z = y; 470 | uint x = y / 2 + 1; 471 | while (x < z) { 472 | z = x; 473 | x = (y / x + x) / 2; 474 | } 475 | } else if (y != 0) { 476 | z = 1; 477 | } 478 | } 479 | } 480 | 481 | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) 482 | 483 | // range: [0, 2**112 - 1] 484 | // resolution: 1 / 2**112 485 | 486 | library UQ112x112 { 487 | uint224 constant Q112 = 2**112; 488 | 489 | // encode a uint112 as a UQ112x112 490 | function encode(uint112 y) internal pure returns (uint224 z) { 491 | z = uint224(y) * Q112; // never overflows 492 | } 493 | 494 | // divide a UQ112x112 by a uint112, returning a UQ112x112 495 | function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { 496 | z = x / uint224(y); 497 | } 498 | } 499 | -------------------------------------------------------------------------------- /tests/e2e-tests/contracts/UNI.sol: -------------------------------------------------------------------------------- 1 | /** 2 | *Submitted for verification at Etherscan.io on 2020-09-16 3 | */ 4 | 5 | /** 6 | *Submitted for verification at Etherscan.io on 2020-09-15 7 | */ 8 | 9 | pragma solidity ^0.5.16; 10 | pragma experimental ABIEncoderV2; 11 | 12 | // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol 13 | // Subject to the MIT license. 14 | 15 | /** 16 | * @dev Wrappers over Solidity's arithmetic operations with added overflow 17 | * checks. 18 | * 19 | * Arithmetic operations in Solidity wrap on overflow. This can easily result 20 | * in bugs, because programmers usually assume that an overflow raises an 21 | * error, which is the standard behavior in high level programming languages. 22 | * `SafeMath` restores this intuition by reverting the transaction when an 23 | * operation overflows. 24 | * 25 | * Using this library instead of the unchecked operations eliminates an entire 26 | * class of bugs, so it's recommended to use it always. 27 | */ 28 | library SafeMath { 29 | /** 30 | * @dev Returns the addition of two unsigned integers, reverting on overflow. 31 | * 32 | * Counterpart to Solidity's `+` operator. 33 | * 34 | * Requirements: 35 | * - Addition cannot overflow. 36 | */ 37 | function add(uint256 a, uint256 b) internal pure returns (uint256) { 38 | uint256 c = a + b; 39 | require(c >= a, "SafeMath: addition overflow"); 40 | 41 | return c; 42 | } 43 | 44 | /** 45 | * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. 46 | * 47 | * Counterpart to Solidity's `+` operator. 48 | * 49 | * Requirements: 50 | * - Addition cannot overflow. 51 | */ 52 | function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 53 | uint256 c = a + b; 54 | require(c >= a, errorMessage); 55 | 56 | return c; 57 | } 58 | 59 | /** 60 | * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). 61 | * 62 | * Counterpart to Solidity's `-` operator. 63 | * 64 | * Requirements: 65 | * - Subtraction cannot underflow. 66 | */ 67 | function sub(uint256 a, uint256 b) internal pure returns (uint256) { 68 | return sub(a, b, "SafeMath: subtraction underflow"); 69 | } 70 | 71 | /** 72 | * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). 73 | * 74 | * Counterpart to Solidity's `-` operator. 75 | * 76 | * Requirements: 77 | * - Subtraction cannot underflow. 78 | */ 79 | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 80 | require(b <= a, errorMessage); 81 | uint256 c = a - b; 82 | 83 | return c; 84 | } 85 | 86 | /** 87 | * @dev Returns the multiplication of two unsigned integers, reverting on overflow. 88 | * 89 | * Counterpart to Solidity's `*` operator. 90 | * 91 | * Requirements: 92 | * - Multiplication cannot overflow. 93 | */ 94 | function mul(uint256 a, uint256 b) internal pure returns (uint256) { 95 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the 96 | // benefit is lost if 'b' is also tested. 97 | // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 98 | if (a == 0) { 99 | return 0; 100 | } 101 | 102 | uint256 c = a * b; 103 | require(c / a == b, "SafeMath: multiplication overflow"); 104 | 105 | return c; 106 | } 107 | 108 | /** 109 | * @dev Returns the multiplication of two unsigned integers, reverting on overflow. 110 | * 111 | * Counterpart to Solidity's `*` operator. 112 | * 113 | * Requirements: 114 | * - Multiplication cannot overflow. 115 | */ 116 | function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 117 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the 118 | // benefit is lost if 'b' is also tested. 119 | // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 120 | if (a == 0) { 121 | return 0; 122 | } 123 | 124 | uint256 c = a * b; 125 | require(c / a == b, errorMessage); 126 | 127 | return c; 128 | } 129 | 130 | /** 131 | * @dev Returns the integer division of two unsigned integers. 132 | * Reverts on division by zero. The result is rounded towards zero. 133 | * 134 | * Counterpart to Solidity's `/` operator. Note: this function uses a 135 | * `revert` opcode (which leaves remaining gas untouched) while Solidity 136 | * uses an invalid opcode to revert (consuming all remaining gas). 137 | * 138 | * Requirements: 139 | * - The divisor cannot be zero. 140 | */ 141 | function div(uint256 a, uint256 b) internal pure returns (uint256) { 142 | return div(a, b, "SafeMath: division by zero"); 143 | } 144 | 145 | /** 146 | * @dev Returns the integer division of two unsigned integers. 147 | * Reverts with custom message on division by zero. The result is rounded towards zero. 148 | * 149 | * Counterpart to Solidity's `/` operator. Note: this function uses a 150 | * `revert` opcode (which leaves remaining gas untouched) while Solidity 151 | * uses an invalid opcode to revert (consuming all remaining gas). 152 | * 153 | * Requirements: 154 | * - The divisor cannot be zero. 155 | */ 156 | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 157 | // Solidity only automatically asserts when dividing by 0 158 | require(b > 0, errorMessage); 159 | uint256 c = a / b; 160 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold 161 | 162 | return c; 163 | } 164 | 165 | /** 166 | * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 167 | * Reverts when dividing by zero. 168 | * 169 | * Counterpart to Solidity's `%` operator. This function uses a `revert` 170 | * opcode (which leaves remaining gas untouched) while Solidity uses an 171 | * invalid opcode to revert (consuming all remaining gas). 172 | * 173 | * Requirements: 174 | * - The divisor cannot be zero. 175 | */ 176 | function mod(uint256 a, uint256 b) internal pure returns (uint256) { 177 | return mod(a, b, "SafeMath: modulo by zero"); 178 | } 179 | 180 | /** 181 | * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), 182 | * Reverts with custom message when dividing by zero. 183 | * 184 | * Counterpart to Solidity's `%` operator. This function uses a `revert` 185 | * opcode (which leaves remaining gas untouched) while Solidity uses an 186 | * invalid opcode to revert (consuming all remaining gas). 187 | * 188 | * Requirements: 189 | * - The divisor cannot be zero. 190 | */ 191 | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 192 | require(b != 0, errorMessage); 193 | return a % b; 194 | } 195 | } 196 | 197 | contract Uni { 198 | /// @notice EIP-20 token name for this token 199 | string public constant name = "Uniswap"; 200 | 201 | /// @notice EIP-20 token symbol for this token 202 | string public constant symbol = "UNI"; 203 | 204 | /// @notice EIP-20 token decimals for this token 205 | uint8 public constant decimals = 18; 206 | 207 | /// @notice Total number of tokens in circulation 208 | uint public totalSupply = 1_000_000_000e18; // 1 billion Uni 209 | 210 | /// @notice Address which may mint new tokens 211 | address public minter; 212 | 213 | /// @notice The timestamp after which minting may occur 214 | uint public mintingAllowedAfter; 215 | 216 | /// @notice Minimum time between mints 217 | uint32 public constant minimumTimeBetweenMints = 1 days * 365; 218 | 219 | /// @notice Cap on the percentage of totalSupply that can be minted at each mint 220 | uint8 public constant mintCap = 2; 221 | 222 | /// @notice Allowance amounts on behalf of others 223 | mapping (address => mapping (address => uint96)) internal allowances; 224 | 225 | /// @notice Official record of token balances for each account 226 | mapping (address => uint96) internal balances; 227 | 228 | /// @notice A record of each accounts delegate 229 | mapping (address => address) public delegates; 230 | 231 | /// @notice A checkpoint for marking number of votes from a given block 232 | struct Checkpoint { 233 | uint32 fromBlock; 234 | uint96 votes; 235 | } 236 | 237 | /// @notice A record of votes checkpoints for each account, by index 238 | mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; 239 | 240 | /// @notice The number of checkpoints for each account 241 | mapping (address => uint32) public numCheckpoints; 242 | 243 | /// @notice The EIP-712 typehash for the contract's domain 244 | bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); 245 | 246 | /// @notice The EIP-712 typehash for the delegation struct used by the contract 247 | bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); 248 | 249 | /// @notice The EIP-712 typehash for the permit struct used by the contract 250 | bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); 251 | 252 | /// @notice A record of states for signing / validating signatures 253 | mapping (address => uint) public nonces; 254 | 255 | /// @notice An event thats emitted when the minter address is changed 256 | event MinterChanged(address minter, address newMinter); 257 | 258 | /// @notice An event thats emitted when an account changes its delegate 259 | event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); 260 | 261 | /// @notice An event thats emitted when a delegate account's vote balance changes 262 | event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); 263 | 264 | /// @notice The standard EIP-20 transfer event 265 | event Transfer(address indexed from, address indexed to, uint256 amount); 266 | 267 | /// @notice The standard EIP-20 approval event 268 | event Approval(address indexed owner, address indexed spender, uint256 amount); 269 | 270 | /** 271 | * @notice Construct a new Uni token 272 | * @param account The initial account to grant all the tokens 273 | * @param minter_ The account with minting ability 274 | * @param mintingAllowedAfter_ The timestamp after which minting may occur 275 | */ 276 | constructor(address account, address minter_, uint mintingAllowedAfter_) public { 277 | require(mintingAllowedAfter_ >= block.timestamp, "Uni::constructor: minting can only begin after deployment"); 278 | 279 | balances[account] = uint96(totalSupply); 280 | emit Transfer(address(0), account, totalSupply); 281 | minter = minter_; 282 | emit MinterChanged(address(0), minter); 283 | mintingAllowedAfter = mintingAllowedAfter_; 284 | } 285 | 286 | /** 287 | * @notice Change the minter address 288 | * @param minter_ The address of the new minter 289 | */ 290 | function setMinter(address minter_) external { 291 | require(msg.sender == minter, "Uni::setMinter: only the minter can change the minter address"); 292 | emit MinterChanged(minter, minter_); 293 | minter = minter_; 294 | } 295 | 296 | /** 297 | * @notice Mint new tokens 298 | * @param dst The address of the destination account 299 | * @param rawAmount The number of tokens to be minted 300 | */ 301 | function mint(address dst, uint rawAmount) external { 302 | require(msg.sender == minter, "Uni::mint: only the minter can mint"); 303 | require(block.timestamp >= mintingAllowedAfter, "Uni::mint: minting not allowed yet"); 304 | require(dst != address(0), "Uni::mint: cannot transfer to the zero address"); 305 | 306 | // record the mint 307 | mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); 308 | 309 | // mint the amount 310 | uint96 amount = safe96(rawAmount, "Uni::mint: amount exceeds 96 bits"); 311 | require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Uni::mint: exceeded mint cap"); 312 | totalSupply = safe96(SafeMath.add(totalSupply, amount), "Uni::mint: totalSupply exceeds 96 bits"); 313 | 314 | // transfer the amount to the recipient 315 | balances[dst] = add96(balances[dst], amount, "Uni::mint: transfer amount overflows"); 316 | emit Transfer(address(0), dst, amount); 317 | 318 | // move delegates 319 | _moveDelegates(address(0), delegates[dst], amount); 320 | } 321 | 322 | /** 323 | * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` 324 | * @param account The address of the account holding the funds 325 | * @param spender The address of the account spending the funds 326 | * @return The number of tokens approved 327 | */ 328 | function allowance(address account, address spender) external view returns (uint) { 329 | return allowances[account][spender]; 330 | } 331 | 332 | /** 333 | * @notice Approve `spender` to transfer up to `amount` from `src` 334 | * @dev This will overwrite the approval amount for `spender` 335 | * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) 336 | * @param spender The address of the account which may transfer tokens 337 | * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) 338 | * @return Whether or not the approval succeeded 339 | */ 340 | function approve(address spender, uint rawAmount) external returns (bool) { 341 | uint96 amount; 342 | if (rawAmount == uint(-1)) { 343 | amount = uint96(-1); 344 | } else { 345 | amount = safe96(rawAmount, "Uni::approve: amount exceeds 96 bits"); 346 | } 347 | 348 | allowances[msg.sender][spender] = amount; 349 | 350 | emit Approval(msg.sender, spender, amount); 351 | return true; 352 | } 353 | 354 | /** 355 | * @notice Triggers an approval from owner to spends 356 | * @param owner The address to approve from 357 | * @param spender The address to be approved 358 | * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) 359 | * @param deadline The time at which to expire the signature 360 | * @param v The recovery byte of the signature 361 | * @param r Half of the ECDSA signature pair 362 | * @param s Half of the ECDSA signature pair 363 | */ 364 | function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { 365 | uint96 amount; 366 | if (rawAmount == uint(-1)) { 367 | amount = uint96(-1); 368 | } else { 369 | amount = safe96(rawAmount, "Uni::permit: amount exceeds 96 bits"); 370 | } 371 | 372 | bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); 373 | bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); 374 | bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); 375 | address signatory = ecrecover(digest, v, r, s); 376 | require(signatory != address(0), "Uni::permit: invalid signature"); 377 | require(signatory == owner, "Uni::permit: unauthorized"); 378 | require(now <= deadline, "Uni::permit: signature expired"); 379 | 380 | allowances[owner][spender] = amount; 381 | 382 | emit Approval(owner, spender, amount); 383 | } 384 | 385 | /** 386 | * @notice Get the number of tokens held by the `account` 387 | * @param account The address of the account to get the balance of 388 | * @return The number of tokens held 389 | */ 390 | function balanceOf(address account) external view returns (uint) { 391 | return balances[account]; 392 | } 393 | 394 | /** 395 | * @notice Transfer `amount` tokens from `msg.sender` to `dst` 396 | * @param dst The address of the destination account 397 | * @param rawAmount The number of tokens to transfer 398 | * @return Whether or not the transfer succeeded 399 | */ 400 | function transfer(address dst, uint rawAmount) external returns (bool) { 401 | uint96 amount = safe96(rawAmount, "Uni::transfer: amount exceeds 96 bits"); 402 | _transferTokens(msg.sender, dst, amount); 403 | return true; 404 | } 405 | 406 | /** 407 | * @notice Transfer `amount` tokens from `src` to `dst` 408 | * @param src The address of the source account 409 | * @param dst The address of the destination account 410 | * @param rawAmount The number of tokens to transfer 411 | * @return Whether or not the transfer succeeded 412 | */ 413 | function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { 414 | address spender = msg.sender; 415 | uint96 spenderAllowance = allowances[src][spender]; 416 | uint96 amount = safe96(rawAmount, "Uni::approve: amount exceeds 96 bits"); 417 | 418 | if (spender != src && spenderAllowance != uint96(-1)) { 419 | uint96 newAllowance = sub96(spenderAllowance, amount, "Uni::transferFrom: transfer amount exceeds spender allowance"); 420 | allowances[src][spender] = newAllowance; 421 | 422 | emit Approval(src, spender, newAllowance); 423 | } 424 | 425 | _transferTokens(src, dst, amount); 426 | return true; 427 | } 428 | 429 | /** 430 | * @notice Delegate votes from `msg.sender` to `delegatee` 431 | * @param delegatee The address to delegate votes to 432 | */ 433 | function delegate(address delegatee) public { 434 | return _delegate(msg.sender, delegatee); 435 | } 436 | 437 | /** 438 | * @notice Delegates votes from signatory to `delegatee` 439 | * @param delegatee The address to delegate votes to 440 | * @param nonce The contract state required to match the signature 441 | * @param expiry The time at which to expire the signature 442 | * @param v The recovery byte of the signature 443 | * @param r Half of the ECDSA signature pair 444 | * @param s Half of the ECDSA signature pair 445 | */ 446 | function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { 447 | bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); 448 | bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); 449 | bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); 450 | address signatory = ecrecover(digest, v, r, s); 451 | require(signatory != address(0), "Uni::delegateBySig: invalid signature"); 452 | require(nonce == nonces[signatory]++, "Uni::delegateBySig: invalid nonce"); 453 | require(now <= expiry, "Uni::delegateBySig: signature expired"); 454 | return _delegate(signatory, delegatee); 455 | } 456 | 457 | /** 458 | * @notice Gets the current votes balance for `account` 459 | * @param account The address to get votes balance 460 | * @return The number of current votes for `account` 461 | */ 462 | function getCurrentVotes(address account) external view returns (uint96) { 463 | uint32 nCheckpoints = numCheckpoints[account]; 464 | return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; 465 | } 466 | 467 | /** 468 | * @notice Determine the prior number of votes for an account as of a block number 469 | * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. 470 | * @param account The address of the account to check 471 | * @param blockNumber The block number to get the vote balance at 472 | * @return The number of votes the account had as of the given block 473 | */ 474 | function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { 475 | require(blockNumber < block.number, "Uni::getPriorVotes: not yet determined"); 476 | 477 | uint32 nCheckpoints = numCheckpoints[account]; 478 | if (nCheckpoints == 0) { 479 | return 0; 480 | } 481 | 482 | // First check most recent balance 483 | if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { 484 | return checkpoints[account][nCheckpoints - 1].votes; 485 | } 486 | 487 | // Next check implicit zero balance 488 | if (checkpoints[account][0].fromBlock > blockNumber) { 489 | return 0; 490 | } 491 | 492 | uint32 lower = 0; 493 | uint32 upper = nCheckpoints - 1; 494 | while (upper > lower) { 495 | uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow 496 | Checkpoint memory cp = checkpoints[account][center]; 497 | if (cp.fromBlock == blockNumber) { 498 | return cp.votes; 499 | } else if (cp.fromBlock < blockNumber) { 500 | lower = center; 501 | } else { 502 | upper = center - 1; 503 | } 504 | } 505 | return checkpoints[account][lower].votes; 506 | } 507 | 508 | function _delegate(address delegator, address delegatee) internal { 509 | address currentDelegate = delegates[delegator]; 510 | uint96 delegatorBalance = balances[delegator]; 511 | delegates[delegator] = delegatee; 512 | 513 | emit DelegateChanged(delegator, currentDelegate, delegatee); 514 | 515 | _moveDelegates(currentDelegate, delegatee, delegatorBalance); 516 | } 517 | 518 | function _transferTokens(address src, address dst, uint96 amount) internal { 519 | require(src != address(0), "Uni::_transferTokens: cannot transfer from the zero address"); 520 | require(dst != address(0), "Uni::_transferTokens: cannot transfer to the zero address"); 521 | 522 | balances[src] = sub96(balances[src], amount, "Uni::_transferTokens: transfer amount exceeds balance"); 523 | balances[dst] = add96(balances[dst], amount, "Uni::_transferTokens: transfer amount overflows"); 524 | emit Transfer(src, dst, amount); 525 | 526 | _moveDelegates(delegates[src], delegates[dst], amount); 527 | } 528 | 529 | function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { 530 | if (srcRep != dstRep && amount > 0) { 531 | if (srcRep != address(0)) { 532 | uint32 srcRepNum = numCheckpoints[srcRep]; 533 | uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; 534 | uint96 srcRepNew = sub96(srcRepOld, amount, "Uni::_moveVotes: vote amount underflows"); 535 | _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); 536 | } 537 | 538 | if (dstRep != address(0)) { 539 | uint32 dstRepNum = numCheckpoints[dstRep]; 540 | uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; 541 | uint96 dstRepNew = add96(dstRepOld, amount, "Uni::_moveVotes: vote amount overflows"); 542 | _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); 543 | } 544 | } 545 | } 546 | 547 | function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { 548 | uint32 blockNumber = safe32(block.number, "Uni::_writeCheckpoint: block number exceeds 32 bits"); 549 | 550 | if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { 551 | checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; 552 | } else { 553 | checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); 554 | numCheckpoints[delegatee] = nCheckpoints + 1; 555 | } 556 | 557 | emit DelegateVotesChanged(delegatee, oldVotes, newVotes); 558 | } 559 | 560 | function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { 561 | require(n < 2**32, errorMessage); 562 | return uint32(n); 563 | } 564 | 565 | function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { 566 | require(n < 2**96, errorMessage); 567 | return uint96(n); 568 | } 569 | 570 | function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { 571 | uint96 c = a + b; 572 | require(c >= a, errorMessage); 573 | return c; 574 | } 575 | 576 | function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { 577 | require(b <= a, errorMessage); 578 | return a - b; 579 | } 580 | 581 | function getChainId() internal pure returns (uint) { 582 | uint256 chainId; 583 | assembly { chainId := chainid() } 584 | return chainId; 585 | } 586 | } 587 | --------------------------------------------------------------------------------