Giter Club home page Giter Club logo

moneyflow2's Introduction

Branches

  1. master is for releases only
  2. dev is for testing
  3. dev2 is for development

The Community

Our thanks go to these people:

  1. @AnthonyAkentiev - Smart Contracts development
  2. @Kirill Guzenko - Smart Contracts development
  3. @Max - Smart Contracts development
  4. @Vladimir - Smart Contracts development
  5. @Mike - Smart Contracts development

Contact Us

PRs Welcome

Please submit issues here.

moneyflow2's People

Contributors

enkogu avatar

Watchers

 avatar  avatar  avatar  avatar

moneyflow2's Issues

Think about min number of required "elements" that will be able to implement ANY available moneyflow sceheme

Ideas

1.1) Funds can not be added to UnsortedSplitters
OR
1.2) Funds can be added to the splitter in order to fill them in parallel:
2) Splitters should contain same type elements only (absolute expenses, relative expenses, funds).
You can't put absolute exp + relative exp into 1 splitter.
3) Rename to "Parallel" splitter
...

TODO

  1. ideas -> list of “almost equal” moneyflow schemes
  2. group -> basic scenarious
  3. basic scenarios -> basic element and parameters
  4. check that all scenarios IMPLEMENTABLE with this element and parameters

The document is here - https://hackmd.io/yhP4qvRCQbq27uWvrwtRCA

Goal

File with:

  1. scenarious ideas
  2. basic scenarios
  3. basic elements (maybe, different ideas/approaches)

Fix funds + splitter

TODOs

  1. Can not add Fund to unsorted splitter
  2. In a top-down splitter expenses should go BEFORE funds

Descriptions (by Kirill)

Кароч, все рушится к херам, когда мы начинаем исопльзовать фонды в схемах. Нужно прям тотально перерабатывать ключевые алгоритмы

14 replies
enkogu [3 hours ago]
Все построено на том, что каждый элемент знает, сколько точно ему нужно, не больше и не меньше. На этом построены сплиттеры, функции getMinWeiNeeded/getTotalWeiNeeded/processFunds

enkogu [3 hours ago]
Плюс мы должны определиться, как будет работать система в ряде сценариев. Вот например

UnsortedSplitter U, 
Fund F1 with 10 eth need, 
AbsoluteExpense A1 with 3 eth need
AbsoluteExpense A2 with 5 eth need

       |-A1 3 eth
    U -|-F1 10 eth
       |-A2 5 eth

// --------------- SEND 100
U.getTotalWeiNeeded(100) -> // 18
for in
A1.getTotalWeiNeeded(100) // 3
F1.getTotalWeiNeeded(100) // 10
A2.getTotalWeiNeeded(100) // 5

// --------------- SEND 12
U.getTotalWeiNeeded(12) -> // 18
for in
A1.getTotalWeiNeeded(12) // 3
F1.getTotalWeiNeeded(12) // 10
A2.getTotalWeiNeeded(12) // 5

// --------------- SEND 9
U.getTotalWeiNeeded(9) -> // 17
for in
A1.getTotalWeiNeeded(9) // 3
F1.getTotalWeiNeeded(9) // 9
A2.getTotalWeiNeeded(9) // 5```

enkogu [3 hours ago]
В сценарии send 100 все в порядке, а что в сценарии с 12, а в сценарии с 9?

enkogu [3 hours ago]
Вариант 1 – все фонды отложить и пройти их в отдельном цикле. То есть в сценарии с 9eth в фонд упадет 1eth и ничего не заревертится
Вариант 2 – ревертить, так как мы последовательно отрабатываем ноды, а на третью уже не хватит (edited)

enkogu [3 hours ago]
Это лишь один из сценариев который появляется. А их с десяток, наверное

enkogu [3 hours ago]
Может быть, нам стоит немного пересмотреть концепцию сплиттеров.
Можно просто в тексте позапрещать определенные сценарии.
Можно добавить кучу сложных проверок
Можно выносить фонды в отдельный цикл

enkogu [2 hours ago]
Есть еще такой вариант – для unsortedSplitter выносить в отдельный цикл фонды, а для topDown – нет.

enkogu [2 hours ago]
Можно еще запретить к unsorted цеплять фонды

enkogu [1 hour ago]
Но останется еще такая проблема
|-A1 3 eth TD -|-F1 10 eth |-A2 5 eth

enkogu [1 hour ago]
То есть в topdown если фонд стоит посередине, то он должен быть полностью заполнен.
Является ли это правильным поведением?

Docs: new improvements

3

  1. почему-то в конце 2 больших куска кода. Не читабельно и не понял, в чем отличие.

