diff --git a/dao/.dockerignore b/dao/.dockerignore deleted file mode 100644 index 7e96cc8..0000000 --- a/dao/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -build -node_modules/ -package-lock.json - diff --git a/dao/.gitignore b/dao/.gitignore deleted file mode 100644 index 77f0382..0000000 --- a/dao/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -build -node_modules/ -MetaCoin/ -package-lock.json -yarn-error.log -/.DS_Store -npm-debug.log -addresses.json -/.vscode diff --git a/dao/.soliumignore b/dao/.soliumignore deleted file mode 100644 index b512c09..0000000 --- a/dao/.soliumignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/dao/.soliumrc.json b/dao/.soliumrc.json deleted file mode 100644 index d3fe054..0000000 --- a/dao/.soliumrc.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "solium:all", - "rules": { - "indentation": ["error", 4], - "quotes": ["error", "double"], - "arg-overflow": "off", - "blank-lines": "off" - } -} \ No newline at end of file diff --git a/dao/Dockerfile b/dao/Dockerfile deleted file mode 100644 index 3e3f8fd..0000000 --- a/dao/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8 - -WORKDIR /dao - -COPY package.json . - -RUN \ - npm install -g truffle && \ - npm install - -COPY . . - diff --git a/dao/README.md b/dao/README.md deleted file mode 100644 index e826e25..0000000 --- a/dao/README.md +++ /dev/null @@ -1,153 +0,0 @@ -# SingularityNetwork -Includes contracts, migrations, tests, user interface and webpack build pipeline. - -## Design Specifications - -[Smart Contracts Design ](./docs/SNContractsDesignSpecs.md) - - -## Requirements - -* [Node.js](https://github.com/nodejs/node) (7.6 +) -* [Npm](https://www.npmjs.com/package/npm) - -## Install - -### Truffle -```bash -npm i -g truffle -``` - -### Ethereum -You can choose between Parity or local testrpc - -### ganache (formerly testrpc) -```bash -npm install -g ganache-cli -``` - -### Parity - **Parity requires Rust version 1.19.0 to build** - - Linux: - ```bash - $ curl https://sh.rustup.rs -sSf | sh - ``` - - Parity also requires `gcc`, `g++`, `libssl-dev`/`openssl`, `libudev-dev` and `pkg-config` packages to be installed. - - OSX: - ```bash - $ curl https://sh.rustup.rs -sSf | sh - ``` - - ##### Download and build Parity - - ```bash - # download Parity code - $ git clone https://github.com/paritytech/parity - $ cd parity - - # build in release mode - $ cargo build --release - ``` - - This will produce an executable in the `./target/release` subdirectory. - Note: if cargo fails to parse manifest try: - - ```bash - $ ~/.cargo/bin/cargo build --release - ``` - - #### Start Parity - To start Parity manually, just run - ```bash - $ ./target/release/parity - ``` - and Parity will begin syncing the Ethereum blockchain. - - ##### Hint - Add parity to your command list: - ```bash - cp /target/release/parity /usr/local/bin - ``` - - -## Build -1. First `cd dao && npm i` -2. `truffle compile` and run on separated tab `parity` or `testrpc` -3. `truffle migrate` to deploy the contracts onto your network of choice (default "development"). -5. `truffle test` - - -## Usage - -You can choose of using web3 with Python and Javascript - -Python ----------- - -Install web3 - -`pip install web3` - -Using Web3 - -To use the web3 library you will need to instantiate an instance of the -``Web3`` object. - - - >>> from web3 import Web3, HTTPProvider, IPCProvider - - # Note that you should create only one RPCProvider per - # process, as it recycles underlying TCP/IP network connections between - # your process and Ethereum node - >>> web3 = Web3(HTTPProvider('http://localhost:8545')) - - # or for an IPC based connection - >>> web3 = Web3(IPCProvider()) - >>> web3.eth.blockNumber - 4000000 - - -This ``web3`` instance will now allow you to interact with the Ethereum -blockchain. - - -Javascript ----------- - -`npm i -s web3` - -Create in /app folder an index.js file - -Use the `web3` object directly from global namespace: - -```js -console.log(web3); // {eth: .., shh: ...} // it's here! -``` - -Set a provider (HttpProvider) - -```js -if (typeof web3 !== 'undefined') { - web3 = new Web3(web3.currentProvider); -} else { - // set the provider you want from Web3.providers - web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); -} -``` - -Set a provider (HttpProvider using [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication)) - -```js -web3.setProvider(new web3.providers.HttpProvider('http://host.url', 0, BasicAuthUsername, BasicAuthPassword)); -``` - -There you go, now you can use it: - -```js -var coinbase = web3.eth.coinbase; -var balance = web3.eth.getBalance(coinbase); -``` - -You can find more examples in [`example`](https://github.com/ethereum/web3.js/tree/master/example) directory. - diff --git a/dao/contracts/Migrations.sol b/dao/contracts/Migrations.sol deleted file mode 100644 index d8c0d07..0000000 --- a/dao/contracts/Migrations.sol +++ /dev/null @@ -1,25 +0,0 @@ -pragma solidity ^0.4.18; - - -contract Migrations { - address public owner; - uint public last_completed_migration; - - modifier restricted() { - if (msg.sender == owner) - _; - } - - function Migrations() { - owner = msg.sender; - } - - function setCompleted(uint completed) restricted { - last_completed_migration = completed; - } - - function upgrade(address newAddress) restricted { - Migrations upgraded = Migrations(newAddress); - upgraded.setCompleted(last_completed_migration); - } -} diff --git a/dao/contracts/agent/Agent.sol b/dao/contracts/agent/Agent.sol deleted file mode 100644 index baca086..0000000 --- a/dao/contracts/agent/Agent.sol +++ /dev/null @@ -1,28 +0,0 @@ -pragma solidity ^0.4.18; - -import "./AgentInterface.sol"; -import "zeppelin-solidity/contracts/ownership/Ownable.sol"; - -contract Agent is AgentInterface, Ownable { - - bytes[] public packets; - MarketJobInterface public job; - - function sendPacket(address target, bytes packet) external onlyOwner { - Agent(target).appendPacket(packet); - } - - // @todo only people who can - function appendPacket(bytes packet) external { - packets.push(packet); - } - - function getPacket(uint id) external constant returns (bytes) { - return packets[id]; - } - - function setJob(MarketJob _job) external returns (address) { - job = _job; - } - -} diff --git a/dao/contracts/agent/AgentFactory.sol b/dao/contracts/agent/AgentFactory.sol deleted file mode 100644 index 77fe1e4..0000000 --- a/dao/contracts/agent/AgentFactory.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma solidity ^0.4.18; - -import "./Agent.sol"; - -contract AgentFactory { - - function create() public returns (Agent) { - return new Agent(); - } -} diff --git a/dao/contracts/agent/AgentInterface.sol b/dao/contracts/agent/AgentInterface.sol deleted file mode 100644 index 39fdf01..0000000 --- a/dao/contracts/agent/AgentInterface.sol +++ /dev/null @@ -1,12 +0,0 @@ -pragma solidity ^0.4.18; - -import "../market/MarketJob.sol"; - -contract AgentInterface { - - function sendPacket(address target, bytes packet) external; - function appendPacket(bytes packet) external; - function getPacket(uint id) external constant returns (bytes); - function setJob(MarketJob _job) external returns (address); - -} diff --git a/dao/contracts/foundation/AgiCrowdsale.sol b/dao/contracts/foundation/AgiCrowdsale.sol deleted file mode 100644 index 2030890..0000000 --- a/dao/contracts/foundation/AgiCrowdsale.sol +++ /dev/null @@ -1,192 +0,0 @@ -pragma solidity ^0.4.18; - -import "../tokens/SingularityNetToken.sol"; -import "zeppelin-solidity/contracts/math/SafeMath.sol"; -import "zeppelin-solidity/contracts/ReentrancyGuard.sol"; -import "zeppelin-solidity/contracts/ownership/Ownable.sol"; -import "zeppelin-solidity/contracts/crowdsale/RefundVault.sol"; - -/** - * @title AgiCrowdsale - * @dev AgiCrowdsale is a base contract for managing a token crowdsale. - * Crowdsales have a start and end timestamps, where investors can make - * token purchases and the crowdsale will assign them tokens based - * on a token per ETH rate. Funds collected are forwarded to a wallet - * as they arrive. - */ -contract AgiCrowdsale is Ownable, ReentrancyGuard { - using SafeMath for uint256; - - uint256 public cap; - uint256 public goal; - uint256 public rate; - uint256 public constant WEI_TO_COGS = 10**uint256(10); - - address public wallet; - RefundVault public vault; - SingularityNetToken public token; - - uint256 public startTime; - uint256 public endTime; - - bool public isFinalized = false; - uint256 public weiRaised; - - mapping(address => bool) public whitelist; - - event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); - event TokenRelease(address indexed beneficiary, uint256 amount); - event TokenRefund(address indexed refundee, uint256 amount); - - event Finalized(); - - function AgiCrowdsale( - address _token, - address _wallet, - uint256 _startTime, - uint256 _endTime, - uint256 _rate, - uint256 _cap, - uint256 _goal - ) { - require(_startTime >= getBlockTimestamp()); - require(_endTime >= _startTime); - require(_rate > 0); - require(_goal > 0); - require(_cap > 0); - require(_wallet != 0x0); - - vault = new RefundVault(_wallet); - token = SingularityNetToken(_token); - wallet = _wallet; - startTime = _startTime; - endTime = _endTime; - rate = _rate; - goal = _goal; - cap = _cap; - } - - // fallback function can be used to buy tokens - function () payable { - buyTokens(msg.sender); - } - - //low level function to buy tokens - function buyTokens(address beneficiary) internal { - require(beneficiary != 0x0); - require(whitelist[beneficiary]); - require(validPurchase()); - - //derive amount in wei to buy - uint256 weiAmount = msg.value; - //check if there is enough funds - uint256 remainingToFund = cap.sub(weiRaised); - if (weiAmount > remainingToFund) { - weiAmount = remainingToFund; - } - uint256 weiToReturn = msg.value.sub(weiAmount); - //derive how many tokens - uint256 tokens = getTokens(weiAmount); - //update the state of weiRaised - weiRaised = weiRaised.add(weiAmount); - - //Forward funs to the vault - forwardFunds(); - //refund if the contribution exceed the cap - if (weiToReturn > 0) { - beneficiary.transfer(weiToReturn); - TokenRefund(beneficiary, weiToReturn); - } - - - //Trigger the event of TokenPurchase - TokenPurchase( - msg.sender, - beneficiary, - weiAmount, - tokens - ); - token.transferTokens(beneficiary,tokens); - - } - - function getTokens(uint256 amount) internal constant returns (uint256) { - return amount.mul(rate).div(WEI_TO_COGS); - } - - // contributors can claim refund if the goal is not reached - function claimRefund() nonReentrant external { - require(isFinalized); - require(!goalReached()); - vault.refund(msg.sender); - } - - //in case of endTime before the reach of the cap, the owner can claim the unsold tokens - function claimUnsold() onlyOwner { - require(endTime <= getBlockTimestamp()); - uint256 unsold = token.balanceOf(this); - - if (unsold > 0) { - require(token.transferTokens(msg.sender, unsold)); - } - } - - // add to whitelist array of addresses - function updateWhitelist(address[] addresses, bool status) public onlyOwner { - for (uint256 i = 0; i < addresses.length; i++) { - address contributorAddress = addresses[i]; - whitelist[contributorAddress] = status; - } - } - - function finalize() onlyOwner { - require(!isFinalized); - require(hasEnded()); - - if (goalReached()) { - //Close the vault - vault.close(); - //Unpause the token - token.unpause(); - } else { - //else enable refunds - vault.enableRefunds(); - } - //update the sate of isFinalized - isFinalized = true; - //trigger and emit the event of finalization - Finalized(); - } - - // send ether to the fund collection wallet, the vault in this case - function forwardFunds() internal { - vault.deposit.value(msg.value)(msg.sender); - } - - // @return true if crowdsale event has ended or cap reached - function hasEnded() public constant returns (bool) { - bool capReached = weiRaised >= cap; - bool passedEndTime = getBlockTimestamp() > endTime; - return passedEndTime || capReached; - } - - function goalReached() public constant returns (bool) { - return weiRaised >= goal; - } - - function isWhitelisted(address contributor) public constant returns (bool) { - return whitelist[contributor]; - } - - // @return true if the transaction can buy tokens - function validPurchase() internal constant returns (bool) { - bool withinPeriod = getBlockTimestamp() >= startTime && getBlockTimestamp() <= endTime; - bool nonZeroPurchase = msg.value != 0; - bool withinCap = weiRaised.add(msg.value) <= cap; - return withinPeriod && withinCap && nonZeroPurchase; - } - - function getBlockTimestamp() internal constant returns (uint256) { - return block.timestamp; - } -} \ No newline at end of file diff --git a/dao/contracts/market/Escrow.sol b/dao/contracts/market/Escrow.sol deleted file mode 100644 index 308de65..0000000 --- a/dao/contracts/market/Escrow.sol +++ /dev/null @@ -1,27 +0,0 @@ -pragma solidity ^0.4.11; - -import "zeppelin-solidity/contracts/ownership/Ownable.sol"; - -contract Escrow is Ownable { - - - address public beneficiary; - - event Deposited(address indexed from, uint amount); - - function Escrow(address _beneficiary) { - beneficiary = _beneficiary; - } - - function () payable { - if (msg.value <= 0) { - return; - } - - Deposited(msg.sender, msg.value); - } - - function releaseFunds() onlyOwner { - beneficiary.transfer(this.balance); - } -} diff --git a/dao/contracts/market/MarketJob.sol b/dao/contracts/market/MarketJob.sol deleted file mode 100644 index 8945ea6..0000000 --- a/dao/contracts/market/MarketJob.sol +++ /dev/null @@ -1,103 +0,0 @@ -pragma solidity ^0.4.18; - -import "zeppelin-solidity/contracts/math/SafeMath.sol"; -import "../tokens/SingularityNetToken.sol"; -import "./MarketJobInterface.sol"; - - -contract MarketJob is MarketJobInterface { - using SafeMath for uint256; - - SingularityNetToken public token; - address public masterAgent; - bytes public jobDescriptor; - bool public jobCompleted; - bool public jobAccepted; - bytes public jobResult; - address public payer; - - event Deposited(address payer, uint256 amount); - event Withdrew(address payee, uint256 amount); - event JobCompleted(); - event JobAccepted(); - - - struct Job { - uint256 amount; - uint256 idService; - } - - mapping (address => Job) public amounts; - - modifier jobDone { - require(jobCompleted == true); - _; - } - - modifier jobApproved { - require(jobAccepted == true); - _; - } - - modifier jobPending { - require(jobCompleted == false); - _; - } - - modifier onlyPayer { - require(msg.sender == payer); - _; - } - - modifier onlyMasterAgent { - require(msg.sender == masterAgent); - _; - } - - function MarketJob( - address[] _agents, - uint256[] _amounts, - uint256[] _services, - address _token, - address _payer, - bytes _jobDescriptor - ) { - require(_agents.length == _amounts.length); - require(_amounts.length == _services.length); - masterAgent = msg.sender; - payer = _payer; - jobDescriptor = _jobDescriptor; - jobCompleted = false; - token = SingularityNetToken(_token); - - for (uint256 i = 0; i < _amounts.length; i++) { - amounts[_agents[i]] = Job(_amounts[i],_services[i]); - } - } - - function deposit(uint256 amount) onlyPayer jobPending public { - require(token.transferFrom(msg.sender, address(this), amount)); - Deposited(msg.sender,amount); - } - - function setJobCompleted(bytes _jobResult) onlyMasterAgent jobPending public { - jobCompleted = true; - jobResult = _jobResult; - JobCompleted(); - } - - function setJobAccepted() onlyPayer jobDone public { - jobAccepted = true; - JobAccepted(); - } - - function withdraw() jobDone jobApproved public { - address agent = msg.sender; - uint256 amount = amounts[agent].amount; - require(amount > 0); - - amounts[agent].amount = 0; - require(token.transfer(agent,amount)); - Withdrew(agent,amount); - } -} diff --git a/dao/contracts/market/MarketJobFactory.sol b/dao/contracts/market/MarketJobFactory.sol deleted file mode 100644 index 43f9ee0..0000000 --- a/dao/contracts/market/MarketJobFactory.sol +++ /dev/null @@ -1,31 +0,0 @@ -pragma solidity ^0.4.18; - -import "./MarketJob.sol"; - -contract MarketJobFactory { - - event Created(address creator, address contractAddress); - - function create( - address[] agents, - uint256[] amounts, - uint256[] services, - address token, - address payer, - bytes firstPacket ) public returns (MarketJob) - { - MarketJob marketJob = new MarketJob( - agents, - amounts, - services, - token, - payer, - firstPacket - ); - - Created(msg.sender, marketJob); - - return marketJob; - } - -} diff --git a/dao/contracts/market/MarketJobInterface.sol b/dao/contracts/market/MarketJobInterface.sol deleted file mode 100644 index 5a0dd05..0000000 --- a/dao/contracts/market/MarketJobInterface.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma solidity ^0.4.18; - - -contract MarketJobInterface { - - event Deposited(address payer, uint256 amount); - event Withdrew(address payee, uint256 amount); - event JobCompleted(); - event JobAccepted(); - - - function withdraw() public; - function setJobCompleted(bytes lastPacket) public; - function setJobAccepted() public; - function deposit(uint256 amount) public; - -} diff --git a/dao/contracts/registries/AgentRegistry.sol b/dao/contracts/registries/AgentRegistry.sol deleted file mode 100644 index 8af7650..0000000 --- a/dao/contracts/registries/AgentRegistry.sol +++ /dev/null @@ -1,42 +0,0 @@ -pragma solidity ^0.4.18; - -import "./AgentRegistryInterface.sol"; - - -contract AgentRegistry is AgentRegistryInterface { - - struct Service { - uint unit; - uint pricePerUnit; - } - - address[] public agents; - - mapping (uint => Service[]) services; - - mapping (uint => uint[]) agentsForService; - - function getAgentsWithService(uint service) external constant returns (uint[]) { - return agentsForService[service]; - } - - function getAgent(uint id) external constant returns (address) { - return agents[id]; - } - - function addAgent( - uint service, - uint unit, - uint price, - address agent ) external - { - services[service].push(Service(unit, price)); - - uint id = agents.length; - - agents.push(agent); - agentsForService[service].push(id); - - AgentAdded(id, agent); - } -} diff --git a/dao/contracts/registries/AgentRegistryInterface.sol b/dao/contracts/registries/AgentRegistryInterface.sol deleted file mode 100644 index 6947ad4..0000000 --- a/dao/contracts/registries/AgentRegistryInterface.sol +++ /dev/null @@ -1,16 +0,0 @@ -pragma solidity ^0.4.18; - - -contract AgentRegistryInterface { - - event AgentAdded(uint id, address agent); - - function getAgentsWithService(uint service) external constant returns (uint[]); - function getAgent(uint id) external constant returns (address); - function addAgent( - uint service, - uint unit, - uint price, - address agent) external; - -} diff --git a/dao/contracts/tokens/SingularityNetToken.sol b/dao/contracts/tokens/SingularityNetToken.sol deleted file mode 100644 index 30dc916..0000000 --- a/dao/contracts/tokens/SingularityNetToken.sol +++ /dev/null @@ -1,60 +0,0 @@ -pragma solidity ^0.4.18; - -import "zeppelin-solidity/contracts/token/PausableToken.sol"; -import "zeppelin-solidity/contracts/token/BurnableToken.sol"; - - -/** - * @title SingularityNET Token - * @dev ERC20 SingularityNET Token (AGI) - * - * AGI Tokens are divisible by 1e8 (100,000,000) base - * referred to as 'cogs'. - * - * AGI are displayed using 8 decimal places of precision. - * - * 1 AGI is equivalent to: - * 100 000 000 == 1 * 10**8 == 1e8 == One Hundred Million cogs - * - * 1 Billion AGI (total supply) is equivalent to: - * 100000000000000000 == 1 000 000 000 * 10**8 == 1e17 == One Hundred Quadrillion cogs - * - * - */ -contract SingularityNetToken is PausableToken, BurnableToken { - - string public constant NAME = "SingularityNET Token"; - string public constant SYMBOL = "AGI"; - uint8 public constant DECIMALS = 8; - uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(DECIMALS); - - uint256 public constant PRIVATE_SUPPLY = 200000000 * 10**uint256(DECIMALS); - uint256 public constant ADVISORS_SUPPLY = 100000000 * 10**uint256(DECIMALS); - uint256 public constant PUBLIC_SUPPLY = 700000000 * 10**uint256(DECIMALS); - - /** - * @dev SingularityNetToken Constructor - */ - - function SingularityNetToken() { - totalSupply = INITIAL_SUPPLY; - balances[msg.sender] = INITIAL_SUPPLY; - } - - function setOwnership(address _owner) onlyOwner { - pause(); - balances[owner] = INITIAL_SUPPLY.sub(PUBLIC_SUPPLY); - owner = _owner; - balances[owner] = PUBLIC_SUPPLY; - } - - function transferTokens(address beneficiary, uint256 amount) onlyOwner returns (bool) { - require(amount > 0); - - balances[owner] = balances[owner].sub(amount); - balances[beneficiary] = balances[beneficiary].add(amount); - Transfer(owner, beneficiary, amount); - - return true; - } -} diff --git a/dao/dao.sh b/dao/dao.sh deleted file mode 100755 index 6b09d50..0000000 --- a/dao/dao.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env sh - -set -o errexit -set -o verbose -set -o xtrace -set -o nounset - - -case "$1" in - -noop) - ;; - -bash) - /bin/bash - ;; - -run) - cd /dao - truffle compile - truffle migrate --reset - truffle test - ;; - -*) echo 'No operation specified' - exit 0; - ;; - -esac diff --git a/dao/docs/SNContractsDesignSpecs.md b/dao/docs/SNContractsDesignSpecs.md deleted file mode 100644 index a04308f..0000000 --- a/dao/docs/SNContractsDesignSpecs.md +++ /dev/null @@ -1,58 +0,0 @@ -# SingularityNET -Smart contract design - -### Contracts - -* AGI Token -* RoboToken (also T-Coin or Spikes) -* MarketJob -* Agent -* AgentFactory -* AgentRegistry - - -### Actors -* Customer -* Job -* Agent(s) (multiple services for each) -* Token - - -![Flow](./SN_ContractsFlow.png) - -### Customer Flow -1) Customer request a job -2) An off-chain estimation happens on the customer's request -3) Finds service providers trought AgentRegistry -4) Contact an Agent and append a Job (he becomes the agent master) -5) The master agent create a MarketJob contract with payer and payee -6) Once th job is done the tokens are swapped from customer's account to agent master - - -### Agent Flow -1) Start Agent -2) Register the service(s) into the Registry -4) a new event triggered new Packet Appended based on the Registry mapping -5) The Agent(s) complete the job and signals marketJob -6) The tokens are automaticcaly swapped -7) Create a pull mecahnism for sub-agent to withdrawal funds from master agent - - - - -### Agent (pseudo)API - -To make your app work on Ethereum, you can use the web3 object provided by the web3 (python library). Under the hood it communicates to a local node through RPC calls. web3 works with any Ethereum node, which exposes an RPC layer. - -### Methods - -* joinNetwork() : address -* advertiseService(uint id, address) : void -* findServiceProviders(uint service) : uint[] -* getAgentbyId(uint id) : address - -### Events - -[web3.py Events doc](https://web3py.readthedocs.io/en/latest/contracts.html#events) -* AgentAdded(uint id, address agent) -* Deposited(address from, uint value) \ No newline at end of file diff --git a/dao/docs/SN_ContractsFlow.png b/dao/docs/SN_ContractsFlow.png deleted file mode 100644 index c9b8f56..0000000 Binary files a/dao/docs/SN_ContractsFlow.png and /dev/null differ diff --git a/dao/js/agent.js b/dao/js/agent.js deleted file mode 100644 index 3e76dfb..0000000 --- a/dao/js/agent.js +++ /dev/null @@ -1,26 +0,0 @@ -// Import libraries we need. -const Web3 = require('web3') -const contract = require('truffle-contract') -// Import our contract artifacts and turn them into usable abstractions. -const Agent = require('../build/contracts/AgentFactory.json') -const agent = contract(Agent) - -const account = "0x627306090abab3a6e1400e9345bc60c78a8bef57" - -function create() { - agent.setProvider(new Web3.providers.HttpProvider("http://localhost:9545")) - - agent.deployed().then(function (instance) { - return instance.create({ - from: account, - gas: 180000 - }) - }).then((tx) => { - console.log(tx) - }).then(console.log) - .catch(function (e) { - console.log(e) - }) -} - -create() \ No newline at end of file diff --git a/dao/js/index.html b/dao/js/index.html deleted file mode 100644 index b0c678c..0000000 --- a/dao/js/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - -

