def manual_etherscan(): """Manual test verification on EtherScan.io.""" contract_name = "PresaleFundCollector" address = "0xb589ef3af084cc5ec905d23112520ec168478582" constructor_args = "000000000000000000000000e8baf9df0ded92c5f28aab97f13936e7716a4a5b00000000000000000000000000000000000000000000000000000000590ba32f000000000000000000000000000000000000000000000002b5e3af16b1880000" libraries = {'SafeMathLib': '0x8fd011ad5d39da2f0a09c2d89e7d6ae861fe42ba'} p = Project() chain_name = "mainnet" verify_contract(project=p, chain_name=chain_name, address=address, contract_name="PresaleFundCollector", contract_filename="PresaleFundCollector.sol", constructor_args=constructor_args, libraries=libraries)
def manual_etherscan(): """Manual test verification on EtherScan.io.""" contract_name = "PresaleFundCollector" address = "0xb589ef3af084cc5ec905d23112520ec168478582" constructor_args = "000000000000000000000000e8baf9df0ded92c5f28aab97f13936e7716a4a5b00000000000000000000000000000000000000000000000000000000590ba32f000000000000000000000000000000000000000000000002b5e3af16b1880000" libraries = {'SafeMathLib': '0x8fd011ad5d39da2f0a09c2d89e7d6ae861fe42ba'} p = Project() chain_name = "mainnet" verify_contract( project=p, chain_name=chain_name, address=address, contract_name="PresaleFundCollector", contract_filename="PresaleFundCollector.sol", constructor_args=constructor_args, libraries=libraries)
def deploy(project: Project, chain, chain_name, web3: Web3, address: str, token: Contract, freeze_ends_at: int, tokens_to_be_allocated: int): # TODO: Fix Populus support this via an deploy argument if "JSONFile" in chain.registrar.registrar_backends: del chain.registrar.registrar_backends["JSONFile"] freeze_ends_at = int(freeze_ends_at) assert freeze_ends_at > 0 assert tokens_to_be_allocated > 0 # Create issuer contract args = [ address, freeze_ends_at, token.address, tokens_to_be_allocated, ] transaction = { "from": address, } print("Deploying new TokenVault contract", args) token_vault, txhash = chain.provider.deploy_contract( "TokenVault", deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) const_args = get_constructor_arguments(token_vault, args) fname = "TokenVault.sol" browser_driver = "chrome" verify_contract(project=project, libraries={}, chain_name=chain_name, address=token_vault.address, contract_name="TokenVault", contract_filename=fname, constructor_args=const_args, browser_driver=browser_driver) link = get_etherscan_link(chain_name, token_vault.address) print("TokenVault verified contract is", link) return token_vault
def deploy(project: Project, chain, chain_name, web3: Web3, address: str, token: Contract, freeze_ends_at: int, tokens_to_be_allocated: int): # TODO: Fix Populus support this via an deploy argument if "JSONFile" in chain.registrar.registrar_backends: del chain.registrar.registrar_backends["JSONFile"] freeze_ends_at = int(freeze_ends_at) assert freeze_ends_at > 0 assert tokens_to_be_allocated > 0 # Create issuer contract args = [ address, freeze_ends_at, token.address, tokens_to_be_allocated, ] transaction = { "from": address, } print("Deploying new TokenVault contract", args) token_vault, txhash = chain.provider.deploy_contract("TokenVault", deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) const_args = get_constructor_arguments(token_vault, args) fname = "TokenVault.sol" browser_driver = "chrome" verify_contract( project=project, libraries={}, chain_name=chain_name, address=token_vault.address, contract_name="TokenVault", contract_filename=fname, constructor_args=const_args, browser_driver=browser_driver) link = get_etherscan_link(chain_name, token_vault.address) print("TokenVault verified contract is", link) return token_vault
def deploy_crowdsale(project: Project, chain, source_definitions: dict, deploy_address) -> Tuple[dict, dict, dict]: """Deploy multiple contracts from crowdsale definitions. :param chain: Populus chain object :param data: One of mainnet/ropsten parsed data definitions in a YAML file :return: Tuple (expaneded definitions, statistics, contract object map). The expanded definitions are run-time data that has everything expanded out and actual contract addresses """ statistics = Counter() # This will contain our output and parsed values runtime_data = copy.deepcopy(source_definitions) # Contract handles for post-actions contracts = {} # Store the address we used for the deployment runtime_data["deploy_address"] = deploy_address chain_name = runtime_data["chain"] verify_on_etherscan = asbool(runtime_data["verify_on_etherscan"]) browser_driver = runtime_data.get("browser_driver", "chrome") need_unlock = runtime_data.get("unlock_deploy_address", True) for name, contract_def in runtime_data["contracts"].items(): contract_name = contract_def["contract_name"] # First expand out all variables address = contract_def.get("address") if address: print("Already deployed contract,", name, address) Contract = getattr(chain.contract_factories, contract_name) contracts[name] = Contract(address=address) statistics["already_deployed"] += 1 continue # Expand Jinja templated variables for this contract context = get_jinja_context(runtime_data) try: expanded_contract_def = interpolate_data(contract_def, context) except jinja2.exceptions.TemplateError as e: raise RuntimeError( "Could not expand data for section {}".format(name)) from e # Store expanded data for output runtime_data["contracts"][name] = expanded_contract_def contracts[name] = deploy_contract(project, chain, deploy_address, expanded_contract_def, chain_name, need_unlock=need_unlock) statistics["deployed"] += 1 # Perform manual verification of the deployed contract if verify_on_etherscan: fname = runtime_data["contracts"][name]["contract_file"] src = verify_contract( project=project, chain_name=chain_name, address=runtime_data["contracts"][name]["address"], contract_name=contract_name, contract_filename=fname, constructor_args=runtime_data["contracts"][name] ["constructor_args"], libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver) runtime_data["contracts"][name][ "etherscan_link"] = get_etherscan_link( chain_name, runtime_data["contracts"][name]["address"]) # Write out our expanded contract expanded_path = os.path.join(os.getcwd(), "build", "expanded", fname) with open(expanded_path, "wt") as out: out.write(src) return runtime_data, statistics, contracts
def main(chain, address, token, csv_file, limit, start_from, issuer_address, address_column, amount_column, allow_zero, master_address): """Distribute tokens to centrally issued crowdsale participant. Reads in distribution data as CSV. Then uses Issuer contract to distribute tokens. All token counts are multiplied by token contract decimal specifier. E.g. if CSV has amount 15.5, token has 2 decimal places, we will issue out 1550 raw token amount. To speed up the issuance, transactions are verified in batches. Each batch is 16 transactions at a time. Example (first run): distribute-tokens --chain=kovan --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --token=0x1644a421ae0a0869bac127fa4cce8513bd666705 --csv-file=input.csv --allow-zero --address-column="Ethereum address" --amount-column="Golden tickets earned" Example (second run, continue after first run was interrupted): distribute-tokens --chain=kovan --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --token=0x1644a421ae0a0869bac127fa4cce8513bd666705 --csv-file=input.csv --allow-zero --address-column="Ethereum address" --amount-column="Golden tickets earned" --issuer-address=0x2c9877534f62c8b40aebcd08ec9f54d20cb0a945 """ project = Project() with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Owner address is", address) print("Owner balance is", from_wei(web3.eth.getBalance(address), "ether"), "ETH") # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, timeout=3600*6) assert not is_account_locked(web3, address) Token = c.provider.get_base_contract_factory('CentrallyIssuedToken') token = Token(address=token) print("Total supply is", token.call().totalSupply()) print("Upgrade master is", token.call().upgradeMaster()) print("Owner token balance master is", token.call().balanceOf(address)) decimals = token.call().decimals() print("Token decimal places is", decimals) assert decimals >= 0 decimal_multiplier = 10**decimals transaction = {"from": address} Issuer = c.provider.get_base_contract_factory('Issuer') if not issuer_address: # TODO: Fix Populus support this via an deploy argument if "JSONFile" in c.registrar.registrar_backends: del c.registrar.registrar_backends["JSONFile"] # Create issuer contract assert master_address, "You need to give master-address" args = [address, master_address, token.address] print("Deploying new issuer contract", args) issuer, txhash = c.provider.deploy_contract("Issuer", deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) const_args = get_constructor_arguments(issuer, args) chain_name = chain fname = "Issuer.sol" browser_driver = "chrome" verify_contract( project=project, libraries={}, # TODO: Figure out how to pass around chain_name=chain_name, address=issuer.address, contract_name="Issuer", contract_filename=fname, constructor_args=const_args, # libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver) link = get_etherscan_link(chain_name, issuer.address) print("Issuer verified contract is", link) else: print("Reusing existing issuer contract") issuer = Issuer(address=issuer_address) print("Issuer contract is", issuer.address) print("Currently issued", issuer.call().issuedCount()) if not master_address: sys.exit("Please use Token.approve() to give some allowance for the issuer contract by master address") allowance = token.call().allowance(master_address, issuer.address) print("Issuer allowance", allowance) if allowance == 0 or not master_address: sys.exit("Please use Token.approve() to give some allowance for the issuer contract by master address") print("Reading data", csv_file) with open(csv_file, "rt") as inp: reader = csv.DictReader(inp) rows = [row for row in reader] # Check that we have unique addresses uniq_addresses = set() for row in rows: addr = row[address_column].strip() if addr in uniq_addresses: raise RuntimeError("Address appears twice in input data", addr) uniq_addresses.add(addr) # Start distribution start_time = time.time() start_balance = from_wei(web3.eth.getBalance(address), "ether") tx_to_confirm = [] # List of txids to confirm tx_batch_size = 16 # How many transactions confirm once print("Total rows", len(rows)) for i in range(start_from, min(start_from+limit, len(rows))): data = rows[i] addr = data[address_column].strip() tokens = Decimal(data[amount_column].strip()) tokens *= decimal_multiplier end_balance = from_wei(web3.eth.getBalance(address), "ether") spent = start_balance - end_balance if tokens == 0: if not allow_zero: raise RuntimeError("Encountered zero amount") else: continue # http://stackoverflow.com/a/19965088/315168 if not tokens % 1 == 0: raise RuntimeError("Could not issue tokens because after multiplication was not integer") tokens = int(tokens) print("Row", i, "giving", tokens, "to", addr, "issuer", issuer.address, "time passed", time.time() - start_time, "ETH passed", spent) if issuer.call().issued(addr): print("Already issued, skipping") continue txid = issuer.transact(transaction).issue(addr, tokens) tx_to_confirm.append(txid) # Confirm N transactions when batch max size is reached if len(tx_to_confirm) >= tx_batch_size: check_multiple_succesful_txs(web3, tx_to_confirm) tx_to_confirm = [] # Confirm dangling transactions check_multiple_succesful_txs(web3, tx_to_confirm) end_balance = from_wei(web3.eth.getBalance(address), "ether") print("Deployment cost is", start_balance - end_balance, "ETH") print("All done! Enjoy your decentralized future.")
def main(chain, address, owner, days, minimum, verify): """Deploy a PresaleFundCollector contract. Example: deploy-presale --chain=ropsten --address=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --owner=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --days=30 --minimum=30 """ project = Project() # Parse command line args to presale constructor args minimum = to_wei(minimum, "ether") freeze_ends_at = int(utc_time() + days * 24 * 3600) contract_name = "PresaleFundCollector" # This is configured in populus.json # We are working on a testnet print( "Make sure {} chain is running, you can connect to it, or you'll get timeout" .format(chain)) with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Deploy address is", address) if not address: sys.exit( "You need to explicitly give the address from where we are deploying from" ) print("Deploy address balance is", from_wei(web3.eth.getBalance(address), "ether")) # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, None) transaction = {"from": address} args = [owner, freeze_ends_at, minimum] # This does deployment with all dependencies linked in print("Deploying contracts") presale, txhash = c.provider.deploy_contract( contract_name, deploy_transaction=transaction, deploy_args=args) print("Deploying presale, tx hash is", txhash) print("Presale contract address is", presale.address) libraries = get_libraries(c, contract_name, presale) print("Linked libraries are", libraries) # This is needed for Etherscan contract verification # https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments constructor_args = get_constructor_arguments(presale, args) print("Presale constructor arguments is", constructor_args) if verify: print("Verifying contract") verify_contract(project=project, chain_name=chain, address=presale.address, contract_name="PresaleFundCollector", contract_filename="PresaleFundCollector.sol", constructor_args=constructor_args, libraries=libraries) # Do some contract reads to see everything looks ok print("Presale freeze ends at", presale.call().freezeEndsAt()) print("Presale minimum buy in (wei) is", presale.call().weiMinimumLimit()) # Estimate invest() gas cost estimation = presale.estimateGas(transaction={ "from": address, "value": to_wei(1000, "ether") }).invest() print("Presale.invest() estimated gas cost is", estimation) sig_data = presale._prepare_transaction("invest") print("Presale.invest() data payload is", sig_data["data"]) sig_data = presale._prepare_transaction("refund") print("Presale.refund() data payload is", sig_data["data"]) print("All done! Enjoy your decentralized future.")
def main(chain, address, contract_name, name, symbol, supply, decimals, minting_agent, release_agent, verify, verify_filename, master_address): """Deploy a single crowdsale token contract. THIS COMMAND IS DEPRECATED. PLEASE USE deploy-contracts instead. Examples: deploy-token --chain=ropsten --address=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --name="MikkoToken 2.0" --symbol=MOO --release-agent=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --supply=100000 deploy-token --chain=kovan --contract-name="CentrallyIssuedToken" --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --name="TestToken" --symbol=MOO --supply=916 --decimals=0 --verify --verify-filename=CentrallyIssuedToken.sol """ project = Project() with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Deployer address is", address) print("Deployer balance is", from_wei(web3.eth.getBalance(address), "ether"), "ETH") # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, None) decimal_multiplier = 10**decimals transaction = {"from": address} args = [name, symbol, supply * decimal_multiplier, decimals] if contract_name == "CentrallyIssuedToken": # TODO: Generalize settings contract args # This sets the upgrade master args = [address] + args # Make sure Populus does not pull up any cached instances of deployed contracts # TODO: Fix Populus support this via an deploy argument if "JSONFile" in c.registrar.registrar_backends: del c.registrar.registrar_backends["JSONFile"] print("Starting contract deployment") # This does deployment with all dependencies linked in contract, txhash = c.provider.deploy_contract( contract_name, deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) print("Contract address is", contract.address) # This is needed for Etherscan contract verification # https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments const_args = get_constructor_arguments(contract, args) print("CrowdsaleToken constructor arguments is", const_args) if release_agent: print("Setting release agent to", release_agent) txid = contract.functions.setReleaseAgent(release_agent).transact( transaction) check_succesful_tx(web3, txid) if minting_agent: print("Setting minting agent") txid = contract.functions.setMintAgent(minting_agent, True).transact(transaction) check_succesful_tx(web3, txid) if master_address: print("Moving upgrade master to a team multisig wallet", master_address) txid = contract.functions.setUpgradeMaster( master_address).transact({"from": address}) check_succesful_tx(web3, txid) print("Moving total supply a team multisig wallet", master_address) contract.functions.transfer( master_address, contract.functions.totalSupply().call()).transact( {"from": address}) check_succesful_tx(web3, txid) if verify: chain_name = chain fname = verify_filename browser_driver = "chrome" verify_contract( project=project, libraries={}, # TODO: Figure out how to pass around chain_name=chain_name, address=contract.address, contract_name=contract_name, contract_filename=fname, constructor_args=const_args, # libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver) link = get_etherscan_link(chain_name, contract.address) print("Verified contract is", link) print("Token supply:", contract.functions.totalSupply().call()) # Do some contract reads to see everything looks ok try: print("Token owner:", contract.functions.owner().call()) except ValueError: pass # No owner try: print("Token upgradeMaster:", contract.functions.upgradeMaster().call()) except ValueError: pass try: print("Token minting finished:", contract.functions.mintingFinished().call()) except ValueError: pass try: print("Token released:", contract.functions.released().call()) print("Token release agent:", contract.functions.releaseAgent().call()) except ValueError: pass print("All done! Enjoy your decentralized future.")
def main(chain, address, token, csv_file, limit, start_from, issuer_address, address_column, amount_column, external_id_column, allow_addresless, master_address, gas_price, solc_version): """Distribute tokens to centrally issued crowdsale participant or bounty program participants using an external key. Reads in distribution data as CSV. Then uses Issuer contract to distribute tokens. All token counts are multiplied by token contract decimal specifier. E.g. if CSV has amount 15.5, token has 2 decimal places, we will issue out 1550 raw token amount. The external id uniquely identifies participants. This is different from the distribute-tokens where the Ethereum address uniquely identifies participants. To speed up the issuance, transactions are verified in batches. Each batch is 16 transactions at a time. First have a issuer contract created: distribute-tokens-ext-id \ --chain=mainnet \ --address=0xccba4928c4e9d10242788d9cf144d865348c6c7f \ --token=0x1a7a8bd9106f2b8d977e08582dc7d24c723ab0db \ --master-address=0xa684a3371e0d46bca4a6db1ff538a44f1440a855 \ --csv-file=data.csv \ --address-column="Ethereum address" \ --amount-column="Token amount" \ --external-id-column="External ID number" \ --solc-version="v0.4.16+commit.d7661dd9" \ --gas-price=100 Then perform EIP-20 approve() to give tokens to the issuer contract deployed in the last command. Then run the distribution: distribute-tokens-ext-id \ --chain=mainnet \ --address=0xccba4928c4e9d10242788d9cf144d865348c6c7f \ --token=0x1a7a8bd9106f2b8d977e08582dc7d24c723ab0db \ --master-address=0xa684a3371e0d46bca4a6db1ff538a44f1440a855 \ --issuer-address=0x60cfb02266310e66dd99b1635e702c519a564726 \ --csv-file=combined.csv \ --address-column="Address" \ --amount-column="Amount" \ --gas-price=70 \ --start-from=670 """ project = Project() with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Deployer account address is", address) print("Deployer account balance is", from_wei(web3.eth.getBalance(address), "ether"), "ETH") # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, timeout=3600 * 6) assert not is_account_locked(web3, address) Token = c.provider.get_base_contract_factory('CentrallyIssuedToken') token = Token(address=token) print("Token is", token.address) print("Total supply is", token.functions.totalSupply().call()) print("Upgrade master is", token.functions.upgradeMaster().call()) print("Deployer account token balance is", token.functions.balanceOf(address).call()) decimals = token.functions.decimals().call() print("Token decimal places is", decimals) assert decimals >= 0 decimal_multiplier = 10**decimals if gas_price: gas_price = int(gas_price) * 10**9 else: gas_price = web3.eth.gasPrice * 2 transaction = {"from": address, "gasPrice": gas_price} print("Using gas price of", gas_price / 10**9, "GWei") IssuerWithId = c.provider.get_base_contract_factory('IssuerWithId') if not issuer_address: # TODO: Fix Populus support this via an deploy argument if "JSONFile" in c.registrar.registrar_backends: del c.registrar.registrar_backends["JSONFile"] # Create issuer contract assert master_address, "You need to give master-address" args = [address, master_address, token.address] print("Deploying new issuer contract", args, "transaction parameters", transaction) issuer, txhash = c.provider.deploy_contract( "IssuerWithId", deploy_transaction=transaction, deploy_args=args) print("Deployment transaction is", txhash) print("Waiting contract to be deployed") check_succesful_tx(web3, txhash) const_args = get_constructor_arguments(issuer, args) print("Contract constructor arguments are", const_args) chain_name = chain fname = "IssuerWithId.sol" browser_driver = "chrome" verify_contract( project=project, libraries={}, # TODO: Figure out how to pass around chain_name=chain_name, address=issuer.address, contract_name="IssuerWithId", contract_filename=fname, constructor_args=const_args, browser_driver=browser_driver, compiler=solc_version) link = get_etherscan_link(chain_name, issuer.address) print("Issuer verified contract is", link) else: print("Using existing issuer contract") issuer = IssuerWithId(address=issuer_address) print("Issuer contract is", issuer.address) print("Currently issued", issuer.functions.issuedCount().call()) if not master_address: sys.exit( "Please use Token.approve() to give some allowance for the issuer contract by master address" ) allowance = token.functions.allowance(master_address, issuer.address).call() print("Issuer allowance", allowance) if allowance == 0 or not master_address: sys.exit( "Please use Token.approve() to give some allowance for the issuer contract by master address" ) print("Reading data", csv_file) with open(csv_file, "rt") as inp: reader = csv.DictReader(inp) rows = [row for row in reader] # Prevalidate addresses # For distributetokens.py this is done by combine-csv # Here we do it inline and make skip addresses that are not valid. for idx, row in enumerate(rows): addr = row[address_column].strip() try: if addr: validate_ethereum_address(addr) except ValueError as e: print("Invalid Ethereum address on row:", idx + 1, "address:", addr, "reason:", str(e), "external_id:", row[external_id_column]) # Proceed regardless of invalid data row[address_column] = "" # Start distribution start_time = time.time() start_balance = from_wei(web3.eth.getBalance(address), "ether") tx_to_confirm = [] # List of txids to confirm tx_batch_size = 16 # How many transactions confirm once print("Total rows", len(rows)) for i in range(start_from, min(start_from + limit, len(rows))): data = rows[i] addr = data[address_column].strip() external_id = data[external_id_column].strip() tokens = Decimal(data[amount_column].strip()) tokens *= decimal_multiplier end_balance = from_wei(web3.eth.getBalance(address), "ether") spent = start_balance - end_balance if addr == "": if not allow_addresless: raise RuntimeError("Encountered missing address") else: continue if not external_id: raise RuntimeError("Missing external id on row #{}".format(i + 1)) # http://stackoverflow.com/a/19965088/315168 if not tokens % 1 == 0: raise RuntimeError( "Could not issue tokens because after multiplication was not integer" ) transaction = { "from": address, "gasPrice": gas_price, "gas": 100000, # Use 100k gas unit limit } tokens = int(tokens) external_id = int(external_id) if not external_id > 0: raise RuntimeError( "External id must be a positive integer on row #{}".format( i + 1)) print("Row", i, "giving", tokens, "to", addr, "issuer", issuer.address, "time passed", time.time() - start_time, "ETH passed", spent, "gas price", transaction["gasPrice"] / (10**9)) if issuer.functions.issued(external_id).call(): print("Already issued, skipping") continue txid = issuer.functions.issue(addr, tokens, external_id).transact(transaction) tx_to_confirm.append(txid) # Confirm N transactions when batch max size is reached if len(tx_to_confirm) >= tx_batch_size: check_multiple_succesful_txs(web3, tx_to_confirm) tx_to_confirm = [] # Confirm dangling transactions check_multiple_succesful_txs(web3, tx_to_confirm) end_balance = from_wei(web3.eth.getBalance(address), "ether") print("Deployment cost is", start_balance - end_balance, "ETH") print("All done! Enjoy your decentralized future.")
def main(chain, address, token, csv_file, limit, start_from, issuer_address, address_column, amount_column, allow_zero, master_address): """Distribute tokens to centrally issued crowdsale participant or bounty program participants. Reads in distribution data as CSV. Then uses Issuer contract to distribute tokens. All token counts are multiplied by token contract decimal specifier. E.g. if CSV has amount 15.5, token has 2 decimal places, we will issue out 1550 raw token amount. To speed up the issuance, transactions are verified in batches. Each batch is 16 transactions at a time. Example (first run): distribute-tokens --chain=kovan --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --token=0x1644a421ae0a0869bac127fa4cce8513bd666705 --master-address=0x9a60ad6de185c4ea95058601beaf16f63742782a --csv-file=input.csv --allow-zero --address-column="Ethereum address" --amount-column="Token amount" Example (second run, continue after first run was interrupted): distribute-tokens --chain=kovan --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --token=0x1644a421ae0a0869bac127fa4cce8513bd666705 --csv-file=input.csv --allow-zero --address-column="Ethereum address" --amount-column="Token amount" --issuer-address=0x2c9877534f62c8b40aebcd08ec9f54d20cb0a945 """ project = Project() with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Owner address is", address) print("Owner balance is", from_wei(web3.eth.getBalance(address), "ether"), "ETH") # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, timeout=3600*6) assert not is_account_locked(web3, address) Token = c.provider.get_base_contract_factory('CentrallyIssuedToken') token = Token(address=token) print("Token is", token.address) print("Total supply is", token.call().totalSupply()) print("Upgrade master is", token.call().upgradeMaster()) print("Owner token balance master is", token.call().balanceOf(address)) decimals = token.call().decimals() print("Token decimal places is", decimals) assert decimals >= 0 decimal_multiplier = 10**decimals transaction = {"from": address} Issuer = c.provider.get_base_contract_factory('Issuer') if not issuer_address: # TODO: Fix Populus support this via an deploy argument if "JSONFile" in c.registrar.registrar_backends: del c.registrar.registrar_backends["JSONFile"] # Create issuer contract assert master_address, "You need to give master-address" args = [address, master_address, token.address] print("Deploying new issuer contract", args) issuer, txhash = c.provider.deploy_contract("Issuer", deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) const_args = get_constructor_arguments(issuer, args) chain_name = chain fname = "Issuer.sol" browser_driver = "chrome" verify_contract( project=project, libraries={}, # TODO: Figure out how to pass around chain_name=chain_name, address=issuer.address, contract_name="Issuer", contract_filename=fname, constructor_args=const_args, # libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver) link = get_etherscan_link(chain_name, issuer.address) print("Issuer verified contract is", link) else: print("Reusing existing issuer contract") issuer = Issuer(address=issuer_address) print("Issuer contract is", issuer.address) print("Currently issued", issuer.call().issuedCount()) if not master_address: sys.exit("Please use Token.approve() to give some allowance for the issuer contract by master address") allowance = token.call().allowance(master_address, issuer.address) print("Issuer allowance", allowance) if allowance == 0 or not master_address: sys.exit("Please use Token.approve() to give some allowance for the issuer contract by master address") print("Reading data", csv_file) with open(csv_file, "rt") as inp: reader = csv.DictReader(inp) rows = [row for row in reader] # Check that we have unique addresses uniq_addresses = set() for row in rows: addr = row[address_column].strip() if addr in uniq_addresses: raise RuntimeError("Address appears twice in input data", addr) uniq_addresses.add(addr) # Start distribution start_time = time.time() start_balance = from_wei(web3.eth.getBalance(address), "ether") tx_to_confirm = [] # List of txids to confirm tx_batch_size = 16 # How many transactions confirm once print("Total rows", len(rows)) for i in range(start_from, min(start_from+limit, len(rows))): data = rows[i] addr = data[address_column].strip() tokens = Decimal(data[amount_column].strip()) tokens *= decimal_multiplier end_balance = from_wei(web3.eth.getBalance(address), "ether") spent = start_balance - end_balance if tokens == 0: if not allow_zero: raise RuntimeError("Encountered zero amount") else: continue # http://stackoverflow.com/a/19965088/315168 if not tokens % 1 == 0: raise RuntimeError("Could not issue tokens because after multiplication was not integer") transaction = { "from": address, "gasPrice": int(web3.eth.gasPrice * 1.5) } tokens = int(tokens) print("Row", i, "giving", tokens, "to", addr, "issuer", issuer.address, "time passed", time.time() - start_time, "ETH passed", spent) if issuer.call().issued(addr): print("Already issued, skipping") continue txid = issuer.transact(transaction).issue(addr, tokens) tx_to_confirm.append(txid) # Confirm N transactions when batch max size is reached if len(tx_to_confirm) >= tx_batch_size: check_multiple_succesful_txs(web3, tx_to_confirm) tx_to_confirm = [] # Confirm dangling transactions check_multiple_succesful_txs(web3, tx_to_confirm) end_balance = from_wei(web3.eth.getBalance(address), "ether") print("Deployment cost is", start_balance - end_balance, "ETH") print("All done! Enjoy your decentralized future.")
def deploy_crowdsale(project: Project, chain, yaml_filename: str, source_definitions: dict, deploy_address) -> Tuple[dict, dict, dict]: """Deploy multiple contracts from crowdsale definitions. :param chain: Populus chain object :param data: One of mainnet/ropsten parsed data definitions in a YAML file :return: Tuple (expaneded definitions, statistics, contract object map). The expanded definitions are run-time data that has everything expanded out and actual contract addresses """ statistics = Counter() # This will contain our output and parsed values runtime_data = copy.deepcopy(source_definitions) # Contract handles for post-actions contracts = {} # Store the address we used for the deployment runtime_data["deploy_address"] = deploy_address chain_name = runtime_data["chain"] verify_on_etherscan = asbool(runtime_data["verify_on_etherscan"]) browser_driver = runtime_data.get("browser_driver", "chrome") solc = runtime_data["solc"] need_unlock = runtime_data.get("unlock_deploy_address", True) for name, contract_def in runtime_data["contracts"].items(): contract_name = contract_def["contract_name"] # First expand out all variables address = contract_def.get("address") if address: print("Already deployed contract,", name, address) Contract = get_contract_by_name(chain, contract_name) contracts[name] = Contract(address=address) statistics["already_deployed"] += 1 continue # Expand Jinja templated variables for this contract context = get_jinja_context(runtime_data) try: expanded_contract_def = interpolate_data(contract_def, context) except jinja2.exceptions.TemplateError as e: raise RuntimeError("Could not expand data for section {}".format(name)) from e # Store expanded data for output runtime_data["contracts"][name] = expanded_contract_def contracts[name] = deploy_contract(project, chain, deploy_address, expanded_contract_def, chain_name, need_unlock=need_unlock) statistics["deployed"] += 1 # Perform manual verification of the deployed contract if verify_on_etherscan: fname = runtime_data["contracts"][name]["contract_file"] src = verify_contract( project=project, chain_name=chain_name, address=runtime_data["contracts"][name]["address"], contract_name=contract_name, contract_filename=fname, constructor_args=runtime_data["contracts"][name]["constructor_args"], libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver, compiler=solc["version"], optimization=asbool(solc["optimizations"]["optimizer"]), optimizer_runs=int(solc["optimizations"]["runs"]) ) runtime_data["contracts"][name]["etherscan_link"] = get_etherscan_link(chain_name, runtime_data["contracts"][name]["address"]) # Write out our expanded contract expanded_path = os.path.join(os.getcwd(), "build", "expanded", fname) with open(expanded_path, "wt") as out: out.write(src) # Write the ongoing output, so we can use it e.g. to debug EtherScan verification write_deployment_report(yaml_filename, runtime_data, partial=True) return runtime_data, statistics, contracts
def main(chain, address, contract_name, name, symbol, supply, decimals, minting_agent, release_agent, verify, verify_filename, master_address): """Deploy a single crowdsale token contract. Examples: deploy-token --chain=ropsten --address=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --name="MikkoToken 2.0" --symbol=MOO --release-agent=0x3c2d4e5eae8c4a31ccc56075b5fd81307b1627c6 --supply=100000 deploy-token --chain=kovan --contract-name="CentrallyIssuedToken" --address=0x001FC7d7E506866aEAB82C11dA515E9DD6D02c25 --name="TestToken" --symbol=MOO --supply=916 --decimals=0 --verify --verify-filename=CentrallyIssuedToken.sol """ project = Project() with project.get_chain(chain) as c: web3 = c.web3 print("Web3 provider is", web3.currentProvider) print("Deployer address is", address) print("Deployer balance is", from_wei(web3.eth.getBalance(address), "ether"), "ETH") # Goes through geth account unlock process if needed if is_account_locked(web3, address): request_account_unlock(c, address, None) decimal_multiplier = 10 ** decimals transaction = {"from": address} args = [name, symbol, supply * decimal_multiplier, decimals] if contract_name == "CentrallyIssuedToken": # TODO: Generalize settings contract args # This sets the upgrade master args = [address] + args # Make sure Populus does not pull up any cached instances of deployed contracts # TODO: Fix Populus support this via an deploy argument if "JSONFile" in c.registrar.registrar_backends: del c.registrar.registrar_backends["JSONFile"] print("Starting contract deployment") # This does deployment with all dependencies linked in contract, txhash = c.provider.deploy_contract(contract_name, deploy_transaction=transaction, deploy_args=args) check_succesful_tx(web3, txhash) print("Contract address is", contract.address) # This is needed for Etherscan contract verification # https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments const_args = get_constructor_arguments(contract, args) print("CrowdsaleToken constructor arguments is", const_args) if release_agent: print("Setting release agent to", release_agent) txid = contract.transact(transaction).setReleaseAgent(release_agent) check_succesful_tx(web3, txid) if minting_agent: print("Setting minting agent") txid = contract.transact(transaction).setMintAgent(minting_agent, True) check_succesful_tx(web3, txid) if master_address: print("Moving upgrade master to a team multisig wallet", master_address) txid = contract.transact({"from": address}).setUpgradeMaster(master_address) check_succesful_tx(web3, txid) print("Moving total supply a team multisig wallet", master_address) contract.transact({"from": address}).transfer(master_address, contract.call().totalSupply()) check_succesful_tx(web3, txid) if verify: chain_name = chain fname = verify_filename browser_driver = "chrome" verify_contract( project=project, libraries={}, # TODO: Figure out how to pass around chain_name=chain_name, address=contract.address, contract_name=contract_name, contract_filename=fname, constructor_args=const_args, # libraries=runtime_data["contracts"][name]["libraries"], browser_driver=browser_driver) link = get_etherscan_link(chain_name, contract.address) print("Verified contract is", link) print("Token supply:", contract.call().totalSupply()) # Do some contract reads to see everything looks ok try: print("Token owner:", contract.call().owner()) except ValueError: pass # No owner try: print("Token upgradeMaster:", contract.call().upgradeMaster()) except ValueError: pass try: print("Token minting finished:", contract.call().mintingFinished()) except ValueError: pass try: print("Token released:", contract.call().released()) print("Token release agent:", contract.call().releaseAgent()) except ValueError: pass print("All done! Enjoy your decentralized future.")