ethereum_abi 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: fb9fd98c2615378d3c6691efbc4ee7378eb8a879ad4c8cfe90c5278d67277dcf
4
+ data.tar.gz: e6847278bb5577c2061f0e92cbc5d22486f564aada7399c636af4bf98f06481e
5
+ SHA512:
6
+ metadata.gz: 2a80abc55633e0c9ac34d69c91f900ac38159fa286635075714b07fa02360d43d9bd96b7bea87c68d934e9ee78c6f998460be991c745392df254d12b98f5b7a6
7
+ data.tar.gz: d67ecd079f1fb4d1637c9c18d612667ceea64f8c9feb50f1146c8ad60c6521ead8ad16675309c6a597f131f69aa2fb8136c0cc8c4579cf71632bc4dfe2c73f87
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,62 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Naming/MethodParameterName:
13
+ Enabled: false
14
+
15
+ Layout/LineLength:
16
+ Max: 120
17
+ Exclude:
18
+ - './test/**/*.rb'
19
+ - './test/*.rb'
20
+
21
+ Naming/VariableNumber:
22
+ Exclude:
23
+ - './test/**/*.rb'
24
+ - './test/*.rb'
25
+
26
+ Lint/UnderscorePrefixedVariableName:
27
+ Exclude:
28
+ - './test/**/*.rb'
29
+ - './test/*.rb'
30
+
31
+ Metrics/MethodLength:
32
+ Enabled: false
33
+
34
+ Metrics/AbcSize:
35
+ Enabled: false
36
+
37
+ Style/StringConcatenation:
38
+ Exclude:
39
+ - './test/**/*.rb'
40
+ - './test/*.rb'
41
+
42
+ Metrics/PerceivedComplexity:
43
+ Enabled: false
44
+
45
+ Style/ModuleFunction:
46
+ Enabled: false
47
+
48
+ Metrics/CyclomaticComplexity:
49
+ Enabled: false
50
+
51
+ Style/Documentation:
52
+ Enabled: false
53
+
54
+ Metrics/ModuleLength:
55
+ Enabled: false
56
+
57
+ Metrics/ClassLength:
58
+ Enabled: false
59
+
60
+ Style/SlicingWithRange:
61
+ Enabled: false
62
+
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-09-21
4
+
5
+ - Initial release
6
+ - Copy ABI from https://github.com/cryptape/ruby-ethereum
@@ -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 tema.place@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 ethereum_abi.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ gem "rlp", "~> 0.7.3"
data/Gemfile.lock ADDED
@@ -0,0 +1,47 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ethereum_abi (0.1.0)
5
+ rlp (~> 0.7.3)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ json (2.6.2)
12
+ minitest (5.16.3)
13
+ parallel (1.22.1)
14
+ parser (3.1.2.1)
15
+ ast (~> 2.4.1)
16
+ rainbow (3.1.1)
17
+ rake (13.0.6)
18
+ regexp_parser (2.5.0)
19
+ rexml (3.2.5)
20
+ rlp (0.7.3)
21
+ rubocop (1.36.0)
22
+ json (~> 2.3)
23
+ parallel (~> 1.10)
24
+ parser (>= 3.1.2.1)
25
+ rainbow (>= 2.2.2, < 4.0)
26
+ regexp_parser (>= 1.8, < 3.0)
27
+ rexml (>= 3.2.5, < 4.0)
28
+ rubocop-ast (>= 1.20.1, < 2.0)
29
+ ruby-progressbar (~> 1.7)
30
+ unicode-display_width (>= 1.4.0, < 3.0)
31
+ rubocop-ast (1.21.0)
32
+ parser (>= 3.1.1.0)
33
+ ruby-progressbar (1.11.0)
34
+ unicode-display_width (2.3.0)
35
+
36
+ PLATFORMS
37
+ x86_64-darwin-20
38
+
39
+ DEPENDENCIES
40
+ ethereum_abi!
41
+ minitest (~> 5.0)
42
+ rake (~> 13.0)
43
+ rlp (~> 0.7.3)
44
+ rubocop (~> 1.21)
45
+
46
+ BUNDLED WITH
47
+ 2.3.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Tema
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
+ # EthereumAbi
2
+
3
+ This is part of implementation of [ruby-ethereum](https://github.com/cryptape/ruby-ethereum)
4
+ that related to calculation of ABI Solidity contract calls for the EVM.
5
+
6
+ ABI stands for application binary interface.
7
+
8
+ In general, an ABI is the interface between two program modules, one of which is often at the level of machine code.
9
+ The interface is the de facto method for encoding/decoding data into/out of the machine code.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'ethereum_abi'
17
+ ```
18
+
19
+ And then execute:
20
+
21
+ $ bundle install
22
+
23
+ Or install it yourself as:
24
+
25
+ $ gem install ethereum_abi
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/TemaMix/ethereum_abi. 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/TemaMix/ethereum_abi/blob/master/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 EthereumAbi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/TemaMix/ethereum_abi/blob/master/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]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "ethereum_abi"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,25 @@
1
+ # -*- encoding : ascii-8bit -*-
2
+ # frozen_string_literal: true
3
+
4
+ module EthereumAbi
5
+ module Constant
6
+ BYTE_EMPTY = ""
7
+ BYTE_ZERO = "\x00"
8
+ BYTE_ONE = "\x01"
9
+
10
+ TT32 = 2**32
11
+ TT256 = 2**256
12
+ TT64M1 = 2**64 - 1
13
+
14
+ UINT_MAX = 2**256 - 1
15
+ UINT_MIN = 0
16
+ INT_MAX = 2**255 - 1
17
+ INT_MIN = -2**255
18
+
19
+ HASH_ZERO = ("\x00" * 32).freeze
20
+
21
+ PUBKEY_ZERO = ("\x00" * 32).freeze
22
+ PRIVKEY_ZERO = ("\x00" * 32).freeze
23
+ PRIVKEY_ZERO_HEX = ("0" * 64).freeze
24
+ end
25
+ end
@@ -0,0 +1,115 @@
1
+ # -*- encoding : ascii-8bit -*-
2
+ # frozen_string_literal: true
3
+
4
+ module EthereumAbi
5
+ class Type
6
+ class ParseError < StandardError; end
7
+
8
+ class << self
9
+ ##
10
+ # Crazy regexp to seperate out base type component (eg. uint), size (eg.
11
+ # 256, 128x128, nil), array component (eg. [], [45], nil)
12
+ #
13
+ def parse(type)
14
+ _, base, sub, dimension = /([a-z]*)([0-9]*x?[0-9]*)((\[[0-9]*\])*)/.match(type).to_a
15
+
16
+ dims = dimension.scan(/\[[0-9]*\]/)
17
+ raise ParseError, "Unknown characters found in array declaration" if dims.join != dimension
18
+
19
+ case base
20
+ when "string"
21
+ raise ParseError, "String type must have no suffix or numerical suffix" unless sub.empty?
22
+ when "bytes"
23
+ raise ParseError, "Maximum 32 bytes for fixed-length string or bytes" unless sub.empty? || sub.to_i <= 32
24
+ when "uint", "int"
25
+ raise ParseError, "Integer type must have numerical suffix" unless sub =~ /\A[0-9]+\z/
26
+
27
+ size = sub.to_i
28
+ raise ParseError, "Integer size out of bounds" unless size >= 8 && size <= 256
29
+ raise ParseError, "Integer size must be multiple of 8" unless (size % 8).zero?
30
+ when "ureal", "real", "fixed", "ufixed"
31
+ unless sub =~ /\A[0-9]+x[0-9]+\z/
32
+ raise ParseError,
33
+ "Real type must have suffix of form <high>x<low>, e.g. 128x128"
34
+ end
35
+
36
+ high, low = sub.split("x").map(&:to_i)
37
+ total = high + low
38
+
39
+ raise ParseError, "Real size out of bounds (max 32 bytes)" unless total >= 8 && total <= 256
40
+ raise ParseError, "Real high/low sizes must be multiples of 8" unless (high % 8).zero? && (low % 8).zero?
41
+ when "hash"
42
+ raise ParseError, "Hash type must have numerical suffix" unless sub =~ /\A[0-9]+\z/
43
+ when "address"
44
+ raise ParseError, "Address cannot have suffix" unless sub.empty?
45
+ when "bool"
46
+ raise ParseError, "Bool cannot have suffix" unless sub.empty?
47
+ else
48
+ raise ParseError, "Unrecognized type base: #{base}"
49
+ end
50
+
51
+ new(base, sub, dims.map { |x| x[1...-1].to_i })
52
+ end
53
+
54
+ def size_type
55
+ @size_type ||= new("uint", 256, [])
56
+ end
57
+ end
58
+
59
+ attr :base, :sub, :dims
60
+
61
+ ##
62
+ # @param base [String] base name of type, e.g. uint for uint256[4]
63
+ # @param sub [String] subscript of type, e.g. 256 for uint256[4]
64
+ # @param dims [Array[Integer]] dimensions of array type, e.g. [1,2,0]
65
+ # for uint256[1][2][], [] for non-array type
66
+ #
67
+ def initialize(base, sub, dims)
68
+ @base = base
69
+ @sub = sub
70
+ @dims = dims
71
+ end
72
+
73
+ def ==(other)
74
+ base == other.base &&
75
+ sub == other.sub &&
76
+ dims == other.dims
77
+ end
78
+
79
+ ##
80
+ # Get the static size of a type, or nil if dynamic.
81
+ #
82
+ # @return [Integer, NilClass] size of static type, or nil for dynamic
83
+ # type
84
+ #
85
+ def size
86
+ @size ||= if dims.empty?
87
+ if %w[string bytes].include?(base) && sub.empty?
88
+ nil
89
+ else
90
+ 32
91
+ end
92
+ elsif dims.last.zero?
93
+ nil # 0 for dynamic array []
94
+ else
95
+ subtype.dynamic? ? nil : dims.last * subtype.size
96
+ end
97
+ end
98
+
99
+ def dynamic?
100
+ size.nil?
101
+ end
102
+
103
+ ##
104
+ # Type with one dimension lesser.
105
+ #
106
+ # @example
107
+ # Type.parse("uint256[2][]").subtype # => Type.new('uint', 256, [2])
108
+ #
109
+ # @return [EthereumAbi::Type]
110
+ #
111
+ def subtype
112
+ @subtype ||= self.class.new(base, sub, dims[0...-1])
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,75 @@
1
+ # -*- encoding : ascii-8bit -*-
2
+ # frozen_string_literal: true
3
+
4
+ require "./lib/ethereum_abi/constant"
5
+
6
+ module EthereumAbi
7
+ module Utils
8
+ extend self
9
+
10
+ include EthereumAbi::Constant
11
+
12
+ def ceil32(x)
13
+ (x % 32).zero? ? x : (x + 32 - x % 32)
14
+ end
15
+
16
+ def encode_hex(b)
17
+ ::RLP::Utils.encode_hex b
18
+ end
19
+
20
+ def decode_hex(s)
21
+ ::RLP::Utils.decode_hex s
22
+ end
23
+
24
+ def big_endian_to_int(s)
25
+ ::RLP::Sedes.big_endian_int.deserialize s.sub(/\A(\x00)+/, "")
26
+ end
27
+
28
+ def int_to_big_endian(n)
29
+ ::RLP::Sedes.big_endian_int.serialize n
30
+ end
31
+
32
+ def lpad(x, symbol, l)
33
+ return x if x.size >= l
34
+
35
+ symbol * (l - x.size) + x
36
+ end
37
+
38
+ def rpad(x, symbol, l)
39
+ return x if x.size >= l
40
+
41
+ x + symbol * (l - x.size)
42
+ end
43
+
44
+ def zpad(x, l)
45
+ lpad x, BYTE_ZERO, l
46
+ end
47
+
48
+ def zunpad(x)
49
+ x.sub(/\A\x00+/, "")
50
+ end
51
+
52
+ def zpad_int(n, l = 32)
53
+ zpad encode_int(n), l
54
+ end
55
+
56
+ def zpad_hex(s, l = 32)
57
+ zpad decode_hex(s), l
58
+ end
59
+
60
+ def encode_int(n)
61
+ raise ArgumentError, "Integer invalid or out of range: #{n}" unless n.is_a?(Integer) && n >= 0 && n <= UINT_MAX
62
+
63
+ int_to_big_endian n
64
+ end
65
+
66
+ def decode_int(v)
67
+ if v.size.positive? && (v[0] == Constant::BYTE_ZERO || v[0].zero?)
68
+ raise ArgumentError,
69
+ "No leading zero bytes allowed for integers"
70
+ end
71
+
72
+ big_endian_to_int v
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EthereumAbi
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,339 @@
1
+ # -*- encoding : ascii-8bit -*-
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require "rlp"
6
+
7
+ require_relative "ethereum_abi/version"
8
+ require_relative "ethereum_abi/utils"
9
+ require_relative "ethereum_abi/constant"
10
+ require_relative "ethereum_abi/type"
11
+
12
+ module EthereumAbi
13
+ class Error < StandardError; end
14
+ class ValueError < StandardError; end
15
+
16
+ extend self
17
+
18
+ include EthereumAbi::Constant
19
+
20
+ class EncodingError < StandardError; end
21
+ class DecodingError < StandardError; end
22
+ class ValueOutOfBounds < StandardError; end
23
+
24
+ ##
25
+ # Encodes multiple arguments using the head/tail mechanism.
26
+ #
27
+ def encode_abi(types, args)
28
+ parsed_types = types.map { |t| Type.parse(t) }
29
+
30
+ head_size = (0...args.size)
31
+ .map { |i| parsed_types[i].size || 32 }
32
+ .reduce(0, &:+)
33
+
34
+ head = ""
35
+ tail = ""
36
+ args.each_with_index do |arg, i|
37
+ if parsed_types[i].dynamic?
38
+ head += encode_type(Type.size_type, head_size + tail.size)
39
+ tail += encode_type(parsed_types[i], arg)
40
+ else
41
+ head += encode_type(parsed_types[i], arg)
42
+ end
43
+ end
44
+
45
+ "#{head}#{tail}"
46
+ end
47
+ alias encode encode_abi
48
+
49
+ ##
50
+ # Encodes a single value (static or dynamic).
51
+ #
52
+ # @param type [EthereumAbi::Type] value type
53
+ # @param arg [Object] value
54
+ #
55
+ # @return [String] encoded bytes
56
+ #
57
+ def encode_type(type, arg)
58
+ if %w[string bytes].include?(type.base) && type.sub.empty?
59
+ raise ArgumentError, "arg must be a string" unless arg.instance_of?(String)
60
+
61
+ size = encode_type Type.size_type, arg.size
62
+ padding = BYTE_ZERO * (Utils.ceil32(arg.size) - arg.size)
63
+
64
+ "#{size}#{arg}#{padding}"
65
+ elsif type.dynamic?
66
+ raise ArgumentError, "arg must be an array" unless arg.instance_of?(Array)
67
+
68
+ head = ""
69
+ tail = ""
70
+ if type.dims.last.zero?
71
+ head += encode_type(Type.size_type, arg.size)
72
+ else
73
+ unless arg.size == type.dims.last
74
+ raise ArgumentError,
75
+ "Wrong array size: found #{arg.size}, expecting #{type.dims.last}"
76
+ end
77
+ end
78
+
79
+ sub_type = type.subtype
80
+ sub_size = type.subtype.size
81
+ arg.size.times do |i|
82
+ if sub_size.nil?
83
+ head += encode_type(Type.size_type, 32 * arg.size + tail.size)
84
+ tail += encode_type(sub_type, arg[i])
85
+ else
86
+ head += encode_type(sub_type, arg[i])
87
+ end
88
+ end
89
+
90
+ "#{head}#{tail}"
91
+ elsif type.dims.empty? # static type
92
+ encode_primitive_type type, arg
93
+ else
94
+ arg.map { |x| encode_type(type.subtype, x) }.join
95
+ end
96
+ end
97
+
98
+ def encode_primitive_type(type, arg)
99
+ case type.base
100
+ when "uint"
101
+ real_size = type.sub.to_i
102
+ i = get_uint arg
103
+
104
+ raise ValueOutOfBounds, arg unless i >= 0 && i < 2**real_size
105
+
106
+ Utils.zpad_int i
107
+ when "bool"
108
+ raise ArgumentError, "arg is not bool: #{arg}" unless arg.instance_of?(TrueClass) || arg.instance_of?(FalseClass)
109
+
110
+ Utils.zpad_int(arg ? 1 : 0)
111
+ when "int"
112
+ real_size = type.sub.to_i
113
+ i = get_int arg
114
+
115
+ raise ValueOutOfBounds, arg unless i >= -2**(real_size - 1) && i < 2**(real_size - 1)
116
+
117
+ Utils.zpad_int(i % 2**type.sub.to_i)
118
+ when "ureal", "ufixed"
119
+ high, low = type.sub.split("x").map(&:to_i)
120
+
121
+ raise ValueOutOfBounds, arg unless arg >= 0 && arg < 2**high
122
+
123
+ Utils.zpad_int((arg * 2**low).to_i)
124
+ when "real", "fixed"
125
+ high, low = type.sub.split("x").map(&:to_i)
126
+
127
+ raise ValueOutOfBounds, arg unless arg >= -2**(high - 1) && arg < 2**(high - 1)
128
+
129
+ i = (arg * 2**low).to_i
130
+ Utils.zpad_int(i % 2**(high + low))
131
+ when "string", "bytes"
132
+ raise EncodingError, "Expecting string: #{arg}" unless arg.instance_of?(String)
133
+
134
+ if type.sub.empty? # variable length type
135
+ size = Utils.zpad_int arg.size
136
+ padding = BYTE_ZERO * (Utils.ceil32(arg.size) - arg.size)
137
+ "#{size}#{arg}#{padding}"
138
+ else # fixed length type
139
+ raise ValueOutOfBounds, arg unless arg.size <= type.sub.to_i
140
+
141
+ padding = BYTE_ZERO * (32 - arg.size)
142
+ "#{arg}#{padding}"
143
+ end
144
+ when "hash"
145
+ size = type.sub.to_i
146
+ raise EncodingError, "too long: #{arg}" unless size.positive? && size <= 32
147
+
148
+ if arg.is_a?(Integer)
149
+ Utils.zpad_int(arg)
150
+ elsif arg.size == size
151
+ Utils.zpad arg, 32
152
+ elsif arg.size == size * 2
153
+ Utils.zpad_hex arg
154
+ else
155
+ raise EncodingError, "Could not parse hash: #{arg}"
156
+ end
157
+ when "address"
158
+ if arg.is_a?(Integer)
159
+ Utils.zpad_int arg
160
+ elsif arg.size == 20
161
+ Utils.zpad arg, 32
162
+ elsif arg.size == 40
163
+ Utils.zpad_hex arg
164
+ elsif arg.size == 42 && arg[0, 2] == "0x"
165
+ Utils.zpad_hex arg[2..-1]
166
+ else
167
+ raise EncodingError, "Could not parse address: #{arg}"
168
+ end
169
+ else
170
+ raise EncodingError, "Unhandled type: #{type.base} #{type.sub}"
171
+ end
172
+ end
173
+
174
+ ##
175
+ # Decodes multiple arguments using the head/tail mechanism.
176
+ #
177
+ def decode_abi(types, data)
178
+ parsed_types = types.map { |t| Type.parse(t) }
179
+
180
+ outputs = [nil] * types.size
181
+ start_positions = [nil] * types.size + [data.size]
182
+
183
+ pos = 0
184
+ parsed_types.each_with_index do |t, i|
185
+ # If a type is static, grab the data directly, otherwise record its
186
+ # start position
187
+ if t.dynamic?
188
+ start_positions[i] = Utils.big_endian_to_int(data[pos, 32])
189
+
190
+ j = i - 1
191
+ while j >= 0 && start_positions[j].nil?
192
+ start_positions[j] = start_positions[i]
193
+ j -= 1
194
+ end
195
+
196
+ pos += 32
197
+ else
198
+ outputs[i] = data[pos, t.size]
199
+ pos += t.size
200
+ end
201
+ end
202
+
203
+ # We add a start position equal to the length of the entire data for
204
+ # convenience.
205
+ j = types.size - 1
206
+ while j >= 0 && start_positions[j].nil?
207
+ start_positions[j] = start_positions[types.size]
208
+ j -= 1
209
+ end
210
+
211
+ raise DecodingError, "Not enough data for head" unless pos <= data.size
212
+
213
+ parsed_types.each_with_index do |t, i|
214
+ if t.dynamic?
215
+ offset, next_offset = start_positions[i, 2]
216
+ outputs[i] = data[offset...next_offset]
217
+ end
218
+ end
219
+
220
+ parsed_types.zip(outputs).map { |(type, out)| decode_type(type, out) }
221
+ end
222
+ alias decode decode_abi
223
+
224
+ def decode_type(type, arg)
225
+ if %w[string bytes].include?(type.base) && type.sub.empty?
226
+ l = Utils.big_endian_to_int arg[0, 32]
227
+ data = arg[32..-1]
228
+
229
+ raise DecodingError, "Wrong data size for string/bytes object" unless data.size == Utils.ceil32(l)
230
+
231
+ data[0, l]
232
+ elsif type.dynamic?
233
+ l = Utils.big_endian_to_int arg[0, 32]
234
+ subtype = type.subtype
235
+
236
+ if subtype.dynamic?
237
+ raise DecodingError, "Not enough data for head" unless arg.size >= 32 + 32 * l
238
+
239
+ start_positions = (1..l).map { |i| Utils.big_endian_to_int arg[32 * i, 32] }
240
+ start_positions.push arg.size
241
+
242
+ outputs = (0...l).map { |i| arg[start_positions[i]...start_positions[i + 1]] }
243
+
244
+ outputs.map { |out| decode_type(subtype, out) }
245
+ else
246
+ (0...l).map { |i| decode_type(subtype, arg[32 + subtype.size * i, subtype.size]) }
247
+ end
248
+ elsif !type.dims.empty? # static-sized arrays
249
+ l = type.dims.last[0]
250
+ subtype = type.subtype
251
+
252
+ (0...l).map { |i| decode_type(subtype, arg[subtype.size * i, subtype.size]) }
253
+ else
254
+ decode_primitive_type type, arg
255
+ end
256
+ end
257
+
258
+ def decode_primitive_type(type, data)
259
+ case type.base
260
+ when "address"
261
+ Utils.encode_hex data[12..-1]
262
+ when "string", "bytes"
263
+ if type.sub.empty? # dynamic
264
+ size = Utils.big_endian_to_int data[0, 32]
265
+ data[32..-1][0, size]
266
+ else # fixed
267
+ data[0, type.sub.to_i]
268
+ end
269
+ when "hash"
270
+ data[(32 - type.sub.to_i), type.sub.to_i]
271
+ when "uint"
272
+ Utils.big_endian_to_int data
273
+ when "int"
274
+ u = Utils.big_endian_to_int data
275
+ u >= 2**(type.sub.to_i - 1) ? (u - 2**type.sub.to_i) : u
276
+ when "ureal", "ufixed"
277
+ _high, low = type.sub.split("x").map(&:to_i)
278
+ Utils.big_endian_to_int(data) * 1.0 / 2**low
279
+ when "real", "fixed"
280
+ high, low = type.sub.split("x").map(&:to_i)
281
+ u = Utils.big_endian_to_int data
282
+ i = u >= 2**(high + low - 1) ? (u - 2**(high + low)) : u
283
+ i * 1.0 / 2**low
284
+ when "bool"
285
+ data[-1] == BYTE_ONE
286
+ else
287
+ raise DecodingError, "Unknown primitive type: #{type.base}"
288
+ end
289
+ end
290
+
291
+ private
292
+
293
+ def get_uint(n)
294
+ case n
295
+ when Integer
296
+ raise EncodingError, "Number out of range: #{n}" if n > UINT_MAX || n < UINT_MIN
297
+
298
+ n
299
+ when String
300
+ if n.size == 40
301
+ Utils.big_endian_to_int Utils.decode_hex(n)
302
+ elsif n.size <= 32
303
+ Utils.big_endian_to_int n
304
+ else
305
+ raise EncodingError, "String too long: #{n}"
306
+ end
307
+ when true
308
+ 1
309
+ when false, nil
310
+ 0
311
+ else
312
+ raise EncodingError, "Cannot decode uint: #{n}"
313
+ end
314
+ end
315
+
316
+ def get_int(n)
317
+ case n
318
+ when Integer
319
+ raise EncodingError, "Number out of range: #{n}" if n > INT_MAX || n < INT_MIN
320
+
321
+ n
322
+ when String
323
+ if n.size == 40
324
+ i = Utils.big_endian_to_int Utils.decode_hex(n)
325
+ elsif n.size <= 32
326
+ i = Utils.big_endian_to_int n
327
+ else
328
+ raise EncodingError, "String too long: #{n}"
329
+ end
330
+ i > INT_MAX ? (i - TT256) : i
331
+ when true
332
+ 1
333
+ when false, nil
334
+ 0
335
+ else
336
+ raise EncodingError, "Cannot decode int: #{n}"
337
+ end
338
+ end
339
+ end
@@ -0,0 +1,4 @@
1
+ module EthereumAbi
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ethereum_abi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Artem Rumiantcev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-09-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rlp
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.7.3
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.7.3
27
+ description: This gem is based on outdated implementation ruby-ethereum.
28
+ email:
29
+ - tema.place@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - bin/console
44
+ - bin/setup
45
+ - lib/ethereum_abi.rb
46
+ - lib/ethereum_abi/constant.rb
47
+ - lib/ethereum_abi/type.rb
48
+ - lib/ethereum_abi/utils.rb
49
+ - lib/ethereum_abi/version.rb
50
+ - sig/ethereum_abi.rbs
51
+ homepage: https://github.com/TemaMix/ethereum_abi
52
+ licenses:
53
+ - MIT
54
+ metadata:
55
+ homepage_uri: https://github.com/TemaMix/ethereum_abi
56
+ source_code_uri: https://github.com/TemaMix/ethereum_abi
57
+ changelog_uri: https://github.com/TemaMix/ethereum_abi
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 2.6.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.0.9
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: A ruby implementation of ABI encoder/decoder for ethereum network.
77
+ test_files: []