contract

-
-
-
- -
- -
- - - \ No newline at end of file diff --git a/dao/js/index.js b/dao/js/index.js deleted file mode 100644 index 4976255..0000000 --- a/dao/js/index.js +++ /dev/null @@ -1,114 +0,0 @@ - -//web3js -const Web3 = require('web3') -const web3 = new Web3(Web3.givenProvider) -const OWNER = web3.eth.accounts[0] - console.log(OWNER) -//const OWNER = '0xb9d2bdfe453640730919fbd8acc5083e991177ff' -//contracts ABI -const agentFactory = require('../build/contracts/AgentFactory.json') -const agentRegistry = require('../build/contracts/AgentRegistry.json') -const agent = require('../build/contracts/Agent.json') -const escrow = require('../build/contracts/Escrow.json') -//constants -const AGENT_FACTORY_ADDRESS = '0xd364ede69b6c1469fb19c145b3ad6f753f7f793a' -const AGENT_REGISTRY_CONTRACT = '0x7988941a7d6037ef89b031af8606b88a1aa09e91' -const AGENT_ADDRESS = '0x2bb2fdf0eb609046bbba217bca0765759a95600d' -const ESCROW_ADDRESS = '0x278c4b8a81eebc94f2b2ebcac2ae33d4b889f5eb' -//Using deployed contrat -const agentFactoryContract = new web3.eth.Contract(agentFactory.abi,AGENT_FACTORY_ADDRESS) -const agentContract = new web3.eth.Contract(agent.abi,AGENT_ADDRESS) -const escrowContarct = new web3.eth.Contract(escrow.abi,ESCROW_ADDRESS) -const agentRegistryContract = new web3.eth.Contract(agentRegistry.abi, AGENT_REGISTRY_CONTRACT) -//payload dev -const GAS = 1500000, GAS_PRICE = 30000000000000, - PAYLOAD = { from:OWNER, gas: GAS, gasPrice: GAS_PRICE} - -//Creates a new agent on the blockchain -async function joinNetwork() { - return await new Promise((resolve,reject) =>{ - agentFactoryContract.methods.create().send({from:OWNER}) - .then((result) => { - resolve(result) - }) - }) -} - -//appendPacket -async function appendPacket(packet) { - return await new Promise((resolve,reject) => { - agentContract.methods.appendPacket(packet).send(PAYLOAD) - .then(result => { - resolve(result) - }) - .catch( reason => { - reject(reason) - }) - }) -} - -//getPacket -async function getPacket(position) { - return await new Promise((resolve,reject) => { - agentContract.methods.getPacket(position).call({from:OWNER}) - .then(result => { - resolve(result) - }) - .catch( reason => { - reject(reason) - }) - }) -} - -//registers an agent's service offerings on the blockchain -async function advertiseService(service,agent) { - return await new Promise((resolve,reject) => { - agentRegistryContract.methods.addAgent(service,agent).send(PAYLOAD) - .then(event => { - resolve(event) - }) - }) -} - -async function findServiceProviders(service) { - return await new Promise((resolve,reject) => { - agentRegistryContract.methods.getAgentsWithService(service).call(PAYLOAD) - .then(agents => { - resolve(agents) - }) - .catch(reason => { - reject(reason) - }) - }) -} - -async function getAgentById(id) { - return await new Promise((resolve,reject) => { - agentRegistryContract.methods.getAgent(id).call(PAYLOAD) - .then(resolve) - .catch(reject) - }) -} - -async function main() { - const wordSenseDisambiguation = 0, textSummarization = 1 - - const address = await joinNetwork() - const address2 = await joinNetwork() - console.log(address,address2) - //console.log(address) - //await advertiseService(textSummarization,address) - - //await appendPacket("0x0") - //const r = await getPacket(0) - - //const providers = await findServiceProviders(textSummarization) - //let target - //if (providers.length>0) target = await getAgentById(parseInt(providers[0])) - //console.log(providers,target) - - -} - - -//main() diff --git a/dao/js/market.js b/dao/js/market.js deleted file mode 100644 index 8bee6a5..0000000 --- a/dao/js/market.js +++ /dev/null @@ -1,70 +0,0 @@ -// Import libraries we need. -const Web3 = require('web3') -const contract = require('truffle-contract') -// Import our contract artifacts and turn them into usable abstractions. -const MarketJob = require('../build/contracts/MarketJob.json') -const marketJob = contract(MarketJob) - - -const account = "0x951BE8FAE44CD16a1152DA1CcC8c414f7aEC7bd6", - PAYER = process.env.PAYER || account, - AGENTS = process.env.AGENTS || [account], - AMOUNTS = process.env.AMOUNTS || [new marketJob.web3.BigNumber(300)], - SERVICES = process.env.SERVICES || [new marketJob.web3.BigNumber(101)], - JOB_DESCRIPTOR = process.env.JOB_DESC || "0x0" - -async function create() { - marketJob.setProvider(new Web3.providers.HttpProvider("http://localhost:8545")) - - let tx - try { - tx = await marketJob.new( - AGENTS, // agents - AMOUNTS, //amounts - SERVICES, // services id - "0xbf625fd0ae8c827d9a9ecba19fe959723ce052ec", //token address - PAYER, // payer address - JOB_DESCRIPTOR, // first bytes packet - { - from: account, - gas: 1500000 - } - ) - const payer = await tx.payer.call() - console.log('New MarketJob started ') - console.log('tx hash :' + tx.transactionHash) - console.log('\n') - - console.log('=====================') - console.log('PAYER :' + payer) - console.log('AGENT :' + account) - console.log('Amount,serviceId : ' + await tx.amounts.call(account)) - console.log('\n') - - console.log('=====================') - console.log('Job Descriptor') - console.log(await tx.jobDescriptor.call()) - - } catch (reason) { - console.error(reason) - } - - return tx -} - -const allowAndDeposit = async (contract) => { - - - //APPROVE - //await token.approve(escrow, amount, { from: acont }) - //const allowance = await token.allowance.call(account, escrow) - -} - - -const main = async () => { - const escrow = await create() - await allowAndDeposit(escrow) -} - -main() diff --git a/dao/js/package.json b/dao/js/package.json deleted file mode 100644 index 7271555..0000000 --- a/dao/js/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "app", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "truffle-contract": "^3.0.1", - "web3": "^0.2.8" - } -} diff --git a/dao/js/registry.js b/dao/js/registry.js deleted file mode 100644 index 55d04f7..0000000 --- a/dao/js/registry.js +++ /dev/null @@ -1,33 +0,0 @@ -// Import libraries we need. -const Web3 = require('web3') -const contract = require('truffle-contract') -// Import our contract artifacts and turn them into usable abstractions. -const Agent = require('../build/contracts/AgentRegistry.json') -const agent = contract(Agent) - -const account = "0x627306090abab3a6e1400e9345bc60c78a8bef57", - SERVICE = process.env.SERVICE || 0, - UNIT = process.env.UNIT || 0, - PRICE = process.env.PRICE || 100, - AGENT = process.env.AGENT || account - -function create() { - agent.setProvider(new Web3.providers.HttpProvider("http://localhost:9545")) - - agent.deployed().then(function (instance) { - return instance.addAgent( - SERVICE, - UNIT, - PRICE, - AGENT, - { from: account, gas: 180000 } - ) - }).then((tx) => { - console.log(tx) - }).then(console.log) - .catch(function (e) { - console.log(e) - }) -} - -create() \ No newline at end of file diff --git a/dao/migrations/1_initial_migration.js b/dao/migrations/1_initial_migration.js deleted file mode 100644 index ed3ed7b..0000000 --- a/dao/migrations/1_initial_migration.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = function(deployer) { }; diff --git a/dao/migrations/2_deploy_contracts.js b/dao/migrations/2_deploy_contracts.js deleted file mode 100644 index 89b6917..0000000 --- a/dao/migrations/2_deploy_contracts.js +++ /dev/null @@ -1,37 +0,0 @@ -const fs = require('fs') - -const Escrow = artifacts.require('Escrow.sol') -const Agent = artifacts.require('agent/Agent.sol') -const MarketJob = artifacts.require('market/MarketJob.sol') -const MarketJobFactory = artifacts.require('market/MarketJobFactory.sol') -const AgentFactory = artifacts.require('agent/AgentFactory.sol') -const AgentRegistry = artifacts.require('registries/AgentRegistry.sol') -const SingularityNetToken = artifacts.require('tokens/SingularityNetToken.sol') - -module.exports = function(deployer, network, accounts) { - deployer.deploy([ - Agent, - Escrow, - MarketJob, - AgentFactory, - AgentRegistry, - MarketJobFactory, - SingularityNetToken - ]).then(() => { - const fileName = "addresses.json" - const content = { - Agent: Agent.address, - Escrow: Escrow.address, - MarketJob: MarketJob.address, - AgentFactory: AgentFactory.address, - AgentRegistry: AgentRegistry.address, - MarketJobFactory: MarketJobFactory.address, - SingularityNetToken: SingularityNetToken.address - } - - fs.writeFile(fileName, JSON.stringify(content), 'utf-8', (err) => { - if (err) { throw err } - console.log("Contracts addresses saved in ./" + fileName) - }) - }) -}; diff --git a/dao/migrations/3_deploy_crowdsale_contract.js b/dao/migrations/3_deploy_crowdsale_contract.js deleted file mode 100644 index 8deea37..0000000 --- a/dao/migrations/3_deploy_crowdsale_contract.js +++ /dev/null @@ -1,50 +0,0 @@ -const fs = require('fs') -const AgiCrowdsale = artifacts.require("foundation/AgiCrowdsale.sol") -const SingularityNetToken = artifacts.require("token/SingularityNetToken.sol") - -function latestTime() { - return web3.eth.getBlock('latest').timestamp; -} - -const duration = { - seconds: function (val) { return val }, - minutes: function (val) { return val * this.seconds(60) }, - hours: function (val) { return val * this.minutes(60) }, - days: function (val) { return val * this.hours(24) }, - weeks: function (val) { return val * this.days(7) }, - years: function (val) { return val * this.days(365) } -} - -module.exports = function(deployer, network, accounts) { - const startTime = latestTime() + duration.minutes(5); - const endTime = startTime + duration.days(20); - const rate = new web3.BigNumber(1000); - const wallet = web3.eth.accounts[0]; - const goal = new web3.BigNumber(3000 * Math.pow(10, 18)); - const cap = new web3.BigNumber(15000 * Math.pow(10, 18)); - - deployer.deploy( - AgiCrowdsale, - SingularityNetToken.address, - wallet, - startTime, - endTime, - rate, - cap, - goal - ).then(() => { - const fileName = "addresses.json" - - fs.readFile(fileName, (err, data) => { - if (!err) { - let content = JSON.parse(data.toString()) - content["AgiCrowdsale"] = AgiCrowdsale.address - - fs.writeFile(fileName, JSON.stringify(content), 'utf-8', (err) => { - if (err) { throw err } - console.log("Added AgiCrowdsale to " + fileName) - }) - } - }) - }) -}; diff --git a/dao/package.json b/dao/package.json deleted file mode 100644 index 0a323ca..0000000 --- a/dao/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "singnet-contracts", - "version": "1.0.0", - "description": "Includes contracts, migrations, tests", - "directories": { - "doc": "docs", - "test": "test" - }, - "scripts": { - "test": "truffle test" - }, - "author": "tiero", - "license": "MIT", - "dependencies": { - "ganache-cli": "^6.0.3", - "truffle-hdwallet-provider": "0.0.3", - "zeppelin-solidity": "^1.4.0", - "solium": "1.0.9", - "scrypt": "6.0.1" - }, - "repository": { - "type": "git", - "url": "git://github.com/singnet/singnet/repository.git" - } -} diff --git a/dao/py/main.py b/dao/py/main.py deleted file mode 100755 index 5f3d072..0000000 --- a/dao/py/main.py +++ /dev/null @@ -1,103 +0,0 @@ -import json -from web3 import Web3, HTTPProvider, IPCProvider - -web3 = Web3(HTTPProvider('http://localhost:8545')) - -def getAddressByName(addresses,name): - for key, value in addresses.items(): - if key==name: - return value - -def parseAbi(data): - for key, value in data.items(): - if key=='abi': - return value -#payloads -payload = {'from': web3.eth.coinbase, 'gas': 1500000, 'gasPrice':30000000000000} - -#ABI(s) -agentRegistryAbi = parseAbi(json.loads(open('../build/contracts/AgentRegistry.json','r').read())) -agentFactoryAbi = parseAbi(json.loads(open('../build/contracts/AgentFactory.json','r').read())) -marketJobAbi = parseAbi(json.loads(open('../build/contracts/MarketJob.json','r').read())) -agentAbi = parseAbi(json.loads(open('../build/contracts/Agent.json','r').read())) -crowdsaleAbi = parseAbi(json.loads(open('../build/contracts/AgiCrowdsale.json','r').read())) -#addresses -agentRegistryAddress = getAddressByName(json.loads(open('../addresses.json','r').read()),'AgentRegistry') -agentFactoryAddress = getAddressByName(json.loads(open('../addresses.json','r').read()),'AgentFactory') -marketJobAddress = getAddressByName(json.loads(open('../addresses.json','r').read()),'MarketJob') -agentAddress = getAddressByName(json.loads(open('../addresses.json','r').read()),'Agent') -crowdsaleAddress = getAddressByName(json.loads(open('../addresses.json','r').read()),'AgiCrowdsale') - -#Contracts -agentRegistryContract = web3.eth.contract(abi = agentRegistryAbi, address=agentRegistryAddress) -agentFactoryContract = web3.eth.contract(abi = agentFactoryAbi, address=agentFactoryAddress) -marketJobContract = web3.eth.contract(abi = marketJobAbi, address=marketJobAddress, bytecode="0x6060604052604051610760380380610760833981016040528080518201919060200180518201919060200180519190602001805182019190602001805190910190505b60005b60008054600160a060020a03191633600160a060020a03161790555b845186511461006f57600080fd5b60018054600160a060020a031916600160a060020a038616179055600282805161009d92916020019061011f565b5060038380516100b192916020019061011f565b50600090505b8451811015610113578481815181106100cc57fe5b90602001906020020151600560008884815181106100e657fe5b90602001906020020151600160a060020a031681526020810191909152604001600020555b6001016100b7565b5b5050505050506101bf565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061016057805160ff191683800117855561018d565b8280016001018555821561018d579182015b8281111561018d578251825591602001919060010190610172565b5b5061019a92915061019e565b5090565b6101bc91905b8082111561019a57600081556001016101a4565b5090565b90565b610592806101ce6000396000f300606060405236156100a15763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663123119cd81146100a65780632f54bf6e146100d55780633ccfd60b1461010857806355a3b2c11461011d578063626568dc1461014e5780638da5cb5b146101d9578063a552386b14610208578063b2a7a8371461022f578063e33b39cf146102ba578063f2fde38b146102cf575b600080fd5b34156100b157600080fd5b6100b96102f0565b604051600160a060020a03909116815260200160405180910390f35b34156100e057600080fd5b6100f4600160a060020a03600435166102ff565b604051901515815260200160405180910390f35b341561011357600080fd5b61011b610316565b005b341561012857600080fd5b61013c600160a060020a036004351661039e565b60405190815260200160405180910390f35b341561015957600080fd5b6101616103b0565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561019e5780820151818401525b602001610185565b50505050905090810190601f1680156101cb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156101e457600080fd5b6100b961044e565b604051600160a060020a03909116815260200160405180910390f35b341561021357600080fd5b6100f461045d565b604051901515815260200160405180910390f35b341561023a57600080fd5b610161610466565b60405160208082528190810183818151815260200191508051906020019080838360005b8381101561019e5780820151818401525b602001610185565b50505050905090810190601f1680156101cb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156102c557600080fd5b61011b610504565b005b34156102da57600080fd5b61011b600160a060020a0360043516610525565b005b600154600160a060020a031681565b600054600160a060020a038281169116145b919050565b60045460009060ff16151560011461032d57600080fd5b600160a060020a0333166000908152600560205260408120541161035057600080fd5b50600160a060020a033316600081815260056020526040808220805492905590919082156108fc0290839051600060405180830381858888f19350505050151561039957600080fd5b5b5b50565b60056020526000908152604090205481565b60038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104465780601f1061041b57610100808354040283529160200191610446565b820191906000526020600020905b81548152906001019060200180831161042957829003601f168201915b505050505081565b600054600160a060020a031681565b60045460ff1681565b60028054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104465780601f1061041b57610100808354040283529160200191610446565b820191906000526020600020905b81548152906001019060200180831161042957829003601f168201915b505050505081565b60045460ff161561051457600080fd5b6004805460ff191660011790555b5b565b61052e336102ff565b151561053957600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b5b505600a165627a7a723058204b360ed4e2a55422759240b12589fce4b67afa92f3d4db7484283b50c211d5210029") -agentContract = web3.eth.contract(abi = agentAbi, address=agentAddress) -crowdsaleContract = web3.eth.contract(abi = crowdsaleAbi, address=crowdsaleAddress, args) - - -def joinNetwork(): - return agentFactoryContract.transact(payload).create() - -def advertiseService(service,agent): - return agentRegistryContract.transact(payload).addAgent(service,agent) - -def findServiceProviders(service): - return agentRegistryContract.call(payload).getAgentsWithService(service) - -def getAgentsById(id): - return agentRegistryContract.call(payload).getAgent(id) - -def createMarketJob(agents,amounts,payer,firstService,lastService): - return marketJobContract.deploy(transaction={'from': web3.eth.accounts[8],'value': web3.toWei(1, 'ether')},args=(agents,amounts,payer,firstService,lastService)) - -def setJobCompleted(): - return marketJobContract.call(payload).setJobCompleted() - -def payAgent(agentAccounts): - return marketJobContract.call({'from': agentAccounts[0]}).withdraw() - - -# assign an integer for each service -# wordSenseDisambiguation = 0, -# textSummarization = 1 - - - -# # Here I'm joining the network and putting in myself the address on the blockchain -# myself1 = joinNetwork() -# print("myself_1 {0}".format(myself1)) -# myself2 = joinNetwork() -# print("myself_2 {0}".format(myself2)) - -# #TODO: add event watch AgentAdded -# #Add an agent (address) and its service (id, unit, pricePerUnit) to the registry -# advertiseService(0, 0, 20, web3.eth.accounts[1]) - -# #Create a new market with two agents -# agentAccounts = [web3.eth.accounts[4],web3.eth.accounts[5]] -# rewardsForServices = [web3.toWei(0.5, 'ether'),web3.toWei(0.5, 'ether')] -# payer = web3.eth.accounts[2] - -# marketJob = createMarketJob(agentAccounts,rewardsForServices,payer,"0","1") -# print("market_job {0}".format(marketJob)) -# #Complete all jobs -# setJobCompleted() -# #Let agent be payed for his service(s) -# payAgent(agentAccounts) - -#Here I'm inserting a new agent for a determined service -'''print("\n\nadvertize service\n") -print(advertiseService(0,myself)) -print(advertiseService(0,test_agent)) -print(advertiseService(72182,test_agent)) - -## Here I'm printing -print("\n\nfind service providers for 0\n") -print(getAgentsById(findServiceProviders(0)[0])) -print(getAgentsById(findServiceProviders(0)[1])) -print("\n\nfind service providers for 72182\n") -print(findServiceProviders(72182)[0]) -test_provider_address = findServiceProviders(72182)[0] -test_provider = getAgentsById(test_provider_address)''' - diff --git a/dao/py/personal.py b/dao/py/personal.py deleted file mode 100644 index 3709ecd..0000000 --- a/dao/py/personal.py +++ /dev/null @@ -1,24 +0,0 @@ -import json -from web3 import Web3, HTTPProvider, IPCProvider - -web3 = Web3(HTTPProvider('http://localhost:8545')) - -#password for encrypting account -psw = '1234' -# seconds -duration = 5 - - -print("list of accounts {0}".format(web3.personal.listAccounts)) - -newAccount = web3.personal.newAccount(psw) -print("Account created {0}".format(newAccount)) -print("Unlocked: {0}".format(web3.personal.unlockAccount(newAccount, psw))) - -# Unlocking with a duration -print("Unlocked with a duration: {0}".format(web3.personal.unlockAccount(newAccount, psw, duration))) - - - - - diff --git a/dao/test.sh b/dao/test.sh deleted file mode 100644 index 6860d28..0000000 --- a/dao/test.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -trap cleanup EXIT - -cleanup() { - if [ -n "$testrpc_pid" ] && ps -p $testrpc_pid > /dev/null; then - kill -9 $testrpc_pid - fi -} - -testrpc_running() { - nc -z localhost 8545 -} - -if testrpc_running; then - echo "Using existing testrpc" -else - echo "testrpc is running " - node_modules/.bin/testrpc > /dev/null & - testrpc_pid=$! -fi - -node_modules/.bin/truffle compile --all "$@" -node_modules/.bin/truffle migrate --reset "$@" -node_modules/.bin/truffle test "$@" -cd py && python main.py diff --git a/dao/test/TestAgent.js b/dao/test/TestAgent.js deleted file mode 100644 index 42b6ad2..0000000 --- a/dao/test/TestAgent.js +++ /dev/null @@ -1,48 +0,0 @@ -const Agent = artifacts.require('agent/Agent.sol') - - -contract('Agent', function () { - - let agent - - beforeEach(async () => { - agent = await Agent.new() - }) - - it('verifies that somehow can append bytes of data to the agent', async () => { - - let result = await agent.appendPacket("0x0") - assert.isNotNull(result) - - }) - - it('verifies that somehow can get bytes of data from the agent', async () => { - - let result = await agent.appendPacket("0x0") - let packet = await agent.getPacket(0) - console.log(packet) - assert.isNotNull(packet) - - }) - - it('verifies that somehow can send bytes of data to an agent', async () => { - - const agent2 = await Agent.new() - - await agent.appendPacket("0x0101") - - let packet = await agent.getPacket(0) - - await agent2.sendPacket(agent2.address, packet) - - let packet2 = await agent2.getPacket(0) - - console.log(packet2) - - assert.isNotNull(packet2) - - }) - - - -}) diff --git a/dao/test/TestAgentFactory.js b/dao/test/TestAgentFactory.js deleted file mode 100644 index 7ab1e2c..0000000 --- a/dao/test/TestAgentFactory.js +++ /dev/null @@ -1,25 +0,0 @@ -const Agent = artifacts.require('agent/Agentfactory.sol') - - -contract('AgentFactory', function () { - - let agentFactory - - beforeEach(async () => { - agentFactory = await Agent.new() - }) - - it('verifies that someone can create a new agent', async () => { - - let result = await agentFactory.create() - assert.isNotNull(result) - - }) - - it('verifies that somehow can create multiple agents', async () => { - let result = await agentFactory.create() - let result2 = await agentFactory.create() - assert.notEqual(result, result2, 'Errors, no multiple agents created') - }) - -}) \ No newline at end of file diff --git a/dao/test/TestAgentRegistry.js b/dao/test/TestAgentRegistry.js deleted file mode 100644 index 36da9a7..0000000 --- a/dao/test/TestAgentRegistry.js +++ /dev/null @@ -1,50 +0,0 @@ -const AgentRegistry = artifacts.require('registries/AgentRegistry.sol'); - - -contract('AgentRegistry', function (accounts) { - - let registry - - beforeEach(async () => { - registry = await AgentRegistry.new() - }) - - it('verifies that agent can be added to registry', async () => { - - let result = await registry.addAgent( - 0, - 1, - 20, - accounts[2] - ) - - assert.equal(result.logs[0].event, 'AgentAdded', 'Agent was not added') - }) - - it('returns agent data at 0 position', async () => { - - await registry.addAgent( - 0, - 1, - 20, - accounts[2] - ) - - let result = await registry.getAgent.call(0) - assert.isNotNull(result) - }) - - it('returns agents with service 0', async () => { - - await registry.addAgent( - 0, - 1, - 20, - accounts[2] - ) - - let result = await registry.getAgentsWithService.call(0) - assert.isNotNull(result) - }) - -}) \ No newline at end of file diff --git a/dao/test/TestAgiCrowdsale.js b/dao/test/TestAgiCrowdsale.js deleted file mode 100644 index 8c48738..0000000 --- a/dao/test/TestAgiCrowdsale.js +++ /dev/null @@ -1,157 +0,0 @@ -const Crowdsale = artifacts.require('./helpers/AgiCrowdsaleMock.sol') -const AGIToken = artifacts.require('SingularityNetToken.sol') - -const { latestTime, duration } = require('./helpers/latestTime') -const { increaseTimeTo } = require('./helpers/increaseTime') - - -contract('AgiCrowdsale', async ([miner, firstContributor, secondContributor, wallet]) => { - let agiCrowdsale - let token - - - beforeEach(async () => { - token = await AGIToken.new() - const startTime = latestTime() + duration.seconds(1) - const endTime = startTime + duration.weeks(1) - const rate = new web3.BigNumber(1000) - const goal = new web3.BigNumber(3000 * Math.pow(10, 18)) - const cap = new web3.BigNumber(15000 * Math.pow(10, 18)) - agiCrowdsale = await Crowdsale.new(token.address, wallet, startTime, endTime, rate, cap, goal) - await agiCrowdsale.setBlockTimestamp(startTime + duration.days(2)) - }) - - describe('initialization', () => { - - it('should not be finalized', async () => { - const isFinalized = await agiCrowdsale.isFinalized() - - assert.isFalse(isFinalized, "isFinalized should be false") - }) - - it('goal should be 3000 ETH', async () => { - const goal = await agiCrowdsale.goal() - assert.equal(goal.toString(10), '3000000000000000000000', "goal is incorrect") - }) - - it('cap should be 15000 ETH', async () => { - const cap = await agiCrowdsale.cap() - assert.equal(cap.toString(10), '15000000000000000000000', "cap is incorrect") - }) - - it('should set the agiCrowdsale as a new owner of AGI token', async () => { - await token.setOwnership(agiCrowdsale.address) - const owner = await token.owner.call() - assert.equal(owner, agiCrowdsale.address, 'Crowdsale is not the owner of the token') - }) - - }) - - describe('whitelist', async () => { - - it('should add two contributors into the whitelist', async () => { - await agiCrowdsale.updateWhitelist([firstContributor, secondContributor], true) - assert.isTrue(await agiCrowdsale.isWhitelisted(firstContributor)) - assert.isTrue(await agiCrowdsale.isWhitelisted(secondContributor)) - }) - - it('should add and remove the same contributor in whitelist', async () => { - await agiCrowdsale.updateWhitelist([firstContributor], true) - assert.isTrue(await agiCrowdsale.isWhitelisted(firstContributor)) - - await agiCrowdsale.updateWhitelist([firstContributor], false) - assert.isFalse(await agiCrowdsale.isWhitelisted(firstContributor)) - }) - }) - - describe('sale', async () => { - - it('should not accept purchase before start', async () => { - try { - await agiCrowdsale.sendTransaction({ value: new web3.BigNumber(web3.toWei(1, 'ether')), from: firstContributor }) - - assert.fail('should have thrown before') - } catch (error) { - assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); - } - }) - - it('should accept payments during the sale and issue tokens', async () => { - await agiCrowdsale.updateWhitelist([firstContributor], true) - - await token.setOwnership(agiCrowdsale.address) - - const rate = new web3.BigNumber(1000) - const weiToCogs = new web3.BigNumber(Math.pow(10, -10)) - const startTime = latestTime() + duration.seconds(1) - - const investmentAmount = new web3.BigNumber(web3.toWei(0.5, 'ether')) - const expectedCotributorAmount = rate.mul(investmentAmount).mul(weiToCogs) - - await increaseTimeTo(startTime) - - const value = new web3.BigNumber(web3.toWei(0.5, 'ether')) - - await agiCrowdsale.sendTransaction({ value, from: firstContributor }) - - const initialSupply = await token.INITIAL_SUPPLY.call() - const contributorAmount = await token.balanceOf(firstContributor) - - assert.equal(contributorAmount.toString(), expectedCotributorAmount.toString()) - assert.equal((initialSupply - contributorAmount).toString(), (initialSupply - expectedCotributorAmount).toString()) - - try { - await token.transfer(secondContributor, 100) - assert.fail('should have thrown before') - } catch (error) { - assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); - } - - - const isFinalized = await agiCrowdsale.isFinalized() - - assert.isFalse(isFinalized, "isFinalized should be true") - }) - - it('should refund payers if the goal is not reached', async () => { - await agiCrowdsale.updateWhitelist([firstContributor], true) - await token.setOwnership(agiCrowdsale.address) - - const value = new web3.BigNumber(web3.toWei(1, 'ether')) - - await agiCrowdsale.sendTransaction({ value, from: firstContributor }) - await agiCrowdsale.setBlockTimestamp(latestTime() + duration.weeks(2)) - await agiCrowdsale.finalize() - - const before = web3.fromWei(web3.eth.getBalance(firstContributor), 'ether') - - await agiCrowdsale.claimRefund({ from: firstContributor }) - - const after = web3.fromWei(web3.eth.getBalance(firstContributor), 'ether') - - assert.equal(Math.round(after - before), web3.fromWei(value, 'ether').toString()) - }) - - it('should enable the owner to claim all unsold tokens', async () => { - await token.setOwnership(agiCrowdsale.address) - - await agiCrowdsale.setBlockTimestamp(latestTime() + duration.weeks(2)) - await agiCrowdsale.finalize() - - const initialSupply = await token.balanceOf(agiCrowdsale.address) - const before = await token.balanceOf(miner) - - await agiCrowdsale.claimUnsold() - - const endSupply = await token.balanceOf(agiCrowdsale.address) - const after = await token.balanceOf(miner) - - assert.equal(after.toString(), parseInt(initialSupply.toString()) + parseInt(before.toString())) - assert.equal(endSupply.toString(), 0) - }) - - }) - -}) - - diff --git a/dao/test/TestMarketJob.js b/dao/test/TestMarketJob.js deleted file mode 100644 index 705b6fa..0000000 --- a/dao/test/TestMarketJob.js +++ /dev/null @@ -1,185 +0,0 @@ -const Market = artifacts.require('market/MarketJob.sol') -const AGIToken = artifacts.require('tokens/SingularityNetTokenMock.sol') - -contract('Market Job', function ([payer, firstAgent, secondAgent, thirdAgent]) { - - const amounts = [new web3.BigNumber(300), new web3.BigNumber(300), new web3.BigNumber(400)] - - - it('DEPOSIT # only the payer can deposit AGI token', async () => { - const token = await AGIToken.new(payer, 1000) - const marketJob = await Market.new( - [firstAgent, secondAgent, thirdAgent], // agents - amounts, //amounts - [101, 102, 103], // services id - token.address, //token address - payer, // payer address - "0x0", // first bytes packet - { - from: firstAgent - } - - ) - const escrow = marketJob.address - // console.log(await token.balanceOf(payer)) - const amount = new web3.BigNumber(1000) - const watch = token.Approval() - //APPROVE - await token.approve(escrow, amount, { from: payer }) - const allowance = await token.allowance.call(payer, escrow) - - - assert.equal(watch.get()[0].args.owner, payer) - assert.equal(watch.get()[0].args.spender, escrow) - - //DEPOSIT - const result = await marketJob.deposit(amount, { from: payer }) - - assert.strictEqual( - (await token.balanceOf.call(escrow)).toNumber(), - amount.toNumber() - ); - - assert.equal(result.logs[0].event, 'Deposited', 'Amount was not deposited') - }) - - it('COMPLETION # only the the master agent can set the job as completed', async () => { - const hash = '0x01' - const token = await AGIToken.new(payer, 1000) - const marketJob = await Market.new( - [firstAgent, secondAgent, thirdAgent], // agents - amounts, //amounts - [101, 102, 103], // services id - token.address, //token address - payer, // payer address - "0x0", // first bytes packet - { - from: firstAgent - } - ) - const escrow = marketJob.address - const amount = new web3.BigNumber(1000) - await token.approve(escrow, amount, { from: payer }) - await marketJob.deposit(amount, { from: payer }) - // balance after deposit === 0 - assert.equal((await token.balanceOf(escrow)).toNumber(), amount, 'Contract Not full empty') - - const result = await marketJob.setJobCompleted(hash, { from: firstAgent }) - const jobResult = await marketJob.jobResult.call() - - assert.equal(jobResult, hash, 'Inserted jobResult is different than actual inserted') - assert.equal(result.logs[0].event, 'JobCompleted', 'Job was not completed') - }) - - it('APPROVAL # only the the payer can set the job as approved ', async () => { - - const hash = '0x01' - - const token = await AGIToken.new(payer, 1000) - const marketJob = await Market.new( - [firstAgent, secondAgent, thirdAgent], // agents - amounts, //amounts - [101, 102, 103], // services id - token.address, //token address - payer, // payer address - "0x0", // first bytes packet - { - from: firstAgent - } - ) - const escrow = marketJob.address - const amount = new web3.BigNumber(1000) - await token.approve(escrow, amount, { from: payer }) - await marketJob.deposit(amount, { from: payer }) - // balance after deposit === 0 - assert.equal((await token.balanceOf(escrow)).toNumber(), amount, 'Contract Not full empty') - - await marketJob.setJobCompleted(hash, { from: firstAgent }) - const result = await marketJob.setJobAccepted() - const jobAccepted = await marketJob.jobAccepted.call() - - assert.equal(jobAccepted, true, 'the job state is euqal to approved') - assert.equal(result.logs[0].event, 'JobAccepted', 'Job was not approved') - }) - - it('WITHDRAW # only allowed agents can request a withdrawal', async () => { - - const hash = '0x01' - - const token = await AGIToken.new(payer, new web3.BigNumber(1000)) - const marketJob = await Market.new( - [firstAgent, secondAgent, thirdAgent], // agents - amounts, //amounts - [101, 102, 103], // services id - token.address, //token address - payer, // payer address - "0x0", // first bytes packet - { - from: firstAgent - } - ) - const escrow = marketJob.address - - const amount = new web3.BigNumber(1000) - - await token.approve(escrow, amount, { from: payer }) - await marketJob.deposit(amount, { from: payer }) - // balance after deposit === 0 - assert.equal((await token.balanceOf(escrow)).toNumber(), amount, 'Contract Not full empty') - await marketJob.setJobCompleted(hash, { from: firstAgent }) - await marketJob.setJobAccepted({ from: payer }) - - - /** - * third agent - */ - const resultThird = await marketJob.withdraw({ from: thirdAgent }) - - assert.strictEqual( - (await token.balanceOf.call(thirdAgent)).toNumber(), - amounts[2].toNumber() - ); - - assert.equal(resultThird.logs[0].event, 'Withdrew', 'Withdrawal in favor of ' + thirdAgent + ' was not approved') - - /** - * second agent - */ - const resultSecond = await marketJob.withdraw({ from: secondAgent }) - - assert.strictEqual( - (await token.balanceOf.call(secondAgent)).toNumber(), - amounts[1].toNumber() - ); - - assert.equal(resultSecond.logs[0].event, 'Withdrew', 'Withdrawal in favor of ' + secondAgent + ' was not approved') - - /** - * first agent - */ - - const resultFirst = await marketJob.withdraw({ from: firstAgent }) - - assert.strictEqual( - (await token.balanceOf.call(firstAgent)).toNumber(), - amounts[1].toNumber() - ); - - assert.equal(resultFirst.logs[0].event, 'Withdrew', 'Withdrawal in favor of ' + firstAgent + ' was not approved') - - //Final balance === 0 - - assert.equal((await token.balanceOf(escrow)).toNumber(), 0, 'Contract Not full empty') - - try { - const tryMore = await marketJob.withdraw({ from: firstAgent }) - assert.fail('should have thrown before') - } catch (error) { - assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); - } - - - - }) - -}) \ No newline at end of file diff --git a/dao/test/TestMarketJobFactory.js b/dao/test/TestMarketJobFactory.js deleted file mode 100644 index 6dd1950..0000000 --- a/dao/test/TestMarketJobFactory.js +++ /dev/null @@ -1,38 +0,0 @@ -const Factory = artifacts.require('market/MarketJobFactory.sol') -const MarketJob = artifacts.require('market/MarketJob.sol') -const AGIToken = artifacts.require('tokens/SingularityNetTokenMock.sol') - -contract('Market Job Factory', function ([agent, payer]) { - - - beforeEach(async () => { - - }) - // master agent: accounts[0] - it('verifies that an agent can create a market job', async () => { - const token = await AGIToken.new(agent, 100) - const factory = await Factory.new() - const tx = await factory.create( - [agent], // agents - [100], // amounts - [12300], //id service - token.address, // token address - payer, // payer address - "0x0", // first packet ) - { - from: agent - } - ) - - assert.isNotNull(tx) - - const marketJob = await MarketJob.new(tx) - assert.isNotNull(marketJob.address) - - const result = await marketJob.setJobCompleted("0x0", { from: agent }) - - assert.equal(result.logs[0].event, 'JobCompleted', 'Job was not completed') - }) - - -}) \ No newline at end of file diff --git a/dao/test/TestSingularityNetToken.js b/dao/test/TestSingularityNetToken.js deleted file mode 100644 index 32c4150..0000000 --- a/dao/test/TestSingularityNetToken.js +++ /dev/null @@ -1,102 +0,0 @@ -const SingularityNetToken = artifacts.require('./helpers/SingularityNetTokenMock.sol') -const Crowdsale = artifacts.require('./helpers/AgiCrowdsaleMock.sol') - - -const { latestTime, duration } = require('./helpers/latestTime') - -contract('SingularityNetToken', (accounts) => { - - let token - - - beforeEach(async () => { - token = await SingularityNetToken.new(accounts[0], 100) - }) - - it('should have the name Singularity Network Token', async () => { - const name = await token.NAME.call() - assert.equal(name, 'SingularityNET Token', "Singularity Network Token wasn't the name") - }) - - it('should have the symbol AGI', async () => { - const symbol = await token.SYMBOL.call() - assert.equal(symbol, 'AGI', "AGI wasn't the symbol") - }) - - it('should have decimals set to 8', async () => { - const decimals = await token.DECIMALS.call() - assert.equal(decimals, 8, "8 wasn't the value of decimals") - }) - - it('should have INITIAL_SUPPLY set to 1e17 cogs', async () => { - const supply = await token.INITIAL_SUPPLY.call() - assert.equal(supply, 1e17, "1e17 wasn't the value of INITIAL_SUPPLY units") - }) - - it('should set totalSupply to 1e17 cogs', async () => { - const supply = await token.totalSupply.call() - assert.equal(supply, 1e17, "1e17 wasn't the value of totalSupply units") - }) - - it('should be able to transfer if transfers are unpaused', async function () { - // await token.unpause() - - await token.transfer(accounts[1], 100) - - const balance0 = await token.balanceOf(accounts[0]) - assert.equal(balance0.toNumber(), 0) - - const balance1 = await token.balanceOf(accounts[1]) - assert.equal(balance1.toNumber(), 100) - }) - - it('should be able to transfer after transfers are paused and unpaused', async function () { - await token.pause() - await token.unpause() - - await token.transfer(accounts[1], 100) - - const balance1 = await token.balanceOf(accounts[1]) - assert.equal(balance1.toNumber(), 100) - }) - - it('should throw an error trying to transfer while transactions are paused', async function () { - await token.pause() - try { - await token.transfer(accounts[1], 100) - assert.fail('should have thrown before') - } catch (error) { - assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); - } - }) - - it('should throw an error trying to transfer from another account while transactions are paused', async function () { - await token.pause() - try { - await token.transferFrom(accounts[0], accounts[1], 100) - assert.fail('should have thrown before') - } catch (error) { - assert.isAbove(error.message.search('invalid opcode'), -1, 'Invalid opcode error must be returned'); - } - }) - - it('should set the agiCrowdsale as the new owner', async function () { - const startTime = latestTime() + duration.seconds(1) - const endTime = startTime + duration.weeks(1) - const rate = new web3.BigNumber(1000) - const goal = new web3.BigNumber(3000 * Math.pow(10, 18)) - const cap = new web3.BigNumber(15000 * Math.pow(10, 18)) - agiCrowdsale = await Crowdsale.new(token.address, accounts[2], startTime, endTime, rate, cap, goal) - await agiCrowdsale.setBlockTimestamp(startTime + duration.days(1)) - await token.setOwnership(agiCrowdsale.address) - const owner = await token.owner.call() - assert.equal(owner, agiCrowdsale.address, 'Crowdsale is not the owner of the token') - }) - - it('should transfer tokens to someone if owner', async function () { - await token.transferTokens(accounts[2], 50) - const balance2 = await token.balanceOf(accounts[2]) - assert.equal(balance2.toNumber(), 50) - }) - -}) \ No newline at end of file diff --git a/dao/test/helpers/AgiCrowdsaleMock.sol b/dao/test/helpers/AgiCrowdsaleMock.sol deleted file mode 100644 index ca5f5e1..0000000 --- a/dao/test/helpers/AgiCrowdsaleMock.sol +++ /dev/null @@ -1,27 +0,0 @@ -pragma solidity ^0.4.18; - -import "../../contracts/foundation/AgiCrowdsale.sol"; - -contract AgiCrowdsaleMock is AgiCrowdsale { - uint256 public timeStamp = now; - function setBlockTimestamp(uint256 _timeStamp) public onlyOwner { - timeStamp = _timeStamp; - } - - function getBlockTimestamp() internal constant returns (uint256) { - return timeStamp; - } - - function AgiCrowdsaleMock( - address _token, - address _wallet, - uint256 _startTime, - uint256 _endTime, - uint256 _rate, - uint256 _cap, - uint256 _goal) - AgiCrowdsale(_token, _wallet, _startTime, _endTime, _rate, _cap, _goal) - { - } - -} \ No newline at end of file diff --git a/dao/test/helpers/SingularityNetTokenMock.sol b/dao/test/helpers/SingularityNetTokenMock.sol deleted file mode 100644 index 5ab329d..0000000 --- a/dao/test/helpers/SingularityNetTokenMock.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.18; - -import "../../contracts/tokens/SingularityNetToken.sol"; - -contract SingularityNetTokenMock is SingularityNetToken { - - function SingularityNetTokenMock( address owner, uint256 supply) { - balances[owner] = supply; - } - -} \ No newline at end of file diff --git a/dao/test/helpers/assertFail.js b/dao/test/helpers/assertFail.js deleted file mode 100644 index d274110..0000000 --- a/dao/test/helpers/assertFail.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = async function assertFail(callback, message) { - let web3ErrorThrown = false - try { - await callback() - } catch (error) { - if (error.message.search('invalid opcode')) web3ErrorThrown = true - } - assert.ok(web3ErrorThrown, message || 'Transaction should fail') -} diff --git a/dao/test/helpers/increaseTime.js b/dao/test/helpers/increaseTime.js deleted file mode 100644 index a32a051..0000000 --- a/dao/test/helpers/increaseTime.js +++ /dev/null @@ -1,53 +0,0 @@ -const time = require('./latestTime') - -// Increases testrpc time by the passed duration in seconds -const increaseTime = (duration) => { - const id = Date.now() - - return new Promise((resolve, reject) => { - web3.currentProvider.sendAsync({ - jsonrpc: '2.0', - method: 'evm_increaseTime', - params: [duration], - id: id, - }, err1 => { - if (err1) return reject(err1) - - web3.currentProvider.sendAsync({ - jsonrpc: '2.0', - method: 'evm_mine', - id: id+1, - }, (err2, res) => { - return err2 ? reject(err2) : resolve(res) - }) - }) - }) -} - -/** - * Beware that due to the need of calling two separate testrpc methods and rpc calls overhead - * it's hard to increase time precisely to a target point so design your test to tolerate - * small fluctuations from time to time. - * - * @param target time in seconds - */ -const increaseTimeTo = (target) => { - let now = time.latestTime() - if (target < now) throw Error(`Cannot increase current time(${now}) to a moment in the past(${target})`); - let diff = target - now - return increaseTime(diff) -} - -const duration = { - seconds: function(val) { return val}, - minutes: function(val) { return val * this.seconds(60) }, - hours: function(val) { return val * this.minutes(60) }, - days: function(val) { return val * this.hours(24) }, - weeks: function(val) { return val * this.days(7) }, - years: function(val) { return val * this.days(365)} -}; - - -module.exports = { - increaseTimeTo -} \ No newline at end of file diff --git a/dao/test/helpers/latestTime.js b/dao/test/helpers/latestTime.js deleted file mode 100644 index 5c18cef..0000000 --- a/dao/test/helpers/latestTime.js +++ /dev/null @@ -1,12 +0,0 @@ -exports.latestTime = function () { - return global.web3.eth.getBlock('latest').timestamp; -} - -exports.duration = { - seconds: function (val) { return val }, - minutes: function (val) { return val * this.seconds(60) }, - hours: function (val) { return val * this.minutes(60) }, - days: function (val) { return val * this.hours(24) }, - weeks: function (val) { return val * this.days(7) }, - years: function (val) { return val * this.days(365) } -}; \ No newline at end of file diff --git a/dao/truffle.js b/dao/truffle.js deleted file mode 100644 index cf7960f..0000000 --- a/dao/truffle.js +++ /dev/null @@ -1,20 +0,0 @@ -const HDWalletProvider = require("truffle-hdwallet-provider") -const mnemonic = "word word word" //MNEMONIC -const host = "http://localhost:8545"//NODE - -module.exports = { - networks: { - development: { - host: "testrpc", - port: 8545, - network_id: "*" // Match any network id - }, - kovan: { - provider: () => { - return new HDWalletProvider(mnemonic, host) - }, - gas: 4700000, - network_id: "*" // Match any network id - } - }, -}