4

  1. (НЕ СДЕЛАНО) code examples добавить/пополнить (см. TODO)

5

  1. Описания всех функций добавить (в аналогичном стиле как вот тут - "2-receivers")
  2. Code example - TODOs поправить

getMinWeiNeeded() refactoring

https://hackmd.io/s/SkyXYnsj7

Идея 3. Переделать поведение getMinWeiNeeded

Какая сейчас ситуация?

relative будет ревертить, если прислать processFunds.value(0)(1eth)
Значит, когда relative говорил, что mineWeiNeeded() == 0, он врал.
Это первое несоответствие.
Заходим в topDownSplitter и видим:
function getMinWeiNeeded()public view returns(uint) {
  if(!isOpen()) {
   return 0;
  }
  uint out = 0;
  for(uint j=childrenCount; j>0; --j) {
   IWeiReceiver c = IWeiReceiver(children[j-1]);
   if(c.getPercentsMul100()>0) {
    out = 10000 * out / c.getPercentsMul100();
   }else {
    out += c.getMinWeiNeeded();
   }
  }
  return out;
 }
Сплиттер считает проценты для relative! Казалось бы, зачем, ведь у них minWeiNeeded==0
А я помню, почему так было сделано. Если в крупной структуре элементов будут стоять одни relative, а в конце absolute, то чтобы деньги добрались до absolute, нужно еще учесть, что будет оседать на relative. Но это неправильно! На самом деле для relative getMinWeiNeeded и getTotalWeiNeeded должны быть равны! И getMinWeiNeeded должна зависеть от потока.

В таком случае код станет уже таким

function getMinWeiNeeded(uint _currentFlow)public view returns(uint) {
if(!isOpen()) {
   return 0;
  }
  uint out = 0;
  for(uint j=childrenCount; j>0; --j) {
   out += IWeiReceiver(children[j-1]).getMinWeiNeeded(_currentFlow);
  }
  return out;
 }
А если введем модификатор zeroIfClosed и вынесем out,

function getMinWeiNeeded(uint _currentFlow)public view zeroIfClosed returns(uint out) {
  for(uint j=childrenCount; j>0; --j) {
   out += IWeiReceiver(children[j-1]).getMinWeiNeeded(_currentFlow);
  }
 }
то код станет значительно проще и читабельнее.

Think - what is a "moneyflow scheme example"?

If it a smart contract (with business logic) or is it a javascript migration file?

What is "an example"?

  1. Set of splitters, expenses, etc connected together
  2. Business logic - methods like setBonusForEmployee(), setSalaryForEmployee() that access nodes/smart contract directly. Can be used to derive smart contract WITH isCanDo() above and to use this scheme as a base.
  3. Migrations - can be used to deploy that scheme to the net.

How user acts?

  1. Gets a template
  2. Read the source code
  3. Deploys the scheme to the testnet and tests it
  4. Derives his own smart contract from the scheme
  5. Overrides some methods, add new methods, etc
  6. Adds isCanDo() using Thetta/core
  7. Deploys his derived scheme to the mainnet and uses it

Research: "Moneyflow by Kirill" (hight-level design)

Goal

Hackmd file:

  1. "Moneyflow by Kirill" system properties:
    a. isomorphic (one type of node only)
    b. every node has ALL parameters
    c. streaming ("поточность")
    d. (???) automation should be implementable on top
    e. (???) push payments
    f. (???) "частичное посылание средств"

  2. Node properties:

  3. Processing Rules:

  4. What scenarios are unimplementable in this case?

  5. What pros/cons of that approach?

Fix: usorted splitter + fund = doublespend

Кароч, все рушится к херам, когда мы начинаем исопльзовать фонды в схемах. Нужно прям тотально перерабатывать ключевые алгоритмы

14 replies
enkogu [3 hours ago]
Все построено на том, что каждый элемент знает, сколько точно ему нужно, не больше и не меньше. На этом построены сплиттеры, функции getMinWeiNeeded/getTotalWeiNeeded/processFunds

enkogu [3 hours ago]
Плюс мы должны определиться, как будет работать система в ряде сценариев. Вот например

    UnsortedSplitter U, 
    Fund F1 with 10 eth need, 
    AbsoluteExpense A1 with 3 eth need
    AbsoluteExpense A2 with 5 eth need

           |-A1 3 eth
        U -|-F1 10 eth
           |-A2 5 eth

// --------------- SEND 100
U.getTotalWeiNeeded(100) -> // 18
    for in
        A1.getTotalWeiNeeded(100) // 3
        F1.getTotalWeiNeeded(100) // 10
        A2.getTotalWeiNeeded(100) // 5

