pando_bot 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 23ff315febfa85d27dc57a02cb56e898f273e71207d12c3862400a2db463ec30
4
+ data.tar.gz: 47111b7bf0034c2d7f7bba643599d5f8ac869adfa2dc9df925f838208b452fe2
5
+ SHA512:
6
+ metadata.gz: 7b4e9bc67d5aab16a77db3d01a2d9467be3d0898fdbe3f74bf93a7cfb5bbae365169102649dd546b7213364274758574ffb6a7c164e8222949128ec2380f7424
7
+ data.tar.gz: b10b8e2298ea6d3120c5da2aa00a605bf5e3579d119dd2a23485000ece1885f00aa3b27edc1c1963b77c77693a193d752e11c17e70f19151153ecf38ec5b4f80
data/.rubocop.yml ADDED
@@ -0,0 +1,16 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: single_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: single_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+
15
+ Lint/UnderscorePrefixedVariableName:
16
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-12-08
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at an.lee.work@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in pando_bot.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+
10
+ gem 'minitest', '~> 5.0'
11
+
12
+ gem 'rubocop', '~> 1.21'
13
+
14
+ gem 'hashids', '~> 1.0'
data/Gemfile.lock ADDED
@@ -0,0 +1,67 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ pando_bot (0.1.0)
5
+ activesupport (>= 5)
6
+ faraday (>= 2)
7
+ faraday-retry (>= 2)
8
+ hashids (>= 1)
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ activesupport (7.0.4)
14
+ concurrent-ruby (~> 1.0, >= 1.0.2)
15
+ i18n (>= 1.6, < 2)
16
+ minitest (>= 5.1)
17
+ tzinfo (~> 2.0)
18
+ ast (2.4.2)
19
+ concurrent-ruby (1.1.10)
20
+ faraday (2.7.1)
21
+ faraday-net_http (>= 2.0, < 3.1)
22
+ ruby2_keywords (>= 0.0.4)
23
+ faraday-net_http (3.0.2)
24
+ faraday-retry (2.0.0)
25
+ faraday (~> 2.0)
26
+ hashids (1.0.6)
27
+ i18n (1.12.0)
28
+ concurrent-ruby (~> 1.0)
29
+ json (2.6.3)
30
+ minitest (5.16.3)
31
+ parallel (1.22.1)
32
+ parser (3.1.3.0)
33
+ ast (~> 2.4.1)
34
+ rainbow (3.1.1)
35
+ rake (13.0.6)
36
+ regexp_parser (2.6.1)
37
+ rexml (3.2.5)
38
+ rubocop (1.40.0)
39
+ json (~> 2.3)
40
+ parallel (~> 1.10)
41
+ parser (>= 3.1.2.1)
42
+ rainbow (>= 2.2.2, < 4.0)
43
+ regexp_parser (>= 1.8, < 3.0)
44
+ rexml (>= 3.2.5, < 4.0)
45
+ rubocop-ast (>= 1.23.0, < 2.0)
46
+ ruby-progressbar (~> 1.7)
47
+ unicode-display_width (>= 1.4.0, < 3.0)
48
+ rubocop-ast (1.24.0)
49
+ parser (>= 3.1.1.0)
50
+ ruby-progressbar (1.11.0)
51
+ ruby2_keywords (0.0.5)
52
+ tzinfo (2.0.5)
53
+ concurrent-ruby (~> 1.0)
54
+ unicode-display_width (2.3.0)
55
+
56
+ PLATFORMS
57
+ x86_64-linux
58
+
59
+ DEPENDENCIES
60
+ hashids (~> 1.0)
61
+ minitest (~> 5.0)
62
+ pando_bot!
63
+ rake (~> 13.0)
64
+ rubocop (~> 1.21)
65
+
66
+ BUNDLED WITH
67
+ 2.3.5
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 an-lee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # PandoBot
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/pando_bot`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'pando_bot'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install pando_bot
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/pando_bot. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/pando_bot/blob/main/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the PandoBot project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/pando_bot/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/test_*.rb']
10
+ end
11
+
12
+ require 'rubocop/rake_task'
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PandoBot
4
+ # for Pando Lake/4swap
5
+ module Lake
6
+ attr_reader :client
7
+
8
+ # HTTP API
9
+ class API
10
+ def initialize(endpoint = 'https://api.4swap.org')
11
+ @client = Faraday.new(url: endpoint) do |f|
12
+ f.request :json
13
+ f.request :retry
14
+ f.response :raise_error
15
+ f.response :logger
16
+ f.response :json
17
+ end
18
+ end
19
+
20
+ def pre_order(**params)
21
+ path = '/api/orders/pre'
22
+
23
+ payload = {
24
+ pay_asset_id: params[:pay_asset_id],
25
+ fill_asset_id: params[:fill_asset_id],
26
+ funds: params[:funds]&.to_s,
27
+ amount: params[:amount]&.round(8)&.to_s
28
+ }.compact
29
+
30
+ r = @client.post path, payload.to_json
31
+ r.body
32
+ end
33
+
34
+ def order(order_id, authorization:)
35
+ path = "/api/orders/#{order_id}"
36
+ r = @client.get path, nil, { Authorization: authorization }
37
+ r.body
38
+ end
39
+
40
+ def pairs
41
+ path = '/api/pairs'
42
+ @client.get(path).body
43
+ end
44
+
45
+ def actions(**options)
46
+ path = '/api/actions'
47
+ payload = {
48
+ action: [3, options[:user_id], options[:follow_id], options[:asset_id], options[:route_id],
49
+ options[:minimum_fill]].join(',')
50
+ }
51
+ @client.post(path, payload.to_json).body
52
+ end
53
+
54
+ def tradable_asset_ids
55
+ _pairs = pairs['data']['pairs']
56
+ _ids = []
57
+ _pairs.each do |pair|
58
+ _ids.push(pair['base_asset_id'])
59
+ _ids.push(pair['quote_asset_id'])
60
+ end
61
+ _ids.uniq!
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Naming/MethodParameterName
4
+ # rubocop:disable Metrics/AbcSize
5
+ # rubocop:disable Metrics/MethodLength
6
+ module PandoBot
7
+ module Lake
8
+ # Curve protocal
9
+ class Curve
10
+ A_CONST = 200
11
+ N_COINS = 2
12
+ ONE = 1
13
+ TWO = 2
14
+
15
+ attr_reader :a
16
+
17
+ def initialize(a = A_CONST)
18
+ @a = a
19
+ end
20
+
21
+ def d_const(xp = [])
22
+ xp = xp.map(&:to_f)
23
+ sum = xp.sum
24
+ return 0 if sum <= 0
25
+
26
+ dp = 0
27
+ d = sum
28
+ ann = a * N_COINS
29
+
30
+ 255.times do
31
+ _dp = d
32
+
33
+ xp.each do |x|
34
+ _dp = _dp * d / (x * N_COINS)
35
+ end
36
+
37
+ dp = d
38
+
39
+ d1 = (ann - ONE) * d
40
+ d2 = (N_COINS + ONE) * _dp
41
+ d = (((ann * sum) + (_dp * N_COINS)) * d) / (d1 + d2)
42
+
43
+ break if (d - dp).floor(0).zero?
44
+ end
45
+
46
+ d.floor(0)
47
+ end
48
+
49
+ def y_const(d, x)
50
+ d = d.to_f
51
+ x = x.to_f
52
+
53
+ ann = a * N_COINS
54
+ c = (d * d) / (x * N_COINS)
55
+ c = (c * d) / (ann * N_COINS)
56
+
57
+ b = x + (d / ann)
58
+
59
+ yp = 0
60
+ y = d
61
+
62
+ 255.times do
63
+ yp = y
64
+ y = ((y * y) + c) / (y + y + b - d)
65
+ break if (y - yp).floor(0).zero?
66
+ end
67
+
68
+ y
69
+ end
70
+
71
+ def x_const(d, y)
72
+ d = d.to_f
73
+ y = y.to_f
74
+ ann = a * N_COINS
75
+ k = (d * d * d) / ann / N_COINS / N_COINS
76
+ j = (d / ann) - d + y + y
77
+ n = (y - j) / TWO
78
+ Math.sqrt((k / y) + (n * n)) + n
79
+ end
80
+
81
+ # swap A for B
82
+ # x, y is liquidity of A, B
83
+ # dx is supply amount of A
84
+ def swap(x, y, dx, d = nil)
85
+ x *= 1e9
86
+ y *= 1e9
87
+ dx *= 1e9
88
+
89
+ _d = d || d_const([x, y])
90
+ _x = x + dx
91
+ _y = y_const(_d, _x)
92
+ (y - _y) / 1e9
93
+ end
94
+
95
+ # swap A for B
96
+ # x, y is liquidity of A, B
97
+ # dy is wanted amount of B
98
+ def swap_reverse(x, y, dy, d = nil)
99
+ x *= 1e9
100
+ y *= 1e9
101
+ dy *= 1e9
102
+ _d = d || d_const([x, y])
103
+ _y = y - dy
104
+ _x = x_const(_d, _y)
105
+ (_x - x) / 1e9
106
+ end
107
+
108
+ def price_impact(dx, dy)
109
+ [(1 - (dy / dx)), 0].max
110
+ end
111
+ end
112
+ end
113
+ end
114
+ # rubocop:enable Naming/MethodParameterName
115
+ # rubocop:enable Metrics/AbcSize
116
+ # rubocop:enable Metrics/MethodLength
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Metrics/AbcSize
4
+ # rubocop:disable Metrics/ClassLength
5
+ # rubocop:disable Metrics/CyclomaticComplexity
6
+ # rubocop:disable Metrics/MethodLength
7
+ # rubocop:disable Metrics/PerceivedComplexity
8
+ module PandoBot
9
+ module Lake
10
+ # swap using paris
11
+ class PairRoutes
12
+ PRECISION = 8
13
+ HASH_SALT = 'uniswap routes'
14
+
15
+ attr_reader :pairs, :uniswap, :curve, :routes
16
+
17
+ def initialize(pairs)
18
+ @uniswap = PandoBot::Lake::Uniswap.new
19
+ @curve = PandoBot::Lake::Curve.new
20
+ @routes = {}.with_indifferent_access
21
+ @pairs =
22
+ pairs.map do |pair|
23
+ pair = pair.with_indifferent_access
24
+
25
+ base_amount = pair[:base_amount].to_f
26
+ quote_amount = pair[:quote_amount].to_f
27
+ fill_percent = 1 - pair[:fee_percent].to_f
28
+
29
+ d = 0
30
+ d = @curve.d_const([base_amount * 1e9, quote_amount * 1e9]) if pair[:swap_method] == 'curve'
31
+
32
+ pair.merge(
33
+ base_amount:,
34
+ quote_amount:,
35
+ fill_percent:,
36
+ K: (base_amount * quote_amount),
37
+ D: d
38
+ )
39
+ end
40
+ @pairs.each do |pair|
41
+ set_asset_route pair[:base_asset_id], pair
42
+ set_asset_route pair[:quote_asset_id], pair
43
+ end
44
+ @pairs.freeze
45
+ end
46
+
47
+ def pre_order(input_asset:, output_asset:, input_amount: nil, output_amount: nil)
48
+ funds = input_amount.to_f.ceil(PRECISION)
49
+ amount = output_amount.to_f.floor(PRECISION)
50
+
51
+ if input_amount.present?
52
+ raise PandoBot::Lake::SwapError, 'input amount invalid' if input_amount.negative?
53
+
54
+ best = best_route input_asset, output_asset, input_amount
55
+ amount = best[:amount]
56
+ elsif output_amount.present?
57
+ raise PandoBot::Lake::SwapError, 'output amount invalid' if output_amount.negative?
58
+
59
+ best = best_route_reverse input_asset, output_asset, output_amount
60
+ funds = best[:funds]
61
+ else
62
+ raise PandoBot::Lake::SwapError, 'input or output are needed'
63
+ end
64
+
65
+ raise PandoBot::Lake::SwapError, 'no pair route found' if best.blank?
66
+
67
+ raise PandoBot::Lake::SwapError, 'swap amount not support' if amount.blank? || funds.blank?
68
+
69
+ best
70
+ .merge(
71
+ {
72
+ amount: format("%.#{PRECISION}f", amount),
73
+ funds: format("%.#{PRECISION}f", funds),
74
+ route_assets: best[:route_assets],
75
+ price_impact: best[:price_impact],
76
+ routes: Hashids.new(HASH_SALT).encode(best[:route_ids]),
77
+ pay_asset_id: input_asset,
78
+ fill_asset_id: output_asset,
79
+ pay_amount: format("%.#{PRECISION}f", funds),
80
+ fill_amount: format("%.#{PRECISION}f", amount),
81
+ state: 'Done'
82
+ }
83
+ )
84
+ end
85
+
86
+ private
87
+
88
+ def set_asset_route(asset, pair)
89
+ routes = @routes[asset].dup || []
90
+ opposit = opposit_asset(pair, asset)
91
+
92
+ return if opposit.in?(routes)
93
+
94
+ @routes[asset] = routes.push(opposit)
95
+ end
96
+
97
+ def find_pair(base, quote)
98
+ @pairs.find(&lambda { |p|
99
+ p1 = p[:base_asset_id] == base && p[:quote_asset_id] == quote
100
+ p2 = p[:base_asset_id] == quote && p[:quote_asset_id] == base
101
+ p1 || p2
102
+ })
103
+ end
104
+
105
+ def find_pair_by_route_id(id)
106
+ @pairs.find(&->(p) { p[:route_id] == id })
107
+ end
108
+
109
+ def opposit_asset(pair, input)
110
+ input == pair[:base_asset_id] ? pair[:quote_asset_id] : pair[:base_asset_id]
111
+ end
112
+
113
+ def best_route(input_asset, output_asset, input_amount)
114
+ deep = 4
115
+ best = {}
116
+ queue = [
117
+ {
118
+ key: input_asset,
119
+ ctx: {
120
+ route_assets: [input_asset],
121
+ route_ids: [],
122
+ amount: 0,
123
+ funds: 0,
124
+ price_impact: 0
125
+ }
126
+ }
127
+ ]
128
+
129
+ while queue.size.positive?
130
+ current = queue.pop
131
+ step_input_amount = current[:ctx][:amount].zero? ? input_amount : current[:ctx][:amount]
132
+ neibors = @routes[current[:key]] || []
133
+
134
+ neibors.each do |neibor|
135
+ next if current[:ctx][:route_ids].size == deep - 1 && neibor != output_asset
136
+
137
+ pair = find_pair current[:key], neibor
138
+ next if pair.blank?
139
+ next if pair[:route_id].in?(current[:ctx][:route_ids])
140
+
141
+ transaction = swap pair, current[:key], step_input_amount
142
+ next if transaction.blank?
143
+
144
+ new_ctx = {
145
+ route_assets: (current[:ctx][:route_assets] + [neibor]),
146
+ route_ids: (current[:ctx][:route_ids] + [pair[:route_id]]),
147
+ amount: transaction[:amount],
148
+ funds: transaction[:funds],
149
+ price_impact: (((1 + current[:ctx][:price_impact]) * (1 + transaction[:price_impact])) - 1)
150
+ }
151
+
152
+ if neibor == output_asset
153
+ best = new_ctx if best.blank? || best[:amount].to_f < new_ctx[:amount]
154
+ next
155
+ end
156
+
157
+ queue.push({ key: neibor, ctx: new_ctx }) if new_ctx[:route_assets].size < deep
158
+ end
159
+ end
160
+
161
+ best
162
+ end
163
+
164
+ def best_route_reverse(input_asset, output_asset, output_amount)
165
+ deep = 4
166
+ best = nil
167
+ queue = [
168
+ {
169
+ key: output_asset,
170
+ ctx: {
171
+ route_assets: [output_asset],
172
+ route_ids: [],
173
+ amount: 0,
174
+ funds: 0,
175
+ price_impact: 0
176
+ }
177
+ }
178
+ ]
179
+
180
+ while queue.size.positive?
181
+ current = queue.pop
182
+ step_input_amount = current[:ctx][:funds].zero? ? output_amount : current[:ctx][:funds]
183
+ neibors = @routes[current[:key]] || []
184
+
185
+ neibors.each do |neibor|
186
+ next if current[:ctx][:route_ids].size == deep - 1 && neibor != input_asset
187
+
188
+ pair = find_pair current[:key], neibor
189
+ next if pair.blank?
190
+ next if pair[:route_id].in?(current[:ctx][:route_ids])
191
+
192
+ transaction = swap_reverse pair, neibor, step_input_amount
193
+ next if transaction.blank?
194
+
195
+ new_ctx = {
196
+ route_assets: ([neibor] + current[:ctx][:route_assets]),
197
+ route_ids: ([pair[:route_id]] + current[:ctx][:route_ids]),
198
+ amount: transaction[:amount],
199
+ funds: transaction[:funds],
200
+ price_impact: (((1 + current[:ctx][:price_impact]) * (1 + transaction[:price_impact])) - 1)
201
+ }
202
+
203
+ if neibor == input_asset
204
+ best = new_ctx if best.blank? || best[:funds] > new_ctx[:funds]
205
+ next
206
+ end
207
+
208
+ if new_ctx[:route_assets].size < deep || (new_ctx[:route_assets].size == deep && neibor == input_asset)
209
+ queue.push({ key: neibor,
210
+ ctx: new_ctx })
211
+ end
212
+ end
213
+ end
214
+
215
+ best
216
+ end
217
+
218
+ def swap(pair, input_asset, input_amount)
219
+ dy = 0
220
+ price_impact = 0
221
+ dx = input_amount.to_f * pair[:fill_percent]
222
+
223
+ x = pair[:base_amount]
224
+ y = pair[:quote_amount]
225
+
226
+ x, y = y, x if input_asset != pair[:base_asset_id]
227
+
228
+ if pair[:swap_method] == 'curve'
229
+ dy = @curve.swap(x, y, dx)
230
+ dy = dy.to_f.floor(PRECISION)
231
+ price_impact = curve.price_impact(input_amount, dy)
232
+ else
233
+ dy = @uniswap.swap(x, y, dx)
234
+ dy = dy.to_f.floor(PRECISION)
235
+ price_impact = uniswap.price_impact(x, y, input_amount, dy)
236
+ end
237
+
238
+ return if dy <= 0
239
+
240
+ {
241
+ funds: input_amount.to_f.round(PRECISION),
242
+ amount: dy,
243
+ price_impact:
244
+ }
245
+ end
246
+
247
+ def swap_reverse(pair, input_asset, output_amount)
248
+ dx = 0
249
+ price_impact = 0
250
+
251
+ dy = output_amount
252
+
253
+ x = pair[:base_amount]
254
+ y = pair[:quote_amount]
255
+
256
+ x, y = y, x if input_asset != pair[:base_asset_id]
257
+
258
+ return if dy > y
259
+
260
+ if pair[:swap_method] == 'curve'
261
+ dx = @curve.swap_reverse(x, y, dy)
262
+ dx = (dx / pair[:fill_percent]).to_f.ceil(PRECISION)
263
+ price_impact = curve.price_impact(dx, output_amount)
264
+ else
265
+ dx = @uniswap.swap_reverse(x, y, dy)
266
+ dx = (dx / pair[:fill_percent]).to_f.ceil(PRECISION)
267
+ dx = dx.to_f.ceil(PRECISION)
268
+ price_impact = uniswap.price_impact(x, y, dx, output_amount)
269
+ end
270
+
271
+ return if dx <= 0
272
+
273
+ {
274
+ funds: dx,
275
+ amount: output_amount,
276
+ price_impact:
277
+ }
278
+ end
279
+ end
280
+ end
281
+ end
282
+ # rubocop:enable Metrics/AbcSize
283
+ # rubocop:enable Metrics/ClassLength
284
+ # rubocop:enable Metrics/CyclomaticComplexity
285
+ # rubocop:enable Metrics/MethodLength
286
+ # rubocop:enable Metrics/PerceivedComplexity
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Naming/MethodParameterName
4
+ module PandoBot
5
+ module Lake
6
+ # Uniswap protocal
7
+ class Uniswap
8
+ def initialize; end
9
+
10
+ # swap A for B
11
+ # x, y is liquidity of A, B
12
+ # dx is supply amount of A
13
+ # k is liquidity of pair
14
+ def swap(x, y, dx, k = nil)
15
+ x = x.to_f
16
+ y = y.to_f
17
+ dx = dx.to_f
18
+
19
+ _k = (k || (x * y)).to_f
20
+ _x = x + dx
21
+ _y = _k / _x
22
+ y - _y
23
+ end
24
+
25
+ # swap A for B
26
+ # x, y is liquidity of A, B
27
+ # dx is supply amount of A
28
+ # dy is wanted amount of B
29
+ def swap_reverse(x, y, dy, k = nil)
30
+ x = x.to_f
31
+ y = y.to_f
32
+ dy = dy.to_f
33
+
34
+ _k = (k || (x * y)).to_f
35
+ _y = y - dy
36
+ _x = _k / _y
37
+ _x - x
38
+ end
39
+
40
+ def price_impact(x, y, dx, dy)
41
+ x = x.to_f
42
+ y = y.to_f
43
+ dx = dx.to_f
44
+ dy = dy.to_f
45
+
46
+ return 0 if x.zero? || y.zero?
47
+
48
+ [
49
+ (1 - ((y - dy) / (x + dx) / (y / x))),
50
+ 0
51
+ ].max.to_f
52
+ end
53
+ end
54
+ end
55
+ end
56
+ # rubocop:enable Naming/MethodParameterName
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lake/api'
4
+ require_relative 'lake/curve'
5
+ require_relative 'lake/pair_routes'
6
+ require_relative 'lake/uniswap'
7
+
8
+ module PandoBot
9
+ # API for Pando Lake/4swap
10
+ module Lake
11
+ def self.api
12
+ @api = PandoBot::Lake::API.new
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PandoBot
4
+ VERSION = '0.1.0'
5
+ end
data/lib/pando_bot.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'faraday/retry'
5
+ require 'hashids'
6
+ require_relative 'pando_bot/version'
7
+ require_relative 'pando_bot/lake'
8
+
9
+ module PandoBot
10
+ class Error < StandardError; end
11
+
12
+ module Lake
13
+ class Error < Error; end
14
+ end
15
+
16
+ module Lake
17
+ class SwapError < Lake::Error; end
18
+ end
19
+ end
data/sig/pando_bot.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module PandoBot
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pando_bot
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - an-lee
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-12-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2'
41
+ - !ruby/object:Gem::Dependency
42
+ name: faraday-retry
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '2'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '2'
55
+ - !ruby/object:Gem::Dependency
56
+ name: hashids
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '1'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '1'
69
+ description: An simple API wrapper for pando lake/leaf/rings
70
+ email:
71
+ - an.lee.work@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".rubocop.yml"
77
+ - CHANGELOG.md
78
+ - CODE_OF_CONDUCT.md
79
+ - Gemfile
80
+ - Gemfile.lock
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - lib/pando_bot.rb
85
+ - lib/pando_bot/lake.rb
86
+ - lib/pando_bot/lake/api.rb
87
+ - lib/pando_bot/lake/curve.rb
88
+ - lib/pando_bot/lake/pair_routes.rb
89
+ - lib/pando_bot/lake/uniswap.rb
90
+ - lib/pando_bot/version.rb
91
+ - sig/pando_bot.rbs
92
+ homepage: https://github.com/an-lee/pando_bot
93
+ licenses:
94
+ - MIT
95
+ metadata:
96
+ allowed_push_host: https://rubygems.org/
97
+ homepage_uri: https://github.com/an-lee/pando_bot
98
+ source_code_uri: https://github.com/an-lee/pando_bot
99
+ changelog_uri: https://github.com/an-lee/pando_bot/blob/main/CHANGELOG.md
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: 3.1.0
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubygems_version: 3.3.4
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: An simple API wrapper for pando.im
119
+ test_files: []