// --------------- SEND 12
U.getTotalWeiNeeded(12) -> // 18
    for in
        A1.getTotalWeiNeeded(12) // 3
        F1.getTotalWeiNeeded(12) // 10
        A2.getTotalWeiNeeded(12) // 5


// --------------- SEND 9
U.getTotalWeiNeeded(9) -> // 17
    for in
        A1.getTotalWeiNeeded(9) // 3
        F1.getTotalWeiNeeded(9) // 9
        A2.getTotalWeiNeeded(9) // 5```


enkogu [3 hours ago]
В сценарии send 100 все в порядке, а что в сценарии с 12, а в сценарии с 9?

enkogu [3 hours ago]
Вариант 1 – все фонды отложить и пройти их в отдельном цикле. То есть в сценарии с 9eth в фонд упадет 1eth и ничего не заревертится
Вариант 2 – ревертить, так как мы последовательно отрабатываем ноды, а на третью уже не хватит (edited)

enkogu [3 hours ago]
Это лишь один из сценариев который появляется. А их с десяток, наверное

enkogu [3 hours ago]
Может быть, нам стоит немного пересмотреть концепцию сплиттеров.
Можно просто в тексте позапрещать определенные сценарии.
Можно добавить кучу сложных проверок
Можно выносить фонды в отдельный цикл

enkogu [2 hours ago]
Есть еще такой вариант – для unsortedSplitter выносить в отдельный цикл фонды, а для topDown – нет.


enkogu [2 hours ago]
Можно еще запретить к unsorted цеплять фонды


enkogu [1 hour ago]
Но останется еще такая проблема
            ```|-A1 3 eth
        TD -|-F1 10 eth
            |-A2 5 eth```


enkogu [1 hour ago]
То есть в topdown если фонд стоит посередине, то он должен быть полностью заполнен.
Является ли это правильным поведением?

Moneyflow should work only with ERC20 tokens. Design it (DO NOT IMPLEMENT)

Design it, DO NOT IMPLEMENT!

Goal - How moneyflow2 should work

  1. Basic moneyflow2 entity - tokens (only ERC20?)
  2. If you need to process ETH - wrap it into WETH
  3. moneyflow2 should allow to use other token types (ERC721, ST20, ERC1384, etc). How to design it so that moneyflow will be "extendable"? Can we use ERC20 wrappers for that token types?

Output

  1. Hackmd file with the description of how moneyflow2 should be implement to achieve Goal

Docs: improvements

1

  1. в code sample
    заменить
    WeiRelativeExpenseWithPeriod reserveFund =newWeiRelativeExpenseWithPeriod(250000,0,false);
    WeiRelativeExpenseWithPeriod dividendsFund =newWeiRelativeExpenseWithPeriod(750000,0,false);

на фонды

  • явно сделать именованные переменные для параметров, чтобы было понятно

3

  1. code example в конце
  2. что произойдет, если мы сначала заполним OneTimeFund полностью фонд, потом сделаем из него flush()?
    он опять будет собирать деньги?
  3. названия всех элементов переименовал
    WeiFund
    WeiFundWithPeriod
    WeiFundWithPeriodSliding
    WeiAbsoluteExpenseWithPeriodSliding
    WeiRelativeExpenseWithPeriodSliding

вот таски https://github.com/Thetta/Moneyflow/projects/1
https://github.com/Thetta/Moneyflow/projects/3

4

  1. code examples добавить/пополнить

5

  1. мне кажется, что если в Destination называлось flush/flushTo, то аналогично должно и в Table быть: flushForElement()
  2. переименовать element -> node или item везде в table

MoneyflowTable is distinguished from Destination by the fact that it have withdrawFundsFromElement()instead of flush()/flushTo().

Moneyflow: Our own company scheme

Use DAO-templates repo to add TWO sample Moneyflow templates:
With employees (salaries, bonues, tasks, etc)

Docs here:
https://docs.thetta.io/moneyflow-guide/examples/example-2

Output

  1. Moneyflow example (smart contract or a javascript migration file?) that can be used as a basic template (without WeiTable).
  2. Moneyflow example (smart contract or a javascript migration file?) that can be used as a basic template (with WeiTable).

https://hackmd.io/s/SkyXYnsj7 <--- new features here

Desc

https://hackmd.io/s/SkyXYnsj7

Таким образом, у нас получается три базовых кубика:
EXPENSE (let’s call it Expense, but that can be a Fund really)
RELATIVE EXPENSE
SPLITTER

Что нужно сделать?

  1. Изменить сплиттер и его поведение (много изменений в тестах, часов 6)
  2. Изменить фонд (часа полтора фиксов)
  3. Протестировать и описать сценарий, когда maxAmount кратен minAmount

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.