Add 'staging/algorand/' from commit '6ed163b8bdc40d18acf55deccf9805e51241626f'

Pulls in the algorand repo using git-subtree, allowing us
to later merge in changes from their upstream repo.

Import of the subtree:

    git subtree add --prefix staging/algorand git@github.com:randlabs/PricecasterService.git dev-wormhole
    git commit --amend --allow-empty  # add Change-Id footer

Push everything minus the merge commit to a temporary branch,
then make a Gerrit review for this one:

    git push gerrit 6ed163b8bdc40d18acf55deccf9805e51241626f:refs/heads/pricecaster
    git push gerrit HEAD:refs/for/dev.v2%r=josh

Temporary Gerrit ACL for the pricecaster branch to bypass review:

+[access "refs/heads/pricecaster"]
+	push = +force group user/Leopold Schabel (leo)

git-subtree-dir: staging/algorand
git-subtree-mainline: cb9c65b421
git-subtree-split: 6ed163b8bd
Change-Id: Ib2085a4a2b4a9dbf4ca55aa0b43452f8ccb12e8a
This commit is contained in:
Leo 2021-12-01 13:12:17 +01:00
commit 149a506c73
54 changed files with 15863 additions and 0 deletions

View File

@ -0,0 +1,20 @@
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
mocha: true
},
extends: [
'standard'
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12
},
plugins: [
'@typescript-eslint'
],
rules: {
}
}

109
staging/algorand/.gitignore vendored Normal file
View File

@ -0,0 +1,109 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
build/*
teal/wormhole/pyteal/__pycache__/*
teal/wormhole/build/*
test/temp/*.teal

661
staging/algorand/LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

236
staging/algorand/README.md Normal file
View File

@ -0,0 +1,236 @@
# Pricecaster Service
## Introduction
This service consumes prices from "price fetchers" and feeds blockchain publishers. There are two basic flows implemented:
* A basic Algorand publisher class with a TEAL program for messages containing signed price data. The program code validates signature and message validity, and if successful, subsequently stores the price information in the global application information for other contracts to retrieve. For the description of the data format used, see below.
* A Wormhole client that uses the JS SDK to get VAAs from Pyth network and feed the payload and cryptographic verification data to a transaction group for validation. Subsequently, the data is optionally processed and stored, either price or metrics. For details regarding Wormhole VAAs see design documents:
https://github.com/certusone/wormhole/tree/dev.v2/design
All gathered price information is stored in a buffer by the Fetcher component -with a maximum size determined by settings-. The price to get from that buffer is selected by the **IStrategy** class implementation; the default implementation being to get the most recent price and clear the buffer for new items to arrive.
Alternative strategies for different purposes, such as getting averages and forecasting, can be implemented easily.
## System Overview
**The objective is to receive signed messages -named as Verifiable Attestments (VAAs) in Wormhole jargon- from our relayer backend (Pricecaster) , verify them against a fixed (and upgradeable) set of "guardian public keys" and process them, publishing on-chain price information or doing governance chores depending on the VAA payload.**
The design is based in two contracts that work in tandem, a **Stateful contract (VAA_Processor)** that accepts calls for verifying and commiting VAAs, and also mantains the global guardian set; and a **verifier stateless contract** that does the computational work of ECDSA signature verification.
Due to computation and space limits, the validation of the 19 guardian signatures against the payload is partitioned so each stateless contract validates a subset of the guardian signatures. If ECDSA decompress and validation opcodes are used, that yields 650+1750 = 2400 computation units * 7 = 16800, leaving 3200 free units for remaining opcodes.
In our design, We call **verification step** to each of the app calls + stateless logic involved in verifying a block of signatures.
The number of signatures in each verification step is fixed at contract compilation stage, so with this in mind and example values:
* let $N_S$ be the total signatures to verify $(19)$
* let $N_V$ be the number of signatures per verification step $(7)$,
* the required number of transactions $N_T = \lceil{N_S/N_V}\rceil = \lceil{19/7}\rceil = 3$
* Each transaction-step $T_i$ will verify signatures $[j..k]$ where $j = i \times N_V$, $k = min(N_S-1, j+N_V-1)$, so for $T_0 = [0..6]$, $T_1 = [7..13]$, $T_2 = [14..18]$.
The verification process inputs consist of:
1. the set of current guardian public keys,
2. the signed message digest (VAA information fields + generic payload),
3. the set of signatures in the VAA header.
With the above in mind, and considering the space and computation limits in the current Algorand protocol, the typical flow for verifying a VAA for 19 guardians using step-size of 7, would be based on the following transaction group:
| TX# | App calls | Stateless logic |
| --- | --------- | --------------- |
| 0 | _args_: guardian_pk[0..6], _txnote_: signed_digest | _args_: sig[0..6] |
| 1 | _args_: guardian_pk[7..13], _txnote_: signed_digest | _args_: sig[7..13] |
| 2 | _args_: guardian_pk[14..18], _txnote_: signed_digest | _args_: sig[14..18] |
Regarding stateless logic we can say that,
* Its code is constant and it's known program hash is validated by the stateful program.
* Asserts that the appropiate stateful program is called using known AppId embedded at compile stage.
* Passing signature subset through arguments does not pose any higher risk since any tampered signature will make the operation to fail;
* The signed digest and public keys are retrieved through transaction note field and argument. This limits for the current design the maximum digest size to 1000 bytes and the maximum number of public keys -and guardians to ~64.
* Verification is performed using TEAL5 ECDSA opcodes. If any signature do not verify, transaction fails and subsequently, the entire transaction group aborts.
For the stateful app-calls we consider,
* Global state stores guardian public-keys, entry count (set size) and guardian set expiration time.
* Initial state after deployment could be set through a bootstrap call, using last guardian-set-change governance VAA if available.
* Sender must be stateless logic
* Argument 1 must contain guardian public keys for guardians $[k..j]$
* Argument 2 must contain current guardian size set
* Note field must contain signed digest.
* Passed guardian keys $[k..j]$ must match the current global state.
* Passed guardian size set must match the current global state.
* Last TX in group triggers VAA processing according to fields (e.g: do governance chores, unpack Pyth price ticker, etc)
**VAA Structure**
VAA structure is defined in:
https://github.com/certusone/wormhole/blob/dev.v2/design/0001_generic_message_passing.md
Governance VAAs:
https://github.com/certusone/wormhole/blob/dev.v2/design/0002_governance_messaging.md
Sample Ethereum Struct Reference:
https://github.com/certusone/wormhole/blob/dev.v2/ethereum/contracts/Structs.sol
```
VAA
i Bytes Field
0 1 Version
1 4 GuardianSetIndex
5 1 LenSignatures (LN)
6 66*LN Signatures where each S = { guardianIndex (1),r(32),s(32),v(1) }
-------------------------------------< hashed/signed body starts here.
4 timestamp
4 Nonce
2 emitterChainId
32 emitterAddress
8 sequence
1 consistencyLevel
N payload
--------------------------------------< hashed/signed body ends here.
```
**VAA Commitment**
Each VAA is uniquely identified by tuple (emitter_chain_id, emitter_address, sequence). We are currently interested in VAAs for:
* Governance operations:
* Upgrade guardian set
* Upgrade contract [this is necessary for non-publishers?]
* Pyth Ticker Data
After all signatures are verified the stateful app will execute the code to handle the VAA according to the tuple fields.
## System Overview (proof-of-concept work)
:warning: You can consider this a first proof-of-concept design, and in terms of our current approach, an obsolete technique.
This flow uses a validator to sign the messages when they arrive. This trusts the price feed, so this is not recommended for production purposes. It may be used as a base design for other data flows. **See the Wormhole Flow below for the verified, cryptographically safe and trustless approach**.
The Pricecaster backend can be configured with any class implementing **IPriceFetcher** and **IPublisher** interfaces. The following diagram shows the service operating with a fetcher from ![Pyth Network](https://pyth.network/), feeding the Algorand chain through the `StdAlgoPublisher` class.
![PRICECASTER](https://user-images.githubusercontent.com/4740613/136037362-bed34a49-6b83-42e1-821d-1df3d9a41477.png)
### Input Message Format
The TEAL contract expects a fixed-length message consisting of:
```
Field size
9 header Literal "PRICEDATA"
1 version int8 (Must be 1)
8 dest This appId
16 symbol String padded with spaces e.g ("ALGO/USD ")
8 price Price. 64bit integer.
8 priceexp Price exponent. Interpret as two-compliment, Big-Endian 64bit
8 conf Confidence (stdev). 64bit integer.
8 slot Valid-slot of this aggregate price.
8 ts timestamp of this price submitted by PriceFetcher service
32 s Signature s-component
32 r Signature r-component
Size: 138 bytes.
```
### Global state
The global state that is mantained by the contract consists of the following fields:
```
sym : byte[] Symbol to keep price for
vaddr : byte[] Validator account
price : uint64 current price
stdev : uint64 current confidence (standard deviation)
slot : uint64 slot of this onchain publication
exp : byte[] exponent. Interpret as two-compliment, Big-Endian 64bit
ts : uint64 last timestamp
```
#### Price parsing
The exponent is stored as a byte array containing a signed, two-complement 64-bit Big-Endian integer, as some networks like Pyth publish negative values here. For example, to parse the byte array from JS:
```
const stExp = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'exp')
const bufExp = Buffer.from(stExp, 'base64')
const val = bufExp.readBigInt64BE()
```
## Installation
Prepare all Node packages with:
```
npm install
```
## Deployment of Applications
Use the deployment tools in `tools` subdirectory.
* To deploy the proof-of-concept "Pricekeeper" system, use the `deploy` tool with proper arguments, and later point the settings file to the deployed Appid.
* To deploy the VAA processor to use with Wormhole, make sure you have Python environment running (preferably >=3.7.0), and `pyteal` installed with `pip3`.
For example, using `deploy-wh` with sample output:
```
node tools\deploy-wh.js tools\v1.prototxt.testnet 1000 OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU testnet
VAA Processor for Wormhole Deployment Tool -- (c)2021-22 Randlabs, Inc.
-----------------------------------------------------------------------
Parameters for deployment:
From: OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU
Network: testnet
Guardian expiration time: 1000
Guardian Keys: (19) 13947Bd48b18E53fdAeEe77F3473391aC727C638,F18AbBac073741DD0F002147B735Ff642f3D113F,9925A94DC043D0803f8ef502D2dB15cAc9e02D76,9e4EC2D92af8602bCE74a27F99A836f93C4a31E4,9C40c4052A3092AfB8C99B985fcDfB586Ed19c98,B86020cF1262AA4dd5572Af76923E271169a2CA7,1937617fE1eD801fBa14Bd8BB9EDEcBA7A942FFe,9475b8D45DdE53614d92c779787C27fE2ef68752,15A53B22c28AbC7B108612146B6aAa4a537bA305,63842657C7aC7e37B04FBE76b8c54EFe014D04E1,948ca1bBF4B858DF1A505b4C69c5c61bD95A12Bd,A6923e2259F8B5541eD18e410b8DdEE618337ff0,F678Daf4b7f2789AA88A081618Aa966D6a39e064,8cF31021838A8B3fFA43a71a50609877846f9E6d,eB15bCF2ae4f957012330B4741ecE3242De96184,cc3766a03e4faec44Bda7a46D9Ea2A9D124e9Bf8,841f499Ba89a6a8E9dD273BAd82Beb175094E5d7,f5F2b82576e6CA17965dee853d08bbB471FA2433,2bC2B1204599D4cA0d4Dde4a658a42c4dD13103a
Enter YES to confirm parameters, anything else to abort. YES
Enter mnemonic for sender account.
BE SURE TO DO THIS FROM A SECURED SYSTEM
.
.
.
Compiling VAA Processor program code...
,VAA Processor Program, (c) 2021-22 Randlabs Inc.
Compiling approval program...
Written to teal/wormhole/build/vaa-processor-approval.teal
Compiling clear state program...
Written to teal/wormhole/build/vaa-processor-clear.teal
,
Creating new app...
txId: DX7YIQ6L5QELSNZHJGKSZ4MQA7U26KJCPUJ42UFEGU22MJWDLY5Q
Deployment App Id: 43816461
Bye.
```
## Backend Configuration
The backend will read configuration from a `settings.ts` file pointed by the `PRICECASTER_SETTINGS` environment variable.
## Running the system
Check the `package.json` file for `npm run tart-xxx` automated commands.
## Tests
Tests can be run for the old `Pricekeeper` contract, and for the new set of Wormhole client contracts:
`npm run pkeeper-sc-test`
`npm run wormhole-sc-test`
Backend tests will come shortly.

View File

@ -0,0 +1,59 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
/**
* A generic Price ticker information class
*/
export class PriceTicker {
constructor (price: BigInt, confidence: BigInt, exponent: number, networkTime: BigInt) {
this._price = price
this._confidence = confidence
this._exponent = exponent
this._networkTime = networkTime
}
/** price */
private _price: BigInt;
public get price (): BigInt {
return this._price
}
public set price (value: BigInt) {
this._price = value
}
/** a confidence interval */
private _confidence: BigInt;
public get confidence (): BigInt {
return this._confidence
}
public set confidence (value: BigInt) {
this._confidence = value
}
/** exponent (fixed point) */
private _exponent: number;
public get exponent (): number {
return this._exponent
}
public set exponent (value: number) {
this._exponent = value
}
/** time in blockchain network units */
private _networkTime: BigInt;
public get networkTime (): BigInt {
return this._networkTime
}
public set networkTime (value: BigInt) {
this._networkTime = value
}
}

View File

@ -0,0 +1,28 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
export interface IAppSettings extends Record<string, unknown> {
mode: string,
algo: {
token: string,
api: string,
port: string,
},
pyth?: {
solanaClusterName?: string
},
params: {
verbose?: boolean,
symbol: string,
bufferSize: number,
publishIntervalSecs: number,
priceKeeperAppId: BigInt,
validator: string,
mnemo?: string
}
}

View File

@ -0,0 +1,13 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
export function sleep (ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}

View File

@ -0,0 +1,21 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
/* eslint-disable no-unused-vars */
export enum StatusCode {
OK,
NO_TICKER,
ERROR_CREATE_MESSAGE,
ERROR_SUBMIT_MESSAGE,
GENERAL_ERROR
}
// export const StatusToString = {
// StatusCode.OK: 'Operation successful'
// }

View File

@ -0,0 +1,11 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
export interface IEngine {
start(): Promise<void>
}

View File

@ -0,0 +1,101 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { IEngine } from './IEngine'
import { PythPriceFetcher } from '../fetcher/PythPriceFetcher'
import { StdAlgoPublisher } from '../publisher/stdAlgoPublisher'
import { StrategyLastPrice } from '../strategy/strategyLastPrice'
import { IAppSettings } from '../common/settings'
import { IPriceFetcher } from '../fetcher/IPriceFetcher'
import { IPublisher, PublishInfo } from '../publisher/IPublisher'
import { PriceTicker } from '../common/priceTicker'
import { StatusCode } from '../common/statusCodes'
import { sleep } from '../common/sleep'
const algosdk = require('algosdk')
const charm = require('charm')()
type WorkerRoutineStatus = {
status: StatusCode,
reason?: string,
tick?: PriceTicker,
pub?: PublishInfo
}
async function workerRoutine (fetcher: IPriceFetcher, publisher: IPublisher): Promise<WorkerRoutineStatus> {
const tick = fetcher.queryTicker()
if (tick === undefined) {
return { status: StatusCode.NO_TICKER }
}
const pub = await publisher.publish(tick)
return { status: pub.status, reason: pub.reason, tick, pub }
}
export class PriceKeeperEngine implements IEngine {
private settings: IAppSettings
constructor (settings: IAppSettings) {
this.settings = settings
}
async start () {
charm.write('Setting up for')
.foreground('yellow')
.write(` ${this.settings.params.symbol} `)
.foreground('white')
.write('for PriceKeeper App')
.foreground('yellow')
.write(` ${this.settings.params.priceKeeperAppId} `)
.foreground('white')
.write(`interval ${this.settings.params.publishIntervalSecs} secs\n`)
const publisher = new StdAlgoPublisher(this.settings.params.symbol,
this.settings.params.priceKeeperAppId,
this.settings.params.validator,
(algosdk.mnemonicToSecretKey(this.settings.params.mnemo)).sk,
this.settings.algo.token,
this.settings.algo.api,
this.settings.algo.port
)
const fetcher = new PythPriceFetcher(this.settings.params.symbol,
new StrategyLastPrice(this.settings.params.bufferSize), this.settings.pyth?.solanaClusterName!)
await fetcher.start()
console.log('Waiting for fetcher to boot...')
while (!fetcher.hasData()) {
await sleep(250)
}
console.log('Waiting for publisher to boot...')
await publisher.start()
console.log('Starting worker.')
let active = true
charm.removeAllListeners('^C')
charm.on('^C', () => {
console.log('CTRL+C: Aborted by user.')
active = false
})
let pubCount = 0
// eslint-disable-next-line no-unmodified-loop-condition
while (active) {
const wrs = await workerRoutine(fetcher, publisher)
switch (wrs.status) {
case StatusCode.OK: {
console.log(`[PUB ${pubCount++}] ${wrs.tick!.price}±${wrs.tick!.confidence} exp:${wrs.tick!.exponent} t:${wrs.tick!.networkTime} TXID:${wrs.pub!.txid}`)
break
}
case StatusCode.NO_TICKER:
console.log('No ticker available from fetcher data source')
break
default:
console.log('Error. Reason: ' + wrs.reason)
}
await sleep(this.settings.params.publishIntervalSecs * 1000)
}
}
}

View File

@ -0,0 +1,103 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { IEngine } from './IEngine'
import { PythPriceFetcher } from '../fetcher/PythPriceFetcher'
import { StdAlgoPublisher } from '../publisher/stdAlgoPublisher'
import { StrategyLastPrice } from '../strategy/strategyLastPrice'
import { IAppSettings } from '../common/settings'
import { IPriceFetcher } from '../fetcher/IPriceFetcher'
import { IPublisher, PublishInfo } from '../publisher/IPublisher'
import { PriceTicker } from '../common/priceTicker'
import { StatusCode } from '../common/statusCodes'
import { sleep } from '../common/sleep'
import { WormholePythPriceFetcher } from 'backend/fetcher/WormholePythPriceFetcher'
const algosdk = require('algosdk')
const charm = require('charm')()
type WorkerRoutineStatus = {
status: StatusCode,
reason?: string,
tick?: PriceTicker,
pub?: PublishInfo
}
async function workerRoutine (fetcher: IPriceFetcher, publisher: IPublisher): Promise<WorkerRoutineStatus> {
const tick = fetcher.queryTicker()
if (tick === undefined) {
return { status: StatusCode.NO_TICKER }
}
const pub = await publisher.publish(tick)
return { status: pub.status, reason: pub.reason, tick, pub }
}
export class WormholeClientEngine implements IEngine {
private settings: IAppSettings
constructor (settings: IAppSettings) {
this.settings = settings
}
async start () {
charm.write('Setting up for')
.foreground('yellow')
.write(` ${this.settings.params.symbol} `)
.foreground('white')
.write('for PriceKeeper App')
.foreground('yellow')
.write(` ${this.settings.params.priceKeeperAppId} `)
.foreground('white')
.write(`interval ${this.settings.params.publishIntervalSecs} secs\n`)
const publisher = new StdAlgoPublisher(this.settings.params.symbol,
this.settings.params.priceKeeperAppId,
this.settings.params.validator,
(algosdk.mnemonicToSecretKey(this.settings.params.mnemo)).sk,
this.settings.algo.token,
this.settings.algo.api,
this.settings.algo.port
)
const fetcher = new WormholePythPriceFetcher(this.settings.params.symbol,
new StrategyLastPrice(this.settings.params.bufferSize), this.settings.pyth?.solanaClusterName!)
await fetcher.start()
console.log('Waiting for fetcher to boot...')
while (!fetcher.hasData()) {
await sleep(250)
}
console.log('Waiting for publisher to boot...')
await publisher.start()
console.log('Starting worker.')
let active = true
charm.removeAllListeners('^C')
charm.on('^C', () => {
console.log('CTRL+C: Aborted by user.')
active = false
})
let pubCount = 0
// eslint-disable-next-line no-unmodified-loop-condition
while (active) {
const wrs = await workerRoutine(fetcher, publisher)
switch (wrs.status) {
case StatusCode.OK: {
console.log(`[PUB ${pubCount++}] ${wrs.tick!.price}±${wrs.tick!.confidence} exp:${wrs.tick!.exponent} t:${wrs.tick!.networkTime} TXID:${wrs.pub!.txid}`)
break
}
case StatusCode.NO_TICKER:
console.log('No ticker available from fetcher data source')
break
default:
console.log('Error. Reason: ' + wrs.reason)
}
await sleep(this.settings.params.publishIntervalSecs * 1000)
}
}
}

View File

@ -0,0 +1,27 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { PriceTicker } from '../common/priceTicker'
import { IStrategy } from '../strategy/strategy'
export interface IPriceFetcher {
start(): void
stop(): void
hasData(): boolean
/**
* Set price aggregation strategy for this fetcher.
* @param IStrategy The local price aggregation strategy
*/
setStrategy(s: IStrategy): void
/**
* Get the current price, according to running strategy.
*/
queryTicker(): PriceTicker | undefined
}

View File

@ -0,0 +1,59 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { IPriceFetcher } from './IPriceFetcher'
import { IStrategy } from '../strategy/strategy'
import { getPythProgramKeyForCluster, PriceData, Product, PythConnection } from '@pythnetwork/client'
import { Cluster, clusterApiUrl, Connection } from '@solana/web3.js'
import { PriceTicker } from '../common/priceTicker'
export class PythPriceFetcher implements IPriceFetcher {
private strategy: IStrategy
private symbol: string
private pythConnection: PythConnection
constructor (symbol: string, strategy: IStrategy, solanaClusterName: string) {
const SOLANA_CLUSTER_NAME: Cluster = solanaClusterName as Cluster
const connection = new Connection(clusterApiUrl(SOLANA_CLUSTER_NAME))
const pythPublicKey = getPythProgramKeyForCluster(SOLANA_CLUSTER_NAME)
this.pythConnection = new PythConnection(connection, pythPublicKey)
this.strategy = strategy
this.symbol = symbol
}
async start () {
await this.pythConnection.start()
this.pythConnection.onPriceChange((product: Product, price: PriceData) => {
if (product.symbol === this.symbol) {
this.onPriceChange(price)
}
})
}
stop (): void {
this.pythConnection.stop()
}
setStrategy (s: IStrategy) {
this.strategy = s
}
hasData (): boolean {
return this.strategy.bufferCount() > 0
}
queryTicker (): PriceTicker | undefined {
return this.strategy.getPrice()
}
private onPriceChange (price: PriceData) {
const pt: PriceTicker = new PriceTicker(price.priceComponent,
price.confidenceComponent, price.exponent, price.publishSlot)
this.strategy.put(pt)
}
}

View File

@ -0,0 +1,66 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { IPriceFetcher } from './IPriceFetcher'
import { IStrategy } from '../strategy/strategy'
import { getPythProgramKeyForCluster, PriceData, Product, PythConnection } from '@pythnetwork/client'
import { Cluster, clusterApiUrl, Connection } from '@solana/web3.js'
import { PriceTicker } from '../common/priceTicker'
import { getEmitterAddressEth, getSignedVAA } from '@certusone/wormhole-sdk'
export class WormholePythPriceFetcher implements IPriceFetcher {
private strategy: IStrategy
private symbol: string
private pythConnection: PythConnection
constructor (symbol: string, strategy: IStrategy, solanaClusterName: string) {
const SOLANA_CLUSTER_NAME: Cluster = solanaClusterName as Cluster
const connection = new Connection(clusterApiUrl(SOLANA_CLUSTER_NAME))
const pythPublicKey = getPythProgramKeyForCluster(SOLANA_CLUSTER_NAME)
this.pythConnection = new PythConnection(connection, pythPublicKey)
this.strategy = strategy
this.symbol = symbol
}
async start () {
await this.pythConnection.start()
this.pythConnection.onPriceChange((product: Product, price: PriceData) => {
if (product.symbol === this.symbol) {
this.onPriceChange(price)
}
})
}
stop (): void {
this.pythConnection.stop()
}
setStrategy (s: IStrategy) {
this.strategy = s
}
hasData (): boolean {
return this.strategy.bufferCount() > 0
}
queryTicker (): PriceTicker | undefined {
getEmitterAddressEth()
await getSignedVAA("https://wormhole-v2-testnet-api.certus.one", )
//return this.strategy.getPrice()
}
private onPriceChange (price: PriceData) {
GrpcWebImpl
PublicRPCServiceClientImpl
getSignedVAA()
const pt: PriceTicker = new PriceTicker(price.priceComponent,
price.confidenceComponent, price.exponent, price.publishSlot)
this.strategy.put(pt)
}
}

View File

@ -0,0 +1,49 @@
/* eslint-disable no-unused-vars */
/**
* Pricecaster Service.
*
* Main program file.
*
* (c) 2021 Randlabs, Inc.
*/
import * as Config from '@randlabs/js-config-reader'
import { IAppSettings } from './common/settings'
import { exit } from 'process'
import { PriceKeeperEngine } from './engine/PriceKeeperEngine'
import { WormholeClientEngine } from './engine/WormholeEngine'
const charm = require('charm')();
(async () => {
charm.pipe(process.stdout)
charm.reset()
charm.foreground('cyan').display('bright')
console.log('Pricecaster Service Backend -- (c) 2021 Randlabs, Inc.\n')
charm.foreground('white')
let settings: IAppSettings
try {
await Config.initialize<IAppSettings>({ envVar: 'PRICECASTER_SETTINGS' })
settings = Config.get<IAppSettings>()
} catch (e: any) {
console.error('Cannot initialize configuration: ' + e.toString())
exit(1)
}
let engine
switch (settings.mode) {
case 'pkeeper':
engine = new PriceKeeperEngine(settings)
break
case 'wormhole-client':
engine = new WormholeClientEngine(settings)
break
default:
console.error('Invalid specified mode in settings')
exit(2)
}
engine.start()
})()

View File

@ -0,0 +1,25 @@
/* eslint-disable no-unused-vars */
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { PriceTicker } from '../common/priceTicker'
import { StatusCode } from '../common/statusCodes'
export type PublishInfo = {
status: StatusCode,
reason?: '',
msgb64?: '',
block?: BigInt
txid?: string
}
export interface IPublisher {
start(): void
stop(): void
publish(tick: PriceTicker): Promise<PublishInfo>
}

View File

@ -0,0 +1,70 @@
import algosdk from 'algosdk'
import { IPublisher, PublishInfo } from '../publisher/IPublisher'
import { PriceTicker } from '../common/priceTicker'
import { StatusCode } from '../common/statusCodes'
const PricecasterLib = require('../../lib/pricecaster')
export class StdAlgoPublisher implements IPublisher {
private pclib: any
private symbol: string
private signKey: Uint8Array
private validator: string
constructor (symbol: string, appId: BigInt, validator: string, signKey: Uint8Array,
algoClientToken: string,
algoClientServer: string,
algoClientPort: string) {
this.symbol = symbol
this.signKey = signKey
this.validator = validator
const algodClient = new algosdk.Algodv2(algoClientToken, algoClientServer, algoClientPort)
this.pclib = new PricecasterLib.PricecasterLib(algodClient)
this.pclib.setAppId(appId)
}
async start () {
await this.pclib.compileApprovalProgram()
}
stop () {
}
signCallback (sender: string, tx: algosdk.Transaction) {
const txSigned = tx.signTxn(this.signKey)
return txSigned
}
async publish (tick: PriceTicker): Promise<PublishInfo> {
const publishInfo: PublishInfo = { status: StatusCode.OK }
let msg, txId
try {
msg = this.pclib.createMessage(
this.symbol,
tick.price,
BigInt(tick.exponent),
tick.confidence,
tick.networkTime,
this.signKey)
publishInfo.msgb64 = msg.toString('base64')
} catch (e: any) {
publishInfo.status = StatusCode.ERROR_CREATE_MESSAGE
publishInfo.reason = e.toString()
return publishInfo
}
try {
txId = await this.pclib.submitMessage(
this.validator,
msg,
this.signCallback.bind(this)
)
publishInfo.txid = txId
} catch (e: any) {
publishInfo.status = StatusCode.ERROR_SUBMIT_MESSAGE
publishInfo.reason = e.response.text ? e.response.text : e.toString()
return publishInfo
}
return publishInfo
}
}

View File

@ -0,0 +1,43 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { PriceTicker } from '../common/priceTicker'
/**
* Implements a strategy for obtaining an asset price from
* a set of received prices in a buffer.
*/
export interface IStrategy {
/**
*
* @param size The size of the buffer
*/
createBuffer(size: number): void
/**
* Clear price buffer
*/
clearBuffer(): void
/**
* Returns the current number of items in buffer
*/
bufferCount(): number
/**
* Put a new price in buffer.
* @param priceData The price data to put
* @returns true if successful.
*/
put(ticker: PriceTicker): boolean
/**
* Get the calculated price according to selected strategy.
*/
getPrice(): PriceTicker | undefined
}

View File

@ -0,0 +1,45 @@
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
import { PriceTicker } from '../common/priceTicker'
import { IStrategy } from './strategy'
/**
* A base class for queue-based buffer strategies
*/
export abstract class StrategyBase implements IStrategy {
protected buffer!: PriceTicker[]
protected bufSize!: number
constructor (bufSize: number = 10) {
this.createBuffer(bufSize)
}
createBuffer (maxSize: number): void {
this.buffer = []
this.bufSize = maxSize
}
clearBuffer (): void {
this.buffer.length = 0
}
bufferCount (): number {
return this.buffer.length
}
put (ticker: PriceTicker): boolean {
if (this.buffer.length === this.bufSize) {
this.buffer.shift()
}
this.buffer.push(ticker)
return true
}
abstract getPrice(): PriceTicker | undefined
}

View File

@ -0,0 +1,21 @@
import { PriceTicker } from '../common/priceTicker'
import { StrategyBase } from './strategyBase'
/**
* Pricecaster Service.
*
* Fetcher backend component.
*
* (c) 2021 Randlabs, Inc.
*/
/**
* This strategy just caches the last provided price,
* acting as a single-item buffer.
*/
export class StrategyLastPrice extends StrategyBase {
getPrice (): PriceTicker | undefined {
const ret = this.buffer[this.buffer.length - 1]
this.clearBuffer()
return ret
}
}

View File

@ -0,0 +1,4 @@
#!/bin/bash
goal app delete --app-id $1 --from "$OWNER_ADDR" -o delete.txn
algokey -t delete.txn -o delete.stxn sign -m "$OWNER_MNEMO"
goal clerk rawsend -f delete.stxn

1
staging/algorand/lib/pricecaster.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module 'PricecasterLib';

View File

@ -0,0 +1,569 @@
/**
*
* Pricecaster Service Utility Library.
* (c) 2021-22 Randlabs, Inc.
*
*/
const algosdk = require('algosdk')
const fs = require('fs')
// eslint-disable-next-line camelcase
const { sha512_256 } = require('js-sha512')
const tools = require('../tools/app-tools')
const approvalProgramFilename = 'teal/pricekeeper/pricekeeper.teal'
const clearProgramFilename = 'teal/pricekeeper/clearstate.teal'
let vaaProcessorApprovalProgramFilename = 'teal/wormhole/build/vaa-processor-approval.teal'
let vaaProcessorClearProgramFilename = 'teal/wormhole/build/vaa-processor-clear.teal'
const vaaVerifyStatelessProgramFilename = 'teal/wormhole/build/vaa-verify.teal'
class PricecasterLib {
constructor (algodClient, ownerAddr = undefined) {
this.algodClient = algodClient
this.ownerAddr = ownerAddr
this.minFee = 1000
this.groupTx = []
/** Overrides the default VAA processor approval program filename
* @param {string} filename New file name to use.
*/
this.setVaaProcessorApprovalFile = function (filename) {
vaaProcessorApprovalProgramFilename = filename
}
/** Overrides the default VAA processor clear-state program filename
* @param {string} filename New file name to use.
*/
this.setVaaProcessorClearStateFile = function (filename) {
vaaProcessorClearProgramFilename = filename
}
/**
* Set Application Id used in all the functions of this class.
* @param {number} applicationId application id
* @returns {void}
*/
this.setAppId = function (applicationId) {
this.appId = applicationId
}
/**
* Get minimum fee to pay for transactions.
* @return {Number} minimum transaction fee
*/
this.minTransactionFee = function () {
return this.minFee
}
/**
* Internal function.
* Read application local state related to the account.
* @param {String} accountAddr account to retrieve local state
* @return {Array} an array containing all the {key: value} pairs of the local state
*/
this.readLocalState = function (accountAddr) {
return tools.readAppLocalState(this.algodClient, this.appId, accountAddr)
}
/**
* Internal function.
* Read application global state.
* @return {Array} an array containing all the {key: value} pairs of the global state
* @returns {void}
*/
this.readGlobalState = function () {
return tools.readAppGlobalState(this.algodClient, this.appId, this.ownerAddr)
}
/**
* Print local state of accountAddr on stdout.
* @param {String} accountAddr account to retrieve local state
* @returns {void}
*/
this.printLocalState = async function (accountAddr) {
await tools.printAppLocalState(this.algodClient, this.appId, accountAddr)
}
/**
* Print application global state on stdout.
* @returns {void}
*/
this.printGlobalState = async function () {
await tools.printAppGlobalState(this.algodClient, this.appId, this.ownerAddr)
}
/**
* Internal function.
* Read application local state variable related to accountAddr.
* @param {String} accountAddr account to retrieve local state
* @param {String} key variable key to get the value associated
* @return {String/Number} it returns the value associated to the key that could be an address, a number or a
* base64 string containing a ByteArray
*/
this.readLocalStateByKey = function (accountAddr, key) {
return tools.readAppLocalStateByKey(this.algodClient, this.appId, accountAddr, key)
}
/**
* Internal function.
* Read application global state variable.
* @param {String} key variable key to get the value associated
* @return {String/Number} it returns the value associated to the key that could be an address,
* a number or a base64 string containing a ByteArray
*/
this.readGlobalStateByKey = function (key) {
return tools.readAppGlobalStateByKey(this.algodClient, this.appId, this.ownerAddr, key)
}
/**
* Compile program that programFilename contains.
* @param {String} programFilename filepath to the program to compile
* @return {String} base64 string containing the compiled program
*/
this.compileProgram = async function (programBytes) {
const compileResponse = await this.algodClient.compile(programBytes).do()
const compiledBytes = new Uint8Array(Buffer.from(compileResponse.result, 'base64'))
return { compiledBytes, hash: compileResponse.hash }
}
/**
* Internal function.
* Compile application clear state program.
* @return {String} base64 string containing the compiled program
*/
this.compileClearProgram = function () {
const program = fs.readFileSync(clearProgramFilename, 'utf8')
return this.compileProgram(program)
}
/**
* Internal function.
* Compile application clear state program.
* @return {String} base64 string containing the compiled program
*/
this.compileVAAProcessorClearProgram = function () {
const program = fs.readFileSync(vaaProcessorClearProgramFilename, 'utf8')
return this.compileProgram(program)
}
/**
* Internal function.
* Compile pricekeeper application approval program.
* @return {String} base64 string containing the compiled program
*/
this.compileApprovalProgram = async function () {
const program = fs.readFileSync(approvalProgramFilename, 'utf8')
const compiledApprovalProgram = await this.compileProgram(program)
this.approvalProgramHash = compiledApprovalProgram.hash
return compiledApprovalProgram
}
/**
* Internal function.
* Compile VAA Processor application approval program.
* @return {String} base64 string containing the compiled program
*/
this.compileVAAProcessorApprovalProgram = async function () {
const program = fs.readFileSync(vaaProcessorApprovalProgramFilename, 'utf8')
const compiledApprovalProgram = await this.compileProgram(program)
this.approvalProgramHash = compiledApprovalProgram.hash
return compiledApprovalProgram
}
/**
* Helper function to retrieve the application id from a createApp transaction response.
* @param {Object} txResponse object containig the transactionResponse of the createApp call
* @return {Number} application id of the created application
*/
this.appIdFromCreateAppResponse = function (txResponse) {
return txResponse['application-index']
}
/**
* Create an application based on the default approval and clearState programs or based on the specified files.
* @param {String} sender account used to sign the createApp transaction
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @return {String} transaction id of the created application
*/
this.createApp = async function (sender, validatorAddr, symbol, signCallback) {
if (symbol.length > 16) {
throw new Error('Symbol exceeds 16 characters')
}
symbol = symbol.padEnd(16, ' ')
const localInts = 0
const localBytes = 0
const globalInts = 4
const globalBytes = 3
// declare onComplete as NoOp
const onComplete = algosdk.OnApplicationComplete.NoOpOC
// get node suggested parameters
const params = await algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
const compiledProgram = await this.compileApprovalProgram()
const approvalProgramCompiled = compiledProgram.compiledBytes
const clearProgramCompiled = (await this.compileClearProgram()).compiledBytes
const enc = new TextEncoder()
const appArgs = [new Uint8Array(algosdk.decodeAddress(validatorAddr).publicKey), enc.encode(symbol)]
// create unsigned transaction
const txApp = algosdk.makeApplicationCreateTxn(
sender, params, onComplete,
approvalProgramCompiled, clearProgramCompiled,
localInts, localBytes, globalInts, globalBytes, appArgs
)
const txId = txApp.txID().toString()
// Sign the transaction
const txAppSigned = signCallback(sender, txApp)
// Submit the transaction
await algodClient.sendRawTransaction(txAppSigned).do()
return txId
}
/**
* Create the VAA Processor application based on the default approval and clearState programs or based on the specified files.
* @param {String} sender account used to sign the createApp transaction
* @param {String} gexpTime Guardian key set expiration time
* @param {String} gkeys Guardian keys listed as a single array
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @return {String} transaction id of the created application
*/
this.createVaaProcessorApp = async function (sender, gexpTime, gkeys, signCallback) {
const localInts = 0
const localBytes = 0
const globalInts = 4
const globalBytes = 20
// declare onComplete as NoOp
const onComplete = algosdk.OnApplicationComplete.NoOpOC
// get node suggested parameters
const params = await algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
const compiledProgram = await this.compileVAAProcessorApprovalProgram()
const approvalProgramCompiled = compiledProgram.compiledBytes
const clearProgramCompiled = (await this.compileVAAProcessorClearProgram()).compiledBytes
const appArgs = [new Uint8Array(Buffer.from(gkeys, 'hex')), algosdk.encodeUint64(parseInt(gexpTime))]
// create unsigned transaction
const txApp = algosdk.makeApplicationCreateTxn(
sender, params, onComplete,
approvalProgramCompiled, clearProgramCompiled,
localInts, localBytes, globalInts, globalBytes, appArgs
)
const txId = txApp.txID().toString()
// Sign the transaction
const txAppSigned = signCallback(sender, txApp)
// Submit the transaction
await algodClient.sendRawTransaction(txAppSigned).do()
return txId
}
/**
* Internal function.
* Call application specifying args and accounts.
* @param {String} sender caller address
* @param {Array} appArgs array of arguments to pass to application call
* @param {Array} appAccounts array of accounts to pass to application call
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @return {String} transaction id of the transaction
*/
this.callApp = async function (sender, appArgs, appAccounts, signCallback) {
// get node suggested parameters
const params = await this.algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
// create unsigned transaction
const txApp = algosdk.makeApplicationNoOpTxn(sender, params, this.appId, appArgs, appAccounts.length === 0 ? undefined : appAccounts)
const txId = txApp.txID().toString()
// Sign the transaction
const txAppSigned = signCallback(sender, txApp)
// Submit the transaction
await this.algodClient.sendRawTransaction(txAppSigned).do()
return txId
}
/**
* Internal function.
* Call application specifying args and accounts. Do it in a group of dummy TXs for maximizing computations.
* @param {String} sender caller address
* @param {Array} appArgs array of arguments to pass to application call
* @param {Array} appAccounts array of accounts to pass to application call
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @param {number} dummyTxCount the number of dummyTx to submit, with the real call last.
* @return {String} transaction id of the transaction
*/
this.callAppInDummyGroup = async function (sender, appArgs, appAccounts, signCallback, dummyTxCount) {
// get node suggested parameters
const params = await this.algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
// console.log(appArgs)
const txns = []
const enc = new TextEncoder()
for (let i = 0; i < dummyTxCount; ++i) {
txns.push(algosdk.makeApplicationNoOpTxn(sender,
params,
this.appId,
undefined, undefined, undefined, undefined,
enc.encode(`dummy_TX_${i}`)))
}
const appTx = algosdk.makeApplicationNoOpTxn(sender, params, this.appId, appArgs)
txns.push(appTx)
algosdk.assignGroupID(txns)
const txId = appTx.txID().toString()
// Sign the transactions
const signedTxns = []
for (const tx of txns) {
signedTxns.push(signCallback(sender, tx))
}
// Submit the transaction
await this.algodClient.sendRawTransaction(signedTxns).do()
return txId
}
/**
* ClearState sender. Remove all the sender associated local data.
* @param {String} sender account to ClearState
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @return {[String]} transaction id of one of the transactions of the group
*/
this.clearApp = async function (sender, signCallback, forcedAppId) {
// get node suggested parameters
const params = await this.algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
let appId = this.appId
if (forcedAppId) {
appId = forcedAppId
}
// create unsigned transaction
const txApp = algosdk.makeApplicationClearStateTxn(sender, params, appId)
const txId = txApp.txID().toString()
// Sign the transaction
const txAppSigned = signCallback(sender, txApp)
// Submit the transaction
await this.algodClient.sendRawTransaction(txAppSigned).do()
return txId
}
/**
* Permanent delete the application.
* @param {String} sender owner account
* @param {Function} signCallback callback with prototype signCallback(sender, tx) used to sign transactions
* @param {Function} applicationId use this application id instead of the one set
* @return {String} transaction id of one of the transactions of the group
*/
this.deleteApp = async function (sender, signCallback, applicationId) {
// get node suggested parameters
const params = await this.algodClient.getTransactionParams().do()
params.fee = this.minFee
params.flatFee = true
if (!applicationId) {
applicationId = this.appId
}
// create unsigned transaction
const txApp = algosdk.makeApplicationDeleteTxn(sender, params, applicationId)
const txId = txApp.txID().toString()
// Sign the transaction
const txAppSigned = signCallback(sender, txApp)
// Submit the transaction
await this.algodClient.sendRawTransaction(txAppSigned).do()
return txId
}
/**
* Helper function to wait until transaction txId is included in a block/round.
* @param {String} txId transaction id to wait for
* @return {VOID} VOID
*/
this.waitForConfirmation = async function (txId) {
const status = (await this.algodClient.status().do())
let lastRound = status['last-round']
// eslint-disable-next-line no-constant-condition
while (true) {
const pendingInfo = await this.algodClient.pendingTransactionInformation(txId).do()
if (pendingInfo['confirmed-round'] !== null && pendingInfo['confirmed-round'] > 0) {
// Got the completed Transaction
return pendingInfo['confirmed-round']
}
lastRound += 1
await this.algodClient.statusAfterBlock(lastRound).do()
}
}
/**
* Helper function to wait until transaction txId is included in a block/round
* and returns the transaction response associated to the transaction.
* @param {String} txId transaction id to get transaction response
* @return {Object} returns an object containing response information
*/
this.waitForTransactionResponse = async function (txId) {
// Wait for confirmation
await this.waitForConfirmation(txId)
// display results
return this.algodClient.pendingTransactionInformation(txId).do()
}
/**
* Creates a message with price data for the PriceKeeper contract
* @param {String} symbol Symbol, must match appid support, 16-char UTF long
* @param {BigInt} price Aggregated price
* @param {BigInt} confidence Confidence
* @param {BigInt} exp Exponent (positive)
* @param {BigInt} slot Valid-slot of price aggregation
* @param {Uint8Array} sk Signing key.
* @param {string} header (optional) Message header. 'PRICEDATA' if undefined.
* @param {BigInt} appId (optional) AppId. Default is this contract appId.
* @param {number} version (optional) Version. Default is 1 if undefined.
* @param {BigInt} ts (optional) Timestamp of message. Current system ts if undefined.
* @returns A base64-encoded message.
*/
this.createMessage = function (symbol, price, exp, confidence, slot, sk, header, appId, version, ts) {
const buf = Buffer.alloc(138)
buf.write(header === undefined ? 'PRICEDATA' : header, 0)
buf.writeInt8(version === undefined ? 1 : version, 9)
buf.writeBigUInt64BE(appId === undefined ? BigInt(this.appId) : appId, 10)
buf.write(symbol, 18)
buf.writeBigUInt64BE(price, 34)
// (!) Libraries like Pyth publish negative exponents. Write as signed 64bit
buf.writeBigInt64BE(exp, 42)
buf.writeBigUInt64BE(confidence, 50)
buf.writeBigUInt64BE(slot, 58)
buf.writeBigUInt64BE(ts === undefined ? BigInt(Math.floor(Date.now() / 1000)) : ts, 66)
const digestu8 = Buffer.from(sha512_256(buf.slice(0, 74)), 'hex')
const signature = Buffer.from(algosdk.tealSign(sk, digestu8, this.approvalProgramHash))
signature.copy(buf, 74)
return buf
}
/**
* Submits message to the PriceKeeper contract.
* @param {*} sender Sender account
* @param {*} msgb64 Base64-encoded message.
* @returns Transaction identifier (txid)
*/
this.submitMessage = async function (sender, msgBuffer, signCallback) {
if (!algosdk.isValidAddress(sender)) {
throw new Error('Invalid sender address: ' + sender)
}
const appArgs = []
appArgs.push(new Uint8Array(msgBuffer))
return await this.callAppInDummyGroup(sender, appArgs, [], signCallback, 3)
}
/**
* VAA Processor: Sets the stateless logic program hash
* @param {*} sender Sender account
* @param {*} hash The stateless logic program hash
* @returns Transaction identifier.
*/
this.setVAAVerifyProgramHash = async function (sender, hash, signCallback) {
if (!algosdk.isValidAddress(sender)) {
throw new Error('Invalid sender address: ' + sender)
}
const appArgs = []
appArgs.push(new Uint8Array(Buffer.from('setvphash')),
algosdk.decodeAddress(hash).publicKey)
return await this.callApp(sender, appArgs, [], signCallback)
}
/**
* Starts a begin...commit section for commiting grouped transactions.
*/
this.beginTxGroup = function () {
this.groupTx = []
}
/**
* Adds a transaction to the group.
* @param {} tx Transaction to add.
*/
this.addTxToGroup = function (tx) {
this.groupTx.push(tx)
}
/**
* @param {*} sender The sender account.
* @param {function} signCallback The sign callback routine.
* @returns Transaction id.
*/
this.commitTxGroup = async function (sender, signCallback) {
algosdk.assignGroupID(this.groupTx)
// Sign the transactions
const signedTxns = []
for (const tx of this.groupTx) {
signedTxns.push(signCallback(sender, tx))
}
// Submit the transaction
const tx = await this.algodClient.sendRawTransaction(signedTxns).do()
this.groupTx = []
return tx.txId
}
/**
* VAA Processor: Add a verification step to a transaction group.
* @param {*} sender The sender account (typically the VAA verification stateless program)
* @param {*} payload The VAA payload as Uint8Array.
* @param {*} gksubset An hex string containing the keys for the guardian subset in this step.
* @param {*} totalguardians The total number of known guardians.
*/
this.addVerifyTx = function (sender, payload, gksubset, totalguardians) {
const appArgs = []
appArgs.push(new Uint8Array(Buffer.from(gksubset, 'hex')), algosdk.encodeUint64(parseInt(totalguardians)))
this.groupTx.push(algosdk.makeApplicationNoOpTxn(sender,
appArgs,
this.appId,
undefined, undefined, undefined, undefined,
payload))
this.groupTx.push()
}
}
}
module.exports = {
PricecasterLib
}

11306
staging/algorand/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,48 @@
{
"name": "pricecaster",
"version": "1.0.0",
"description": "Pricecaster Service",
"main": "index.js",
"scripts": {
"compile": "tsc",
"build": "rimraf build && npm run compile",
"prepack": "npm run build",
"start-btc": "npm run compile && cross-env PRICECASTER_SETTINGS=./settings/settings-btc.js node build/main.js",
"start-eth": "npm run compile && cross-env PRICECASTER_SETTINGS=./settings/settings-eth.js node build/main.js",
"start-doge": "npm run compile && cross-env PRICECASTER_SETTINGS=./settings/settings-doge.js node build/main.js",
"test-pkeeper-sc": "mocha test/pkeeper-sc-test.js --timeout 60000 --bail",
"test-wormhole-sc": "mocha test/wormhole-sc-test.js --timeout 60000 --bail"
},
"author": "Randlabs inc",
"license": "ISC",
"dependencies": {
"@certusone/wormhole-sdk": "^0.0.9",
"@improbable-eng/grpc-web-node-http-transport": "^0.15.0",
"@pythnetwork/client": "^2.3.1",
"@randlabs/js-config-reader": "^1.1.0",
"algosdk": "^1.12.0",
"charm": "^1.0.2",
"elliptic": "^6.5.4",
"esm": "^3.2.25",
"ethers": "^5.5.1",
"fastpriorityqueue": "^0.7.1",
"js-sha512": "^0.8.0",
"web3-eth-abi": "^1.6.1",
"web3-utils": "^1.6.1"
},
"devDependencies": {
"@types/superagent": "^4.1.13",
"@typescript-eslint/eslint-plugin": "^4.32.0",
"@typescript-eslint/parser": "^4.32.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"mocha": "^9.1.2",
"rimraf": "^3.0.2"
}
}

View File

@ -0,0 +1,5 @@
#!/bin/bash
goal app create --creator "$OWNER_ADDR" --global-ints 4 --global-byteslices 20 --local-byteslices 0 --local-ints 0 --approval-prog vaa-processor-approval.teal --clear-prog vaa-processor-clear.teal --app-arg "b64:$GKEYSBASE64" --app-arg int:0 --app-arg int:0 -o create.txn
algokey -t create.txn -o create.stxn sign -m "$OWNER_MNEMO"
goal clerk rawsend -f create.stxn

View File

@ -0,0 +1,4 @@
#!/bin/bash
goal app delete --app-id $1 --from "$OWNER_ADDR" -o delete.txn
algokey -t delete.txn -o delete.stxn sign -m "$OWNER_MNEMO"
goal clerk rawsend -f delete.stxn

View File

@ -0,0 +1,29 @@
const TestLib = require('../test/testlib.js')
const t = new TestLib.TestLib()
const sigkeys = ['563d8d2fd4e701901d3846dee7ae7a92c18f1975195264d676f8407ac5976757', '8d97f25916a755df1d9ef74eb4dbebc5f868cb07830527731e94478cdc2b9d5f', '9bd728ad7617c05c31382053b57658d4a8125684c0098f740a054d87ddc0e93b',
'5a02c4cd110d20a83a7ce8d1a2b2ae5df252b4e5f6781c7855db5cc28ed2d1b4',
'93d4e3b443bf11f99a00901222c032bd5f63cf73fc1bcfa40829824d121be9b2',
'ea40e40c63c6ff155230da64a2c44fcd1f1c9e50cacb752c230f77771ce1d856',
'87eaabe9c27a82198e618bca20f48f9679c0f239948dbd094005e262da33fe6a',
'61ffed2bff38648a6d36d6ed560b741b1ca53d45391441124f27e1e48ca04770',
'bd12a242c6da318fef8f98002efb98efbf434218a78730a197d981bebaee826e',
'20d3597bb16525b6d09e5fb56feb91b053d961ab156f4807e37d980f50e71aff',
'344b313ffbc0199ff6ca08cacdaf5dc1d85221e2f2dc156a84245bd49b981673',
'848b93264edd3f1a521274ca4da4632989eb5303fd15b14e5ec6bcaa91172b05',
'c6f2046c1e6c172497fc23bd362104e2f4460d0f61984938fa16ef43f27d93f6',
'693b256b1ee6b6fb353ba23274280e7166ab3be8c23c203cc76d716ba4bc32bf',
'13c41508c0da03018d61427910b9922345ced25e2bbce50652e939ee6e5ea56d',
'460ee0ee403be7a4f1eb1c63dd1edaa815fbaa6cf0cf2344dcba4a8acf9aca74',
'b25148579b99b18c8994b0b86e4dd586975a78fa6e7ad6ec89478d7fbafd2683',
'90d7ac6a82166c908b8cf1b352f3c9340a8d1f2907d7146fb7cd6354a5436cca',
'b71d23908e4cf5d6cd973394f3a4b6b164eb1065785feee612efdfd8d30005ed'
]
const vaa = t.createSignedVAA(0, sigkeys, 1, 1, 1, '0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b', 0, 0, '0x12345678')
if (process.argv[2] === '--sig') {
console.log(vaa.substr(12, sigkeys.length * 132))
} else if (process.argv[2] === '--body') {
console.log(vaa.substr(12 + sigkeys.length * 132))
} else {
console.log(vaa)
}

View File

@ -0,0 +1,7 @@
#!/bin/bash
export OWNER_ADDR=OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU
export OWNER_MNEMO='assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
export GUARDIAN_KEYS='52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599072491bd66F63356090C11Aae8114F5372aBf12B51280eA1fd2B0A1c76Ae29a7d54dda68860A2bfFfa9Aa60CfF05e20E2CcAA784eE89A0A16C2057CBe42d59F8FCd86a1c5c4bA351bD251A5c5B05DF6A4B07fF9D5cE1A6ed58b6e9e7d6974d1baBEc087ec8306B84235D7b0478c61783C50F990bfC44cFc0C8C1035110a13fe788259A4148F871b52bAbcb1B58A2508A20A7198E131503ce26bBE119aA8c62b28390820f04ddA22AFe03be1c3bb10f4ba6CF94A01FD6e97387C34a1F36DE0f8341E9D409E06ec45b255a41fC2792209CB998A8287204D40996df9E54bA663B12DD23fbF4FbAC618Be140727986B3BBd079040E577aC50486d0F6930e160A5C75FD1203C63580D2F00309A9A85efFAf02564Fc183C0183A963869795913D3B6dBF3B24a1C7654672c69A23c351c0Cc52D7673c52DE99785741344662F5b2308a0'
export GKEYSBASE64=`node -e "console.log(Buffer.from('$GUARDIAN_KEYS', 'hex').toString('base64'))"`

View File

@ -0,0 +1,9 @@
#!/bin/bash
export STATELESS_ADDR=$(goal clerk compile vaa-verify.teal | cut -f 2 -d ':' | cut -c 2- )
goal app call --app-id $1 --from "$OWNER_ADDR" --app-arg "str:setvphash" --app-arg "addr:$STATELESS_ADDR" -o setvphash.txn
algokey -t setvphash.txn -o setvphash.stxn sign -m "$OWNER_MNEMO"
goal clerk rawsend -f setvphash.stxn

View File

@ -0,0 +1,53 @@
#!/bin/bash
export SIGNATURES064=`node -e "console.log(Buffer.from('003fe8e05b0d3594bbf0ab1da0110dded88930a181ace6089a2442a8e58b293b23777331d928ab36c85de11e6f2874c1cc12c418fc4e0c1e344864a8b85fda042e0001791d7134fba47002376841fe688f7c478ba223580ec25ad5046a93db477d36fb4afa241ea95bf3c02b378a24220ff0f2ea035d088a0011bff9a4743d88f5c1b4010281940f26308012efd7a307960223638abde4fb55abcaac04a9fa97bf92e5518e5903396bf7e807eb0e97e3009f7e679c0dcece45cd659ab6cf45fed9add2d6a10103470cda5780ffb89118f152c449b4137f6c4f5413c4193d8a4169b31712d6c6583a90d34a31184cc5f3c8e8c987753a69ceadb2a46fcd31cd2db8fba4f918f5270004376beb1f765fe3222cc3fc0a891f731a7c9cdb762b5997e8bd9e32e473c2cf8b63db7fbb06156ec90990e6edd39cf3402054c2ca34bbec6fc2ab1cbfe49c9a860005058e4f1150dcdba98b8054f99dfe75fa2c2c8f0c9b23a858c9e5abff85e535f317627ddf5ec51b43182b382811f8a52c7832be5c7c630eb45d9213a96989c25c01','hex').toString('base64'))"`
export SIGNATURES164=`node -e "console.log(Buffer.from('0699f7fe9387cbc7c6528f7b7183042efb8d52f5e2811dc274c3e90141ff187fa21761f04e0d9b99f7bb40ad48709532c40b012de07d5253696aae4972ed1db2130107bfcf86e950316e431874dc755acafdbaf9c28d62b3731f76abe2f7299add68d0629fc5df238856ba6ad1c9ab6a5ed3f0c43a350250005274bdadbc2c697eb63b0108d69cae6a854c5468415c51747c9d7861ca5d5b164d100486c40477602a1c2e983da703866ffb2d3c9a642681e0c97c1ba8927d38b1d583c03a89d4f277a9a33900097e82cad360d4bb4f71e74e2ce0bdc067c38a97bd000fb397c99dbed63013179000b47e534028300a99ba5f722877164341ab859f8e7c21f815a77d54fd78aba2000ab009ea66dd2d7114952b3a667bd603110f08bd20ac03a79b672049e4a2f515b713527db7db0a3c13442ba8f2dad37cb255e4c660251cb96784ce7d385576eed5010b5ef9003237297028d98779f43041bd3141b4219ffa5965cf806d23188bb0538f0639aaadcda9d62a402df3a48da7cae5cc25e1a129ba30cf08cf5ff4da49bd0c00', 'hex').toString('base64'))"`
export SIGNATURES264=`node -e "console.log(Buffer.from('0cca7cd22e1514f0022666b35379f0685bfebbd5b80832d77eae6f57f52d351509093c433774d07ff6f3a4698331333a1dbb5478c4a51e20c15380d5dc68575f66000d525ac1524ec9d9ee623ef535a867e8f86d9b3f8e4c7b4234dbe7bb40dc8494327af2fa37c3db50064d6114f2e1441c4eee444b83636f11ce1f730f7b38490e28000e4528d8e7556ac14c74260f4ca5ed62c275324adec5a1146ac1abf6b41fcec88a24b4b797ed5370f648647904662e1fe2da2b4dea4327dfd2b94ca7080ed569f7010f5c84b1ef2ff5938ecdfd7048b2323b3e3568b2e0a62c8c513f60a4dfce8ee48e3fc7409caad8be1185be42c8a5e81d1fa4c4c98f6f53cdcddab6add2384dc5f20110cad08c66411cde321ce5b598ee4620e098e18a0427444c57923507064368912a3fab73a6b40dc050fbdaf340409583735a2528fde9b9b0322bd317f804b4767b0011c17a151c7d37376a3f7ea45030a18c4e3791dc5e376c350fe7838548506f64ee19e946fcb1b258394c6b6964608fc0a9d6a5ef682b3faded66b214637220dab300', 'hex').toString('base64'))"`
export SIGNATURES364=`node -e "console.log(Buffer.from('12af4f9015c9f11da3cb5457be96db960d49b37e59ec2bfce2b21dd2dfd28305f560e7977994a8380b7486361758a3eeace18aa1781bfcd79ad27995b41e504cd701','hex').toString('base64'))"`
export GK0='52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599072491bd66F63356090C11Aae8114F5372aBf12B51280eA1fd2B0A1c76Ae29a7d54dda68860A2bfFfa9Aa60CfF05e20E2CcAA784eE89A0A16C2057CB'
export GK1='e42d59F8FCd86a1c5c4bA351bD251A5c5B05DF6A4B07fF9D5cE1A6ed58b6e9e7d6974d1baBEc087ec8306B84235D7b0478c61783C50F990bfC44cFc0C8C1035110a13fe788259A4148F871b52bAbcb1B58A2508A20A7198E131503ce26bBE119aA8c62b28390820f04ddA22AFe03be1c3bb10f4ba6CF94A0'
export GK2='1FD6e97387C34a1F36DE0f8341E9D409E06ec45b255a41fC2792209CB998A8287204D40996df9E54bA663B12DD23fbF4FbAC618Be140727986B3BBd079040E577aC50486d0F6930e160A5C75FD1203C63580D2F00309A9A85efFAf02564Fc183C0183A963869795913D3B6dBF3B24a1C7654672c69A23c35'
export GK3='1c0Cc52D7673c52DE99785741344662F5b2308a0'
export GK064=`node -e "console.log(Buffer.from('$GK0', 'hex').toString('base64'))"`
export GK164=`node -e "console.log(Buffer.from('$GK1', 'hex').toString('base64'))"`
export GK264=`node -e "console.log(Buffer.from('$GK2', 'hex').toString('base64'))"`
export GK364=`node -e "console.log(Buffer.from('$GK3', 'hex').toString('base64'))"`
export VAABODY='0000000100000001000171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b00000000000000000012345678'
export VAABODY64=`node -e "console.log(Buffer.from('$VAABODY', 'hex').toString('base64'))"`
rm -f verify?.txn verify?.stxn verify?.dump
if [[ $1 == '' ]]
then
echo 'No appid specified'
exit
fi
if [[ $STATELESS_ADDR == '' ]]
then
echo 'No STATELESS_ADDR'
exit
fi
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GK064" --app-arg "int:19" --noteb64 "$VAABODY64" -o verify0.txn
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GK164" --app-arg "int:19" --noteb64 "$VAABODY64" -o verify1.txn
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GK264" --app-arg "int:19" --noteb64 "$VAABODY64" -o verify2.txn
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GK364" --app-arg "int:19" --noteb64 "$VAABODY64" -o verify3.txn
cat verify0.txn verify1.txn verify2.txn verify3.txn > verifycc.txn
goal clerk group -i verifycc.txn -o group.txn
goal clerk split -i group.txn -o verify-signed
goal clerk sign --program vaa-verify.teal --argb64 "$SIGNATURES064" --infile verify-signed-0 --outfile verify-signed-0
goal clerk sign --program vaa-verify.teal --argb64 "$SIGNATURES164" --infile verify-signed-1 --outfile verify-signed-1
goal clerk sign --program vaa-verify.teal --argb64 "$SIGNATURES264" --infile verify-signed-2 --outfile verify-signed-2
goal clerk sign --program vaa-verify.teal --argb64 "$SIGNATURES364" --infile verify-signed-3 --outfile verify-signed-3
cat verify-signed-0 verify-signed-1 verify-signed-2 verify-signed-3 > verifygroup.stxn
goal clerk dryrun -t verifygroup.stxn --dryrun-dump --outfile verifygroup.dump
goal clerk dryrun-remote -D verifygroup.dump --verbose

View File

@ -0,0 +1,13 @@
#!/bin/bash
export SIGNATURES64=`node -e "console.log(Buffer.from('$2','hex').toString('base64'))"`
export GUARDIAN_KEYS='52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599072491bd66F63356090C11Aae8114F5372aBf12B51280eA1fd2B0A1c76Ae29a7d54dda68860A2bfFfa9Aa60CfF05e20E2CcAA784eE89A0A16C2057CBe42d59F8FCd86a1c5c4bA351bD251A5c5B05DF6A4B07fF9D5cE1A6ed58b6e9e7d6974d1baBEc087ec8306B84235D7b0478c61783C50F990bfC44cFc0C8C1035110a13fe788259A4148F871b52bAbcb1B58A2508A20A7198E131503ce26bBE119aA8c62b28390820f04ddA22AFe03be1c3bb10f4ba6CF94A01FD6e97387C34a1F36DE0f8341E9D409E06ec45b255a41fC2792209CB998A8287204D40996df9E54bA663B12DD23fbF4FbAC618Be140727986B3BBd079040E577aC50486d0F6930e160A5C75FD1203C63580D2F00309A9A85efFAf02564Fc183C0183A963869795913D3B6dBF3B24a1C7654672c69A23c351c0Cc52D7673c52DE99785741344662F5b2308a0'
export GKEYSBASE64=`node -e "console.log(Buffer.from('$GUARDIAN_KEYS', 'hex').toString('base64'))"`
export VAABODY=$3
export VAABODY64=`node -e "console.log(Buffer.from('$VAABODY', 'hex').toString('base64'))"`
rm verify.txn verify.stxn
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GKEYSBASE64" --app-arg "int:3" --noteb64 "$VAABODY64" -o verify.txn
goal clerk sign --program vaa-verify.teal --argb64 "$SIGNATURES64" --infile verify.txn --outfile verify.stxn
goal clerk dryrun -t verify.stxn --dryrun-dump --outfile verify.dump
goal clerk dryrun-remote -D verify.dump --verbose

View File

@ -0,0 +1,12 @@
#!/bin/bash
export SIGNATURES64=`node -e "console.log(Buffer.from('25a2cec435380f6413e8b5d5531cd8789322a1d8bc488309bb868c33a26cc9492947b48895460d8d2261d669bcef210987cc5eeb9fa21504c3f5a9b5a0ff32df00ee4d1a5e589b5aa0d4787eaf57ba4b41e6a54e35e8ca60a028a0f1e35db3a8ed5d901a9831272fc117f472fcd0115d31365efd575a19a28eaf5ad9be7cf5f0d901a671b7c2af66aa6bff3337adaa7e5f196630508f85491e650cfdaccd2f67d2a605faf1c267eddaa50ac6de8d35894afce7974f14982f6173b0d020e0567f2a4a01','hex').toString('base64'))"`
export GUARDIAN_KEYS='52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599'
export GKEYSBASE64=`node -e "console.log(Buffer.from('$GUARDIAN_KEYS', 'hex').toString('base64'))"`
export VAABODY='0000000100000001000171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b00000000000000010012345678'
export VAABODY64=`node -e "console.log(Buffer.from('$VAABODY', 'hex').toString('base64'))"`
goal app call --app-id $1 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GKEYSBASE64" --app-arg "int:3" --noteb64 "$VAABODY64" -o verify.txn

View File

@ -0,0 +1,20 @@
module.exports = {
mode: 'pkeeper',
algo: {
token: '',
api: 'https://api.testnet.algoexplorer.io',
port: ''
},
pyth: {
solanaClusterName: 'devnet'
},
params: {
verbose: true,
symbol: 'BTC/USD',
bufferSize: 100,
publishIntervalSecs: 30,
priceKeeperAppId: 32968790,
validator: 'OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU',
mnemo: 'assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
}
}

View File

@ -0,0 +1,20 @@
module.exports = {
mode: 'pkeeper',
algo: {
token: '',
api: 'https://api.testnet.algoexplorer.io',
port: ''
},
pyth: {
solanaClusterName: 'devnet'
},
params: {
verbose: true,
symbol: 'DOGE/USD',
bufferSize: 100,
publishIntervalSecs: 30,
priceKeeperAppId: 32984598,
validator: 'OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU',
mnemo: 'assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
}
}

View File

@ -0,0 +1,20 @@
module.exports = {
mode: 'pkeeper',
algo: {
token: '',
api: 'https://api.testnet.algoexplorer.io',
port: ''
},
pyth: {
solanaClusterName: 'devnet'
},
params: {
verbose: true,
symbol: 'ETH/USD',
bufferSize: 100,
publishIntervalSecs: 30,
priceKeeperAppId: 32984466,
validator: 'OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU',
mnemo: 'assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
}
}

View File

@ -0,0 +1,3 @@
#pragma version 5
int 1
return

View File

@ -0,0 +1,255 @@
#pragma version 5
// ================================================================================================
// PriceKeeper Approval Program
// ================================================================================================
//
// App-globals:
// sym : byte[] Symbol to keep price for
// vaddr : byte[] Validator account
// price : uint64 current price
// stdev : uint64 current confidence (standard deviation)
// slot : uint64 slot of this onchain publication
// exp : byte[] exponent. Interpret as two-compliment, Big-Endian 64bit
// ts : uint64 last timestamp
//
// Slots:
// 0 Input message block
// 1 SHA256-Hashed message
//
// The Message format must have the packed fields:
//
// Field size
// 9 header Literal "PRICEDATA"
// 1 version int8 (Must be 1)
// 8 dest This appId
// 16 symbol String filled with spaces e.g ("ALGO/USD ")
// 8 price Price. 64bit integer.
// 8 priceexp Price exponent. Interpret as two-compliment, Big-Endian 64bit
// 8 conf Confidence (stdev). 64bit integer.
// 8 slot Valid-slot of this aggregate price.
// 8 ts timestamp of this price submitted by PriceFetcher service
// 32 s Signature s-component
// 32 r Signature r-component
//
// Size: 138 bytes.
//
// ------------------------------------------------------------------------------------------------
// Application creation.
int 0
txn ApplicationID
==
bnz handle_create
// Handle app call: send price message
txn OnCompletion
int NoOp
==
bnz handle_call
// Handle deletion.
txn OnCompletion
int DeleteApplication
==
bnz success
// Fail otherwise
err
handle_create:
// -----------------------------------------------------
// Handle creation
// Arg 0: Validator address
// Arg 1: Symbol to keep price data
// -----------------------------------------------------
byte "vaddr"
txn ApplicationArgs 0
app_global_put
byte "sym"
txn ApplicationArgs 1
dup
len
int 16
==
assert
app_global_put
byte "ts"
global LatestTimestamp
app_global_put
b success
// -----------------------------------------------------
// Handle app call
// -----------------------------------------------------
handle_call:
// Group size must be 4 to raise computational allowance to 2800
global GroupSize
int 4
==
assert
// if this is one of dummy transactions(0, 1 or 2), exit with success
txn GroupIndex
int 3
!=
bnz success
// Verify if sender is the data validator
txn Sender
byte "vaddr"
app_global_get
==
assert
// Retrieve message, store in slot 0
txn ApplicationArgs 0
store 0
// ------------------------------------------------------
// Validate message
// ------------------------------------------------------
// Check length
load 0
len
int 138
==
assert
// Check header
byte "PRICEDATA"
load 0
extract 0 9
==
assert
// Check version - must be 1.
load 0
extract 9 1
byte 0x01
==
assert
// Check destination - must be this appId.
load 0
extract 10 8
btoi
txn ApplicationID
==
assert
// Reject zero price
load 0
extract 34 8
btoi
int 0
!=
assert
// Reject zero slot
load 0
extract 58 8
btoi
int 0
!=
assert
// Check timestamp:
// * must be higher than ts recorded in global state
// * must be lower than current block stamp + 10s
// (TODO: check this again)
load 0
extract 66 8
btoi
dup
dup
global LatestTimestamp
int 10
+
<
assert
byte "ts"
app_global_get
>
assert
// ed25519verify args in stack:
// data (hash of message)
load 0
extract 0 74
sha512_256
// (B) signature
load 0
extract 74 64
// validator-address
byte "vaddr"
app_global_get
// Verify signature
ed25519verify
int 1
==
assert
// ----------------------------------------------------------------------------
// Verified. Store data to app globals.
// ----------------------------------------------------------------------------
byte "ts"
load 0
extract 66 8
btoi
app_global_put
byte "price"
load 0
extract 34 8
btoi
app_global_put
byte "exp"
load 0
extract 42 8
app_global_put
byte "conf"
load 0
extract 50 8
btoi
app_global_put
byte "slot"
load 0
extract 58 8
btoi
app_global_put
b success
// ----------------------------------------------------------------------------
fail:
int 0
return
success:
int 1
return

View File

@ -0,0 +1,60 @@
#!/usr/bin/python3
# The maximum number of signatures verified by each transaction in the group.
# the total count of required transactions to verify all guardian signatures is
#
# floor(guardian_count / SIGNATURES_PER_TRANSACTION)
#
from pyteal.types import *
from pyteal.ast import *
MAX_SIGNATURES_PER_VERIFICATION_STEP = 6
"""
Math ceil function.
"""
@Subroutine(TealType.uint64)
def ceil(n, d):
q = n / d
r = n % d
return Seq([
If(r != Int(0)).Then(Return(q + Int(1))).Else(Return(q))
])
"""
Return the minimum Uint64 of A,B
"""
@Subroutine(TealType.uint64)
def min(a, b):
If(Int(a) < Int(b), Return(a), Return(b))
"""
Let G be the guardian count, N number of signatures per verification step, group must have CEIL(G/N) transactions.
"""
@Subroutine(TealType.uint64)
def get_group_size(num_guardians):
return ceil(num_guardians, Int(MAX_SIGNATURES_PER_VERIFICATION_STEP))
"""
Get the number of signatures to verify in current step
"""
@Subroutine(TealType.uint64)
def get_sig_count_in_step(step, num_guardians):
r = num_guardians % Int(MAX_SIGNATURES_PER_VERIFICATION_STEP)
return Seq(
If(r == Int(0)).Then(Return(Int(MAX_SIGNATURES_PER_VERIFICATION_STEP)))
.ElseIf(step < get_group_size(num_guardians) - Int(1))
.Then(
Return(Int(MAX_SIGNATURES_PER_VERIFICATION_STEP)))
.Else(
Return(num_guardians % Int(MAX_SIGNATURES_PER_VERIFICATION_STEP))))

View File

@ -0,0 +1,36 @@
#!/usr/bin/python3
from pyteal import *
class CustomOp():
def __init__(self, opcode):
self.opcode = opcode
self.mode = Mode.Signature | Mode.Application
self.min_version = 2
def __str__(self) -> str:
return self.opcode
class InlineAssembly(LeafExpr):
def __init__(self, opcode: str, *args: "Expr", type: TealType = TealType.none) -> None:
super().__init__()
opcode_with_args = opcode.split(" ")
self.op = CustomOp(opcode_with_args[0])
self.type = type
self.opcode_args = opcode_with_args[1:]
self.args = args
def __teal__(self, options: "CompileOptions"):
op = TealOp(self, self.op, *self.opcode_args)
return TealBlock.FromOp(options, op, *self.args[::1])
def __str__(self):
return "(InlineAssembly: {})".format(self.opcode)
def type_of(self):
return self.type

View File

@ -0,0 +1,291 @@
#!/usr/bin/python3
"""
================================================================================================
The VAA Processor Program
(c) 2021 Randlabs, Inc.
------------------------------------------------------------------------------------------------
This program is the core client to signed VAAs from Wormhole, working in tandem with the
verify-vaa.teal stateless programs.
The following application calls are available.
setvphash: Set verify program hash.
Must be part of group:
verify: Verify guardian signature subset i..j, works in tandem with stateless program.
Arguments: #0 guardian public keys subset i..j (must match stored in global state)
#1 guardian signatures subset i..j
TX Note: payload to verify
Last verification step (the last TX in group) triggers the VAA commiting stage,
where we decide what to do based on the payload.
------------------------------------------------------------------------------------------------
Global state:
"vphash" : Hash of verification program logic
"gsexp" : Guardian set expiration time
"gscount" : Guardian set size
"vssize" : Verification step size.
key N : address of guardian N
------------------------------------------------------------------------------------------------
Stores in scratch:
SLOT 255: number of guardians in set
================================================================================================
"""
from pyteal.ast import *
from pyteal.types import *
from pyteal.compiler import *
from pyteal.ir import *
from globals import *
import sys
GUARDIAN_ADDRESS_SIZE = 20
METHOD = Txn.application_args[0]
VERIFY_ARG_GUARDIAN_KEY_SUBSET = Txn.application_args[1]
VERIFY_ARG_GUARDIAN_SET_SIZE = Txn.application_args[2]
VERIFY_ARG_PAYLOAD = Txn.note()
SLOTID_TEMP_0 = 251
SLOTID_VERIFIED_BIT = 254
STATELESS_LOGIC_HASH = App.globalGet(Bytes("vphash"))
NUM_GUARDIANS = App.globalGet(Bytes("gscount"))
SLOT_VERIFIED_BITFIELD = ScratchVar(TealType.uint64, SLOTID_VERIFIED_BIT)
SLOT_TEMP = ScratchVar(TealType.uint64, SLOTID_TEMP_0)
# defined chainId/contracts
GOVERNANCE_CHAIN_ID = 1
GOVERNANCE_EMITTER_ID = '00000000000000000000000000000000000000000000'
PYTH2WORMHOLE_CHAIN_ID = 1
PYTH2WORMHOLE_EMITTER_ID = '0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b'
# VAA fields
VAA_RECORD_EMITTER_CHAIN_POS = 4
VAA_RECORD_EMITTER_CHAIN_LEN = 4
VAA_RECORD_EMITTER_ADDR_POS = 10
VAA_RECORD_EMITTER_ADDR_LEN = 32
# -------------------------------------------------------------------------------------------------
@Subroutine(TealType.uint64)
# Arg0: Bootstrap with the initial list of guardians packed.
# Arg1: Expiration time in second argument.
# Arg2: Guardian set Index.
#
# Guardian public keys are 20-bytes wide, so
# using arguments a maximum 1000/20 ~ 200 public keys can be specified in this version.
def bootstrap():
guardian_count = ScratchVar(TealType.uint64)
i = SLOT_TEMP
return Seq([
Assert(Txn.application_args.length() == Int(3)),
Assert(Len(Txn.application_args[0]) %
Int(GUARDIAN_ADDRESS_SIZE) == Int(0)),
guardian_count.store(
Len(Txn.application_args[0]) / Int(GUARDIAN_ADDRESS_SIZE)),
Assert(guardian_count.load() > Int(0)),
For(i.store(Int(0)), i.load() < guardian_count.load(), i.store(i.load() + Int(1))).Do(
App.globalPut(Itob(i.load()), Extract(
Txn.application_args[0], i.load() * Int(GUARDIAN_ADDRESS_SIZE), Int(GUARDIAN_ADDRESS_SIZE)))
),
App.globalPut(Bytes("gscount"), guardian_count.load()),
App.globalPut(Bytes("gsexp"), Btoi(Txn.application_args[1])),
App.globalPut(Bytes("gsindex"), Btoi(Txn.application_args[2])),
App.globalPut(Bytes("vssize"), Int(MAX_SIGNATURES_PER_VERIFICATION_STEP)),
Approve()
])
@Subroutine(TealType.uint64)
def is_creator():
return Txn.sender() == Global.creator_address()
@Subroutine(TealType.uint64)
def check_guardian_key_subset():
# Verify that the passed argument for guardian keys [i..j] match the
# global state for the same keys.
#
i = SLOT_TEMP
sig_count = ScratchVar(TealType.uint64)
idx_base = ScratchVar(TealType.uint64)
return Seq([
idx_base.store(Int(MAX_SIGNATURES_PER_VERIFICATION_STEP) * Txn.group_index()),
sig_count.store(get_sig_count_in_step(Txn.group_index(), NUM_GUARDIANS)),
For(i.store(Int(0)),
i.load() < sig_count.load(),
i.store(i.load() + Int(1))).Do(
If(
App.globalGet(Itob(i.load() + idx_base.load())) != Extract(VERIFY_ARG_GUARDIAN_KEY_SUBSET,
i.load() * Int(GUARDIAN_ADDRESS_SIZE),
Int(GUARDIAN_ADDRESS_SIZE))).Then(Return(Int(0))) # get and compare stored global key
),
Return(Int(1))
])
@Subroutine(TealType.uint64)
def check_guardian_set_size():
#
# Verify that the passed argument for guardian set size matches the global state.
#
return NUM_GUARDIANS == Btoi(VERIFY_ARG_GUARDIAN_SET_SIZE)
@Subroutine(TealType.uint64)
def handle_governance():
return Int(1)
@Subroutine(TealType.uint64)
def handle_pyth_price_ticker():
return Int(1)
@Subroutine(TealType.uint64)
#
# Unpack the verified VAA payload and process it according to
# the source based by emitterChainId, emitterAddress.
#
def commit_vaa():
chainId = Btoi(Extract(VERIFY_ARG_PAYLOAD, Int(
VAA_RECORD_EMITTER_CHAIN_POS), Int(VAA_RECORD_EMITTER_CHAIN_LEN)))
emitterId = Extract(VERIFY_ARG_PAYLOAD, Int(
VAA_RECORD_EMITTER_ADDR_POS), Int(VAA_RECORD_EMITTER_ADDR_LEN))
return Seq([
If(And(
chainId == Int(GOVERNANCE_CHAIN_ID),
emitterId == Bytes(GOVERNANCE_EMITTER_ID))).Then(
Return(handle_governance()))
.ElseIf(And(
chainId == Int(PYTH2WORMHOLE_CHAIN_ID),
emitterId == Bytes('base16', PYTH2WORMHOLE_EMITTER_ID)
)).Then(
Return(handle_pyth_price_ticker())
).Else(
Return(Int(0))
)
])
@Subroutine(TealType.uint64)
def check_final_verification_state():
#
# Verifies that previous steps had set their verification bits.
#
i = SLOT_TEMP
return Seq([
For(i.store(Int(1)),
i.load() < Global.group_size(),
i.store(i.load() + Int(1))).Do(Seq([
Assert(Gtxn[i.load()].type_enum() == TxnType.ApplicationCall),
Assert(Gtxn[i.load()].application_id() == Txn.application_id()),
Assert(GetBit(ImportScratchValue(i.load() - Int(1), SLOTID_VERIFIED_BIT), i.load() - Int(1)) == Int(1))
])
),
Return(Int(1))
])
def setvphash():
#
# Sets the hash of the verification stateless program.
#
return Seq([
Assert(is_creator()),
Assert(Global.group_size() == Int(1)),
Assert(Txn.application_args.length() == Int(2)),
Assert(Len(Txn.application_args[1]) == Int(32)),
App.globalPut(Bytes("vphash"), Txn.application_args[1]),
Approve()
])
def verify():
# * Sender must be stateless logic.
# * Let N be the number of signatures per verification step, for the TX(i) in group, we verify signatures [j..k] where j = i*N, k = j+(N-1)
# * Argument 0 must contain guardian public keys for guardians [i..j] (read by stateless logic).
# Public keys are 32 bytes long so expected argument length is 32 * (j - i + 1)
# * Argument 1 must contain current guardian set size (read by stateless logic)
# * Passed guardian public keys [i..j] must match the current global state.
# * Note must contain VAA message-in-digest (header+payload) (up to 1KB) (read by stateless logic)
#
# Last TX in group will trigger VAA handling depending on payload. It is required that
# all previous transactions are app-calls for this AppId and all bitfields are set.
return Seq([
SLOT_VERIFIED_BITFIELD.store(Int(0)),
Assert(Global.group_size() == get_group_size(NUM_GUARDIANS)),
Assert(Txn.application_args.length() == Int(3)),
Assert(Txn.sender() == STATELESS_LOGIC_HASH),
Assert(check_guardian_set_size()),
Assert(check_guardian_key_subset()),
SLOT_VERIFIED_BITFIELD.store(
SetBit(SLOT_VERIFIED_BITFIELD.load(), Txn.group_index(), Int(1))),
If(Txn.group_index() == Global.group_size() -
Int(1)).Then(
Return(Seq([
Assert(check_final_verification_state()),
commit_vaa()
]))),
Approve()])
def vaa_processor_program():
handle_create = Return(bootstrap())
handle_update = Return(is_creator())
handle_delete = Return(is_creator())
handle_noop = Cond(
[METHOD == Bytes("setvphash"), setvphash()],
[METHOD == Bytes("verify"), verify()],
)
return Cond(
[Txn.application_id() == Int(0), handle_create],
[Txn.on_completion() == OnComplete.UpdateApplication, handle_update],
[Txn.on_completion() == OnComplete.DeleteApplication, handle_delete],
[Txn.on_completion() == OnComplete.NoOp, handle_noop]
)
def clear_state_program():
return Int(1)
if __name__ == "__main__":
approval_outfile = "teal/wormhole/build/vaa-processor-approval.teal"
clear_state_outfile = "teal/wormhole/build/vaa-processor-clear.teal"
if len(sys.argv) >= 2:
approval_outfile = sys.argv[1]
if len(sys.argv) >= 3:
clear_state_outfile = sys.argv[2]
print("VAA Processor Program, (c) 2021-22 Randlabs Inc. ")
print("Compiling approval program...")
with open(approval_outfile, "w") as f:
compiled = compileTeal(vaa_processor_program(),
mode=Mode.Application, version=5)
f.write(compiled)
print("Written to " + approval_outfile)
print("Compiling clear state program...")
with open(clear_state_outfile, "w") as f:
compiled = compileTeal(clear_state_program(),
mode=Mode.Application, version=5)
f.write(compiled)
print("Written to " + clear_state_outfile)

View File

@ -0,0 +1,134 @@
#!/usr/bin/python3
"""
================================================================================================
The VAA Signature Verify Stateless Program
(c) 2021 Randlabs, Inc.
------------------------------------------------------------------------------------------------
This program verifies a subset of the signatures in a VAA against the guardian set. This
program works in tandem with the VAA Processor stateful program.
================================================================================================
"""
from pyteal.ast import *
from pyteal.types import *
from pyteal.compiler import *
from pyteal.ir import *
from globals import *
from inlineasm import *
import sys
SLOTID_RECOVERED_PK_X = 240
SLOTID_RECOVERED_PK_Y = 241
@Subroutine(TealType.uint64)
def sig_check(signatures, digest, keys):
si = ScratchVar(TealType.uint64)
ki = ScratchVar(TealType.uint64)
i = ScratchVar(TealType.uint64)
rec_pk_x = ScratchVar(TealType.bytes, SLOTID_RECOVERED_PK_X)
rec_pk_y = ScratchVar(TealType.bytes, SLOTID_RECOVERED_PK_Y)
return Seq(
[
rec_pk_x.store(Bytes("")),
rec_pk_y.store(Bytes("")),
For(Seq([
i.store(Int(0)),
si.store(Int(0)),
ki.store(Int(0))
]),
si.load() < Len(signatures),
Seq([
si.store(si.load() + Int(66)),
ki.store(ki.load() + Int(20)),
i.store(i.load() + Int(1)),
])).Do(
Seq([
# Index must be sequential
Assert(Btoi(Extract(signatures, si.load(), Int(1))) ==
i.load() + (Txn.group_index() * Int(MAX_SIGNATURES_PER_VERIFICATION_STEP))),
InlineAssembly(
"ecdsa_pk_recover Secp256k1",
Keccak256(digest),
Btoi(Extract(signatures, si.load() + Int(65), Int(1))),
Extract(signatures, si.load() + Int(1), Int(32)), # R
Extract(signatures, si.load() + Int(33), Int(32)), # S
type=TealType.none),
# returned values in stack, pass to scratch-vars
InlineAssembly("store " + str(SLOTID_RECOVERED_PK_Y)),
InlineAssembly("store " + str(SLOTID_RECOVERED_PK_X)),
# Generate Ethereum-type public key, compare with guardian key.
Assert(
Extract(keys, ki.load(), Int(20)) ==
Substring(Keccak256(Concat(rec_pk_x.load(),
rec_pk_y.load())), Int(12), Int(32))
)
])
),
Return(Int(1))
]
)
"""
* Let N be the number of signatures per verification step, for the TX(i) in group, we verify signatures [j..k] where j = i*N, k = j+(N-1)
* Input 0 is signatures [j..k] to verify as LogicSigArgs. (Format is GuardianIndex + signature)
* Input 1 is signed digest of payload, contained in the note field of the TX in current slot.
* Input 2 is public keys for guardians [j..k] contained in the first Argument of the TX in current slot.
* Input 3 is guardian set size contained in the second argument of the TX in current slot.
"""
def vaa_verify_program(vaa_processor_app_id):
signatures = Arg(0)
digest = Txn.note()
keys = Txn.application_args[1]
num_guardians = Txn.application_args[2]
return Seq([
Assert(Txn.fee() <= Int(1000)),
Assert(Txn.application_args.length() == Int(3)),
Assert(Len(signatures) == get_sig_count_in_step(
Txn.group_index(), Btoi(num_guardians)) * Int(66)),
Assert(Txn.rekey_to() == Global.zero_address()),
Assert(Txn.application_id() == Int(vaa_processor_app_id)),
Assert(Txn.type_enum() == TxnType.ApplicationCall),
Assert(Global.group_size() == get_group_size(Btoi(num_guardians))),
Assert(sig_check(signatures, digest, keys)),
Approve()]
)
if __name__ == "__main__":
outfile = "teal/wormhole/build/vaa-verify.teal"
appid = 0
print("VAA Verify Stateless Program, (c) 2021-22 Randlabs Inc. ")
print("Compiling...")
if len(sys.argv) >= 2:
appid = sys.argv[1]
if len(sys.argv) >= 3:
outfile = sys.argv[2]
with open(outfile, "w") as f:
compiled = compileTeal(vaa_verify_program(
int(appid)), mode=Mode.Signature, version=5)
f.write(compiled)
print("Written to " + outfile)

View File

@ -0,0 +1,237 @@
Hand-testing guide
------------------
The nineteen sample guardian keys:
```
Key PK
------------------------------------------ ----------------------------------------------------------------
0x52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2 563d8d2fd4e701901d3846dee7ae7a92c18f1975195264d676f8407ac5976757
0x389A74E8FFa224aeAD0778c786163a7A2150768C 8d97f25916a755df1d9ef74eb4dbebc5f868cb07830527731e94478cdc2b9d5f
0xB4459EA6482D4aE574305B239B4f2264239e7599 9bd728ad7617c05c31382053b57658d4a8125684c0098f740a054d87ddc0e93b
0x072491bd66F63356090C11Aae8114F5372aBf12B 5a02c4cd110d20a83a7ce8d1a2b2ae5df252b4e5f6781c7855db5cc28ed2d1b4
0x51280eA1fd2B0A1c76Ae29a7d54dda68860A2bfF 93d4e3b443bf11f99a00901222c032bd5f63cf73fc1bcfa40829824d121be9b2
0xfa9Aa60CfF05e20E2CcAA784eE89A0A16C2057CB ea40e40c63c6ff155230da64a2c44fcd1f1c9e50cacb752c230f77771ce1d856
0xe42d59F8FCd86a1c5c4bA351bD251A5c5B05DF6A 87eaabe9c27a82198e618bca20f48f9679c0f239948dbd094005e262da33fe6a
0x4B07fF9D5cE1A6ed58b6e9e7d6974d1baBEc087e 61ffed2bff38648a6d36d6ed560b741b1ca53d45391441124f27e1e48ca04770
0xc8306B84235D7b0478c61783C50F990bfC44cFc0 bd12a242c6da318fef8f98002efb98efbf434218a78730a197d981bebaee826e
0xC8C1035110a13fe788259A4148F871b52bAbcb1B 20d3597bb16525b6d09e5fb56feb91b053d961ab156f4807e37d980f50e71aff
0x58A2508A20A7198E131503ce26bBE119aA8c62b2 344b313ffbc0199ff6ca08cacdaf5dc1d85221e2f2dc156a84245bd49b981673
0x8390820f04ddA22AFe03be1c3bb10f4ba6CF94A0 848b93264edd3f1a521274ca4da4632989eb5303fd15b14e5ec6bcaa91172b05
0x1FD6e97387C34a1F36DE0f8341E9D409E06ec45b c6f2046c1e6c172497fc23bd362104e2f4460d0f61984938fa16ef43f27d93f6
0x255a41fC2792209CB998A8287204D40996df9E54 693b256b1ee6b6fb353ba23274280e7166ab3be8c23c203cc76d716ba4bc32bf
0xbA663B12DD23fbF4FbAC618Be140727986B3BBd0 13c41508c0da03018d61427910b9922345ced25e2bbce50652e939ee6e5ea56d
0x79040E577aC50486d0F6930e160A5C75FD1203C6 460ee0ee403be7a4f1eb1c63dd1edaa815fbaa6cf0cf2344dcba4a8acf9aca74
0x3580D2F00309A9A85efFAf02564Fc183C0183A96 b25148579b99b18c8994b0b86e4dd586975a78fa6e7ad6ec89478d7fbafd2683
0x3869795913D3B6dBF3B24a1C7654672c69A23c35 90d7ac6a82166c908b8cf1b352f3c9340a8d1f2907d7146fb7cd6354a5436cca
0x1c0Cc52D7673c52DE99785741344662F5b2308a0 b71d23908e4cf5d6cd973394f3a4b6b164eb1065785feee612efdfd8d30005ed
------------------------------------------ ----------------------------------------------------------------
```
keys for tx0:
52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599072491bd66F63356090C11Aae8114F5372aBf12B51280eA1fd2B0A1c76Ae29a7d54dda68860A2bfFfa9Aa60CfF05e20E2CcAA784eE89A0A16C2057CB
keys for tx1:
e42d59F8FCd86a1c5c4bA351bD251A5c5B05DF6A4B07fF9D5cE1A6ed58b6e9e7d6974d1baBEc087ec8306B84235D7b0478c61783C50F990bfC44cFc0C8C1035110a13fe788259A4148F871b52bAbcb1B58A2508A20A7198E131503ce26bBE119aA8c62b28390820f04ddA22AFe03be1c3bb10f4ba6CF94A0
keys for tx2:
1FD6e97387C34a1F36DE0f8341E9D409E06ec45b255a41fC2792209CB998A8287204D40996df9E54bA663B12DD23fbF4FbAC618Be140727986B3BBd079040E577aC50486d0F6930e160A5C75FD1203C63580D2F00309A9A85efFAf02564Fc183C0183A963869795913D3B6dBF3B24a1C7654672c69A23c35
keys for tx3:
1c0Cc52D7673c52DE99785741344662F5b2308a0
563d8d2fd4e701901d3846dee7ae7a92c18f1975195264d676f8407ac5976757
8d97f25916a755df1d9ef74eb4dbebc5f868cb07830527731e94478cdc2b9d5f
9bd728ad7617c05c31382053b57658d4a8125684c0098f740a054d87ddc0e93b
5a02c4cd110d20a83a7ce8d1a2b2ae5df252b4e5f6781c7855db5cc28ed2d1b4
93d4e3b443bf11f99a00901222c032bd5f63cf73fc1bcfa40829824d121be9b2
ea40e40c63c6ff155230da64a2c44fcd1f1c9e50cacb752c230f77771ce1d856
87eaabe9c27a82198e618bca20f48f9679c0f239948dbd094005e262da33fe6a
61ffed2bff38648a6d36d6ed560b741b1ca53d45391441124f27e1e48ca04770
bd12a242c6da318fef8f98002efb98efbf434218a78730a197d981bebaee826e
20d3597bb16525b6d09e5fb56feb91b053d961ab156f4807e37d980f50e71aff
344b313ffbc0199ff6ca08cacdaf5dc1d85221e2f2dc156a84245bd49b981673
848b93264edd3f1a521274ca4da4632989eb5303fd15b14e5ec6bcaa91172b05
c6f2046c1e6c172497fc23bd362104e2f4460d0f61984938fa16ef43f27d93f6
693b256b1ee6b6fb353ba23274280e7166ab3be8c23c203cc76d716ba4bc32bf
13c41508c0da03018d61427910b9922345ced25e2bbce50652e939ee6e5ea56d
460ee0ee403be7a4f1eb1c63dd1edaa815fbaa6cf0cf2344dcba4a8acf9aca74
b25148579b99b18c8994b0b86e4dd586975a78fa6e7ad6ec89478d7fbafd2683
90d7ac6a82166c908b8cf1b352f3c9340a8d1f2907d7146fb7cd6354a5436cca
b71d23908e4cf5d6cd973394f3a4b6b164eb1065785feee612efdfd8d30005ed
003fe8e05b0d3594bbf0ab1da0110dded88930a181ace6089a2442a8e58b293b23777331d928ab36c85de11e6f2874c1cc12c418fc4e0c1e344864a8b85fda042e00
01791d7134fba47002376841fe688f7c478ba223580ec25ad5046a93db477d36fb4afa241ea95bf3c02b378a24220ff0f2ea035d088a0011bff9a4743d88f5c1b401
0281940f26308012efd7a307960223638abde4fb55abcaac04a9fa97bf92e5518e5903396bf7e807eb0e97e3009f7e679c0dcece45cd659ab6cf45fed9add2d6a101
03470cda5780ffb89118f152c449b4137f6c4f5413c4193d8a4169b31712d6c6583a90d34a31184cc5f3c8e8c987753a69ceadb2a46fcd31cd2db8fba4f918f52700
04376beb1f765fe3222cc3fc0a891f731a7c9cdb762b5997e8bd9e32e473c2cf8b63db7fbb06156ec90990e6edd39cf3402054c2ca34bbec6fc2ab1cbfe49c9a8600
05058e4f1150dcdba98b8054f99dfe75fa2c2c8f0c9b23a858c9e5abff85e535f317627ddf5ec51b43182b382811f8a52c7832be5c7c630eb45d9213a96989c25c01
0699f7fe9387cbc7c6528f7b7183042efb8d52f5e2811dc274c3e90141ff187fa21761f04e0d9b99f7bb40ad48709532c40b012de07d5253696aae4972ed1db21301
07bfcf86e950316e431874dc755acafdbaf9c28d62b3731f76abe2f7299add68d0629fc5df238856ba6ad1c9ab6a5ed3f0c43a350250005274bdadbc2c697eb63b01
08d69cae6a854c5468415c51747c9d7861ca5d5b164d100486c40477602a1c2e983da703866ffb2d3c9a642681e0c97c1ba8927d38b1d583c03a89d4f277a9a33900
097e82cad360d4bb4f71e74e2ce0bdc067c38a97bd000fb397c99dbed63013179000b47e534028300a99ba5f722877164341ab859f8e7c21f815a77d54fd78aba200
0ab009ea66dd2d7114952b3a667bd603110f08bd20ac03a79b672049e4a2f515b713527db7db0a3c13442ba8f2dad37cb255e4c660251cb96784ce7d385576eed501
0b5ef9003237297028d98779f43041bd3141b4219ffa5965cf806d23188bb0538f0639aaadcda9d62a402df3a48da7cae5cc25e1a129ba30cf08cf5ff4da49bd0c00
0cca7cd22e1514f0022666b35379f0685bfebbd5b80832d77eae6f57f52d351509093c433774d07ff6f3a4698331333a1dbb5478c4a51e20c15380d5dc68575f6600
0d525ac1524ec9d9ee623ef535a867e8f86d9b3f8e4c7b4234dbe7bb40dc8494327af2fa37c3db50064d6114f2e1441c4eee444b83636f11ce1f730f7b38490e2800
0e4528d8e7556ac14c74260f4ca5ed62c275324adec5a1146ac1abf6b41fcec88a24b4b797ed5370f648647904662e1fe2da2b4dea4327dfd2b94ca7080ed569f701
0f5c84b1ef2ff5938ecdfd7048b2323b3e3568b2e0a62c8c513f60a4dfce8ee48e3fc7409caad8be1185be42c8a5e81d1fa4c4c98f6f53cdcddab6add2384dc5f201
10cad08c66411cde321ce5b598ee4620e098e18a0427444c57923507064368912a3fab73a6b40dc050fbdaf340409583735a2528fde9b9b0322bd317f804b4767b00
11c17a151c7d37376a3f7ea45030a18c4e3791dc5e376c350fe7838548506f64ee19e946fcb1b258394c6b6964608fc0a9d6a5ef682b3faded66b214637220dab300
12af4f9015c9f11da3cb5457be96db960d49b37e59ec2bfce2b21dd2dfd28305f560e7977994a8380b7486361758a3eeace18aa1781bfcd79ad27995b41e504cd701
* Compile PyTEAL sources,
```
C:\src\PriceCasterService>python teal\wormhole\pyteal\vaa-processor.py vaap.teal vaap-clear.teal
VAA Processor Program, (c) 2021-22 Randlabs Inc.
Compiling approval program...
Written to vaap.teal
Compiling clear state program...
Written to vaap-clear.teal
```
* Copy compiled teal files to Sandbox (optional):
```
./sandbox copyTo /mnt/c/src/PriceCasterService/vaap.teal
Now copying /mnt/c/src/PriceCasterService/vaap.teal to Algod container in /opt/data//mnt/c/src/PriceCasterService/vaap.teal
./sandbox copyTo /mnt/c/src/PriceCasterService/vaap-clear.teal
Now copying /mnt/c/src/PriceCasterService/vaap-clear.teal to Algod container in /opt/data//mnt/c/src/PriceCasterService/vaap-clear.teal
```
* Execute `setvars` from scripts directory
```
source scripts/setvars.sh
```
* Make sure to clear previously created VAA Processor Apps, example:
```
goal account info -a OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU
Created Assets:
<none>
Held Assets:
ID 14704676, Wrapped Algo Testnet, balance 0.000000 wALGO Ts
Created Apps:
ID 45231352, global state used 2/2 uints, 20/20 byte slices
Opted In Apps:
ID 14713804, local state used 1/3 uints, 1/2 byte slices
scripts/deleteapp.sh 45231352
```
* Create the application and Check the deployed application ID according to the final TX ID.
```
scripts/createapp.sh
```
* Compile the stateless logic with the VAA Processor ID, for example:
```
python teal\wormhole\pyteal\vaa-verify.py <APP-ID> vaaverify.teal
goal clerk compile vaaverify.teal
vaaverify.teal: 4H2VD6GY4L7HEOVTZBKGTO6EYFASYFOWN34ONR5HIFEE2JIJ2M5GK26SXI
```
* Set the stateless program hash with the "setvphash" appcall:
```
source scripts/setvphash <APP-ID>
```
* To verify a sample VAA, you can use the testing library using Nodejs as follows:
```
Welcome to Node.js v14.17.6.
Type ".help" for more information.
> TestLib = require('./test/testlib')
{ TestLib: [class TestLib] }
> t = new TestLib.TestLib
TestLib {}
> sigkeys = ['563d8d2fd4e701901d3846dee7ae7a92c18f1975195264d676f8407ac5976757', '8d97f25916a755df1d9ef74eb4dbebc5f868cb07830527731e94478cdc2b9d5f', '9bd728ad7617c05c31382053b57658d4a8125684c0098f740a054d87ddc0e93b']
[
'563d8d2fd4e701901d3846dee7ae7a92c18f1975195264d676f8407ac5976757',
'8d97f25916a755df1d9ef74eb4dbebc5f868cb07830527731e94478cdc2b9d5f',
'9bd728ad7617c05c31382053b57658d4a8125684c0098f740a054d87ddc0e93b'
]
> t.createSignedVAA(0, sigkeys, 1, 1, 1, '0x71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b', 0, 0, '0x12345678')
'0100000000030025a2cec435380f6413e8b5d5531cd8789322a1d8bc488309bb868c33a26cc9492947b48895460d8d2261d669bcef210987cc5eeb9fa21504c3f5a9b5a0ff32df0001ee4d1a5e589b5aa0d4787eaf57ba4b41e6a54e35e8ca60a028a0f1e35db3a8ed5d901a9831272fc117f472fcd0115d31365efd575a19a28eaf5ad9be7cf5f0d90102a671b7c2af66aa6bff3337adaa7e5f196630508f85491e650cfdaccd2f67d2a605faf1c267eddaa50ac6de8d35894afce7974f14982f6173b0d020e0567f2a4a0100000001000000010001000000000000000000000000000000000000000000000000000000000000ffff00000000000000000012345678'
```
The resulting decomposed in fields VAA is:
```
01 Version
00000000 Guardian-set-index
03 Signature count
sig indexes + signatures:
00
25a2cec435380f6413e8b5d5531cd8789322a1d8bc488309bb868c33a26cc9492947b48895460d8d2261d669bcef210987cc5eeb9fa21504c3f5a9b5a0ff32df00
01
ee4d1a5e589b5aa0d4787eaf57ba4b41e6a54e35e8ca60a028a0f1e35db3a8ed5d901a9831272fc117f472fcd0115d31365efd575a19a28eaf5ad9be7cf5f0d901
02
a671b7c2af66aa6bff3337adaa7e5f196630508f85491e650cfdaccd2f67d2a605faf1c267eddaa50ac6de8d35894afce7974f14982f6173b0d020e0567f2a4a01
00000001 timestamp
00000001 nonce
0001 chain-id
71f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b emitterAddress
0000000000000000 sequence
00 consistency-level
payload:
12345678
```
VAA Body:
0000000100000001000171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b00000000000000010012345678
Since there are three signers, VAA can be verified in a group transaction with just one step.
Stateless logic accepts signature subset as argument (encoded in base64).
```
export SIGNATURES64=`node -e "console.log(Buffer.from('25a2cec435380f6413e8b5d5531cd8789322a1d8bc488309bb868c33a26cc9492947b48895460d8d2261d669bcef210987cc5eeb9fa21504c3f5a9b5a0ff32df00ee4d1a5e589b5aa0d4787eaf57ba4b41e6a54e35e8ca60a028a0f1e35db3a8ed5d901a9831272fc117f472fcd0115d31365efd575a19a28eaf5ad9be7cf5f0d901a671b7c2af66aa6bff3337adaa7e5f196630508f85491e650cfdaccd2f67d2a605faf1c267eddaa50ac6de8d35894afce7974f14982f6173b0d020e0567f2a4a01','hex').toString('base64'))"`
export VAABODY=`0000000100000001000171f8dcb863d176e2c420ad6610cf687359612b6fb392e0642b0ca6b1f186aa3b00000000000000010012345678`
export VAABODY64=`node -e "console.log(Buffer.from('$VAABODY64', 'hex').toString('base64'))"`
export STATELESS_ADDR=4H2VD6GY4L7HEOVTZBKGTO6EYFASYFOWN34ONR5HIFEE2JIJ2M5GK26SXI
export GUARDIAN_KEYS='52A26Ce40F8CAa8D36155d37ef0D5D783fc614d2389A74E8FFa224aeAD0778c786163a7A2150768CB4459EA6482D4aE574305B239B4f2264239e7599'
export GKEYSBASE64=`node -e "console.log(Buffer.from('$GUARDIAN_KEYS', 'hex').toString('base64'))"`
goal app call --app-id 45504480 --from "$STATELESS_ADDR" --app-arg "str:verify" --app-arg "b64:$GKEYSBASE64" --app-arg "int:3" --noteb64 "$VAABODY" -o verify.txn
```
00 3fe8e05b0d3594bbf0ab1da0110dded88930a181ace6089a2442a8e58b293b23777331d928ab36c85de11e6f2874c1cc12c418fc4e0c1e344864a8b85fda042e00
01 791d7134fba47002376841fe688f7c478ba223580ec25ad5046a93db477d36fb 4afa241ea95bf3c02b378a24220ff0f2ea035d088a0011bff9a4743d88f5c1b401
02 81940f26308012efd7a307960223638abde4fb55abcaac04a9fa97bf92e5518e5903396bf7e807eb0e97e3009f7e679c0dcece45cd659ab6cf45fed9add2d6a10
52a26ce40f8caa8d36155d37ef0d5d783fc614d2
389a74e8ffa224aead0778c786163a7a2150768c
b4459ea6482d4ae574305b239b4f2264239e7599

View File

View File

@ -0,0 +1,139 @@
const PricecasterLib = require('../lib/pricecaster')
const tools = require('../tools/app-tools')
const algosdk = require('algosdk')
const { expect } = require('chai')
const chai = require('chai')
chai.use(require('chai-as-promised'))
// Test general configuration for Betanet
const VALIDATOR_ADDR = 'OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU'
const VALIDATOR_MNEMO = 'assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
const OTHER_ADDR = 'DMTBK62XZ6KNI7L5E6TRBTPB4B3YNVB4WYGSWR42SEV4XKV4LYHGBW4O34'
const OTHER_MNEMO = 'old agree harbor cost pink fog chunk hope vital used rural soccer model acquire clown host friend bring marriage surge dirt surge slab absent punch'
const SIGNATURES = {}
SIGNATURES[VALIDATOR_ADDR] = algosdk.mnemonicToSecretKey(VALIDATOR_MNEMO)
SIGNATURES[OTHER_ADDR] = algosdk.mnemonicToSecretKey(OTHER_MNEMO)
const VALID_SYMBOL = 'BTC/USD '
const VALID_PRICE = BigInt(485265555)
const VALID_EXPONENT = BigInt(4)
const VALID_CONF = BigInt(1400000)
const VALID_SLOT = BigInt(104566700)
function signCallback (sender, tx) {
const txSigned = tx.signTxn(SIGNATURES[sender].sk)
return txSigned
}
describe('Price-Keeper contract tests', function () {
let pclib
let algodClient
let appId
let lastTs
before(async function () {
algodClient = new algosdk.Algodv2('', 'https://api.betanet.algoexplorer.io', '')
pclib = new PricecasterLib.PricecasterLib(algodClient)
console.log('Clearing accounts of all previous apps...')
const appsTo = await tools.readCreatedApps(algodClient, VALIDATOR_ADDR)
for (let i = 0; i < appsTo.length; i++) {
console.log('Clearing ' + appsTo[i].id)
try {
const txId = await pclib.deleteApp(VALIDATOR_ADDR, signCallback, appsTo[i].id)
await pclib.waitForConfirmation(txId)
} catch (e) {
console.error('Could not delete application! Reason: ' + e)
}
}
console.log('Creating new app...')
const txId = await pclib.createApp(VALIDATOR_ADDR, VALIDATOR_ADDR, VALID_SYMBOL, signCallback)
const txResponse = await pclib.waitForTransactionResponse(txId)
appId = pclib.appIdFromCreateAppResponse(txResponse)
pclib.setAppId(appId)
console.log('App Id: %d', appId)
})
it('Must create app with proper initial global state', async function () {
const stVAddr = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'vaddr')
const stSym = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'sym')
expect(Buffer.from(stSym, 'base64').toString()).to.equal(VALID_SYMBOL)
expect(stVAddr.toString()).to.equal(VALIDATOR_ADDR)
})
it('Must accept valid message and store data', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk)
const txid = await pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)
expect(txid).to.have.length(52)
await pclib.waitForTransactionResponse(txid)
// console.log(await tools.printAppGlobalState(algodClient, appId, VALIDATOR_ADDR))
const stPrice = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'price')
const stExp = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'exp')
const stConf = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'conf')
const stSlot = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'slot')
expect(stPrice.toString()).to.equal(VALID_PRICE.toString())
expect((Buffer.from(stExp, 'base64')).readBigInt64BE()).to.equal(VALID_EXPONENT)
expect(stSlot.toString()).to.equal(VALID_SLOT.toString())
expect(stConf.toString()).to.equal(VALID_CONF.toString())
})
it('Must accept second message with different price', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE + BigInt(400), VALID_EXPONENT + BigInt(3), VALID_CONF + BigInt(2), VALID_SLOT + BigInt(100), SIGNATURES[VALIDATOR_ADDR].sk)
const txid = await pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)
expect(txid).to.have.length(52)
await pclib.waitForTransactionResponse(txid)
const stPrice = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'price')
const stExp = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'exp')
const stConf = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'conf')
const stSlot = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'slot')
expect(stPrice.toString()).to.equal((VALID_PRICE + BigInt(400)).toString())
expect((Buffer.from(stExp, 'base64')).readBigInt64BE()).to.equal(VALID_EXPONENT + BigInt(3))
expect(stSlot.toString()).to.equal((VALID_SLOT + BigInt(100)).toString())
expect(stConf.toString()).to.equal((VALID_CONF + BigInt(2)).toString())
lastTs = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'ts')
})
it('Must accept negative exponent, stored as 2-complement 64bit', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, BigInt(-9), VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk)
const txid = await pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)
expect(txid).to.have.length(52)
await pclib.waitForTransactionResponse(txid)
const stExp = await tools.readAppGlobalStateByKey(algodClient, appId, VALIDATOR_ADDR, 'exp')
const bufExp = Buffer.from(stExp, 'base64')
const val = bufExp.readBigInt64BE()
expect(val.toString()).to.equal('-9')
})
it('Must reject non-validator as signer', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[OTHER_ADDR].sk)
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject non-validator as sender', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk)
await expect(pclib.submitMessage(OTHER_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject future timestamp', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk, undefined, undefined, undefined, BigInt(lastTs + 200))
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject old timestamp', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk, undefined, undefined, undefined, BigInt(lastTs - 999999))
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject zero-priced message', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, BigInt(0), VALID_EXPONENT, VALID_CONF, VALID_SLOT, SIGNATURES[VALIDATOR_ADDR].sk)
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject zero slot', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, BigInt(0), SIGNATURES[VALIDATOR_ADDR].sk)
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject bad header', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, BigInt(0), SIGNATURES[VALIDATOR_ADDR].sk, 'BADHEADER')
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject bad destination appId', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, BigInt(0), SIGNATURES[VALIDATOR_ADDR].sk, undefined, BigInt(100))
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject bad message version', async function () {
const msgBuffer = pclib.createMessage(VALID_SYMBOL, VALID_PRICE, VALID_EXPONENT, VALID_CONF, BigInt(0), SIGNATURES[VALIDATOR_ADDR].sk, undefined, undefined, 0)
await expect(pclib.submitMessage(VALIDATOR_ADDR, msgBuffer, signCallback)).to.be.rejectedWith('Bad Request')
})
})

View File

@ -0,0 +1 @@
dummy file

View File

@ -0,0 +1,90 @@
/**
*
* Pricecaster Testing Library.
* (c) 2021-22 Randlabs, Inc.
*
*/
const web3EthAbi = require('web3-eth-abi')
const web3Utils = require('web3-utils')
const elliptic = require('elliptic')
class TestLib {
/**
* Create a packed and signed VAA for testing.
* See https://github.com/certusone/wormhole/blob/dev.v2/design/0001_generic_message_passing.md
*
* @param {} guardianSetIndex The guardian set index
* @param {*} signers The list of private keys for signing the VAA
* @param {*} timestamp The timestamp of VAA
* @param {*} nonce The nonce.
* @param {*} emitterChainId The emitter chain identifier
* @param {*} emitterAddress The emitter chain address, prefixed with 0x
* @param {*} sequence The sequence.
* @param {*} consistencyLevel The reported consistency level
* @param {*} payload This VAA Payload hex string, prefixed with 0x
*/
createSignedVAA (guardianSetIndex,
signers,
timestamp,
nonce,
emitterChainId,
emitterAddress,
sequence,
consistencyLevel,
payload) {
const body = [
web3EthAbi.encodeParameter('uint32', timestamp).substring(2 + (64 - 8)),
web3EthAbi.encodeParameter('uint32', nonce).substring(2 + (64 - 8)),
web3EthAbi.encodeParameter('uint16', emitterChainId).substring(2 + (64 - 4)),
web3EthAbi.encodeParameter('bytes32', emitterAddress).substring(2),
web3EthAbi.encodeParameter('uint64', sequence).substring(2 + (64 - 16)),
web3EthAbi.encodeParameter('uint8', consistencyLevel).substring(2 + (64 - 2)),
payload.substr(2)
]
const hash = web3Utils.keccak256('0x' + body.join(''))
console.log('VAA body Hash: ', hash)
let signatures = ''
for (const i in signers) {
// eslint-disable-next-line new-cap
const ec = new elliptic.ec('secp256k1')
const key = ec.keyFromPrivate(signers[i])
const signature = key.sign(hash.substr(2), { canonical: true })
const packSig = [
web3EthAbi.encodeParameter('uint8', i).substring(2 + (64 - 2)),
this.zeroPadBytes(signature.r.toString(16), 32),
this.zeroPadBytes(signature.s.toString(16), 32),
web3EthAbi.encodeParameter('uint8', signature.recoveryParam).substr(2 + (64 - 2))
]
signatures += packSig.join('')
}
const vm = [
web3EthAbi.encodeParameter('uint8', 1).substring(2 + (64 - 2)),
web3EthAbi.encodeParameter('uint32', guardianSetIndex).substring(2 + (64 - 8)),
web3EthAbi.encodeParameter('uint8', signers.length).substring(2 + (64 - 2)),
signatures,
body.join('')
].join('')
return vm
}
zeroPadBytes (value, length) {
while (value.length < 2 * length) {
value = '0' + value
}
return value
}
}
module.exports = {
TestLib
}

View File

@ -0,0 +1,211 @@
/* eslint-disable no-unused-expressions */
const PricecasterLib = require('../lib/pricecaster')
const tools = require('../tools/app-tools')
const algosdk = require('algosdk')
const { expect } = require('chai')
const chai = require('chai')
chai.use(require('chai-as-promised'))
const spawnSync = require('child_process').spawnSync
const fs = require('fs')
let pclib
let algodClient
const OWNER_ADDR = 'OPDM7ACAW64Q4VBWAL77Z5SHSJVZZ44V3BAN7W44U43SUXEOUENZMZYOQU'
const OWNER_MNEMO = 'assault approve result rare float sugar power float soul kind galaxy edit unusual pretty tone tilt net range pelican avoid unhappy amused recycle abstract master'
const OTHER_ADDR = 'DMTBK62XZ6KNI7L5E6TRBTPB4B3YNVB4WYGSWR42SEV4XKV4LYHGBW4O34'
const OTHER_MNEMO = 'old agree harbor cost pink fog chunk hope vital used rural soccer model acquire clown host friend bring marriage surge dirt surge slab absent punch'
const SIGNATURES = {}
SIGNATURES[OWNER_ADDR] = algosdk.mnemonicToSecretKey(OWNER_MNEMO)
SIGNATURES[OTHER_ADDR] = algosdk.mnemonicToSecretKey(OTHER_MNEMO)
const gkeys = [
'13947Bd48b18E53fdAeEe77F3473391aC727C638',
'F18AbBac073741DD0F002147B735Ff642f3D113F',
'9925A94DC043D0803f8ef502D2dB15cAc9e02D76',
'9e4EC2D92af8602bCE74a27F99A836f93C4a31E4',
'9C40c4052A3092AfB8C99B985fcDfB586Ed19c98',
'B86020cF1262AA4dd5572Af76923E271169a2CA7',
'1937617fE1eD801fBa14Bd8BB9EDEcBA7A942FFe',
'9475b8D45DdE53614d92c779787C27fE2ef68752',
'15A53B22c28AbC7B108612146B6aAa4a537bA305',
'63842657C7aC7e37B04FBE76b8c54EFe014D04E1',
'948ca1bBF4B858DF1A505b4C69c5c61bD95A12Bd',
'A6923e2259F8B5541eD18e410b8DdEE618337ff0',
'F678Daf4b7f2789AA88A081618Aa966D6a39e064',
'8cF31021838A8B3fFA43a71a50609877846f9E6d',
'eB15bCF2ae4f957012330B4741ecE3242De96184',
'cc3766a03e4faec44Bda7a46D9Ea2A9D124e9Bf8',
'841f499Ba89a6a8E9dD273BAd82Beb175094E5d7',
'f5F2b82576e6CA17965dee853d08bbB471FA2433',
'2bC2B1204599D4cA0d4Dde4a658a42c4dD13103a'
]
function makeVAA () {
}
async function createApp (gsexptime, gkeys) {
const txId = await pclib.createVaaProcessorApp(OWNER_ADDR, gsexptime, gkeys.join(''), signCallback)
const txResponse = await pclib.waitForTransactionResponse(txId)
const appId = pclib.appIdFromCreateAppResponse(txResponse)
pclib.setAppId(appId)
return appId
}
function signCallback (sender, tx) {
const txSigned = tx.signTxn(SIGNATURES[sender].sk)
return txSigned
}
describe('VAA Processor Smart-contract Tests', function () {
let appId
before(async function () {
algodClient = new algosdk.Algodv2('', 'https://api.testnet.algoexplorer.io', '')
pclib = new PricecasterLib.PricecasterLib(algodClient)
console.log('Clearing accounts of all previous apps...')
const appsTo = await tools.readCreatedApps(algodClient, OWNER_ADDR)
for (let i = 0; i < appsTo.length; i++) {
console.log('Clearing ' + appsTo[i].id)
try {
const txId = await pclib.deleteApp(OWNER_ADDR, signCallback, appsTo[i].id)
await pclib.waitForConfirmation(txId)
} catch (e) {
console.error('Could not delete application! Reason: ' + e)
}
}
const vaaProcessorClearState = 'test/temp/vaa-clear-state.teal'
const vaaProcessorApproval = 'test/temp/vaa-processor.teal'
pclib.setVaaProcessorApprovalFile(vaaProcessorApproval)
pclib.setVaaProcessorClearStateFile(vaaProcessorClearState)
console.log(spawnSync('python', ['teal/wormhole/pyteal/vaa-processor.py', vaaProcessorApproval, vaaProcessorClearState]).output.toString())
}
)
it('Must fail to create app with incorrect guardian keys length', async function () {
const gsexptime = 2524618800
await expect(createApp(gsexptime, ['BADADDRESS'])).to.be.rejectedWith('Bad Request')
})
it('Must create app with initial guardians and proper initial state', async function () {
const gsexptime = 2524618800
appId = await createApp(gsexptime, gkeys)
console.log(' [Created appId: %d]', appId)
const gscount = await tools.readAppGlobalStateByKey(algodClient, appId, OWNER_ADDR, 'gscount')
const gsexp = await tools.readAppGlobalStateByKey(algodClient, appId, OWNER_ADDR, 'gsexp')
expect(gscount.toString()).to.equal((gkeys.length).toString())
expect(gsexp.toString()).to.equal(gsexptime.toString())
let i = 0
const buf = Buffer.alloc(8)
for (const gk of gkeys) {
buf.writeBigUint64BE(BigInt(i++))
const gkstate = await tools.readAppGlobalStateByKey(algodClient, appId, OWNER_ADDR, buf.toString())
expect(Buffer.from(gkstate, 'base64').toString('hex')).to.equal(gk.toLowerCase())
}
})
it('Must set stateless logic hash from owner', async function () {
const teal = 'test/temp/vaa-verify.teal'
spawnSync('python', ['teal/wormhole/pyteal/vaa-verify.py', appId, teal])
const program = fs.readFileSync(teal, 'utf8')
const compiledProgram = await pclib.compileProgram(program)
const txid = await pclib.setVAAVerifyProgramHash(OWNER_ADDR, compiledProgram.hash, signCallback)
await pclib.waitForTransactionResponse(txid)
const vphstate = await tools.readAppGlobalStateByKey(algodClient, appId, OWNER_ADDR, 'vphash')
expect(vphstate).to.equal(compiledProgram.hash)
})
it('Must disallow setting stateless logic hash from non-owner', async function () {
const teal = 'test/temp/vaa-verify.teal'
spawnSync('python', ['teal/wormhole/pyteal/vaa-verify.py', appId, teal])
const program = fs.readFileSync(teal, 'utf8')
const compiledProgram = await pclib.compileProgram(program)
await expect(pclib.setVAAVerifyProgramHash(OTHER_ADDR, compiledProgram.hash, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject setting stateless logic hash from group transaction', async function () {
const teal = 'test/temp/vaa-verify.teal'
spawnSync('python', ['teal/wormhole/pyteal/vaa-verify.py', appId, teal])
const program = fs.readFileSync(teal, 'utf8')
const compiledProgram = await pclib.compileProgram(program)
const hash = algosdk.decodeAddress(compiledProgram.hash).publicKey
const appArgs = [new Uint8Array(Buffer.from('setvphash')), hash.subarray(0, 10)]
const params = await algodClient.getTransactionParams().do()
params.fee = 1000
params.flatFee = true
pclib.beginTxGroup()
const appTx = algosdk.makeApplicationNoOpTxn(OWNER_ADDR, params, this.appId, appArgs)
const dummyTx = algosdk.makeApplicationNoOpTxn(OWNER_ADDR, params, this.appId, appArgs)
pclib.addTxToGroup(appTx)
pclib.addTxToGroup(dummyTx)
await expect(pclib.commitTxGroup(OWNER_ADDR, signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must reject setting stateless logic hash with invalid address length', async function () {
const teal = 'test/temp/vaa-verify.teal'
spawnSync('python', ['teal/wormhole/pyteal/vaa-verify.py', appId, teal])
const program = fs.readFileSync(teal, 'utf8')
const compiledProgram = await pclib.compileProgram(program)
const hash = algosdk.decodeAddress(compiledProgram.hash).publicKey
const appArgs = [new Uint8Array(Buffer.from('setvphash')), hash.subarray(0, 10)]
await expect(pclib.callApp(OWNER_ADDR, appArgs, [], signCallback)).to.be.rejectedWith('Bad Request')
})
it('Must verify and handle Pyth VAA', async function () {
})
it('Must verify and handle governance VAA', async function () {
})
it('Must reject unknown VAA', async function () {
})
it('Must reject incorrect transaction group size', async function () {
})
it('Must reject incorrect argument count for verify call', async function () {
})
it('Must reject unknown sender for verify call', async function () {
})
it('Must reject guardian set count argument not matching global state', async function () {
})
it('Must reject guardian key list argument not matching global state', async function () {
})
it('Must reject non-app call transaction in group', async function () {
})
it('Must reject app-call with mismatched AppId in group', async function () {
})
it('Must reject transaction with not verified bit set in group', async function () {
})
it('Stateless: Must reject transaction with excess fee', async function () {
})
it('Stateless: Must reject incorrect number of logic program arguments', async function () {
})
it('Stateless: Must reject transaction with mismatching number of signatures', async function () {
})
it('Stateless: Must reject transaction with non-zero rekey', async function () {
})
it('Stateless: Must reject transaction call from bad app-id', async function () {
})
it('Stateless: Must reject non-app call tx type', async function () {
})
it('Stateless: Must reject invalid group size', async function () {
})
it('Stateless: Must reject signature verification failure', async function () {
})
})

View File

@ -0,0 +1,270 @@
/*************************************************************************
* [2018] - [2020] Rand Labs Inc.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Rand Labs Inc.
* The intellectual and technical concepts contained
* herein are proprietary to Rand Labs Inc.
*/
const sha512 = require('js-sha512')
const hibase32 = require('hi-base32')
const ALGORAND_ADDRESS_SIZE = 58
function timeoutPromise (ms, promise) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('promise timeout'))
}, ms)
promise.then(
(res) => {
clearTimeout(timeoutId)
resolve(res)
},
(err) => {
clearTimeout(timeoutId)
reject(err)
}
)
})
}
function getInt64Bytes (x, len) {
if (!len) {
len = 8
}
const bytes = new Uint8Array(len)
do {
len -= 1
// eslint-disable-next-line no-bitwise
bytes[len] = x & (255)
// eslint-disable-next-line no-bitwise
x >>= 8
} while (len)
return bytes
}
function addressFromByteBuffer (addr) {
const bytes = Buffer.from(addr, 'base64')
// compute checksum
const checksum = sha512.sha512_256.array(bytes).slice(28, 32)
const c = new Uint8Array(bytes.length + checksum.length)
c.set(bytes)
c.set(checksum, bytes.length)
const v = hibase32.encode(c)
return v.toString().slice(0, ALGORAND_ADDRESS_SIZE)
}
function printAppCallDeltaArray (deltaArray) {
for (let i = 0; i < deltaArray.length; i++) {
if (deltaArray[i].address) {
console.log('Local state change address: ' + deltaArray[i].address)
for (let j = 0; j < deltaArray[i].delta.length; j++) {
printAppCallDelta(deltaArray[i].delta[j])
}
} else {
console.log('Global state change')
printAppCallDelta(deltaArray[i])
}
}
}
function printAppStateArray (stateArray) {
for (let n = 0; n < stateArray.length; n++) {
printAppState(stateArray[n])
}
}
function appValueState (stateValue) {
let text = ''
if (stateValue.type == 1) {
const addr = addressFromByteBuffer(stateValue.bytes)
if (addr.length == ALGORAND_ADDRESS_SIZE) {
text += addr
} else {
text += stateValue.bytes
}
} else if (stateValue.type == 2) {
text = stateValue.uint
} else {
text += stateValue.bytes
}
return text
}
function appValueStateString (stateValue) {
let text = ''
if (stateValue.type == 1) {
const addr = addressFromByteBuffer(stateValue.bytes)
if (addr.length == ALGORAND_ADDRESS_SIZE) {
text += addr
} else {
text += stateValue.bytes
}
} else if (stateValue.type == 2) {
text += stateValue.uint
} else {
text += stateValue.bytes
}
return text
}
function printAppState (state) {
let text = Buffer.from(state.key, 'base64').toString() + ': '
text += appValueStateString(state.value)
console.log(text)
}
async function printAppLocalState (algodClient, appId, accountAddr) {
const ret = await readAppLocalState(algodClient, appId, accountAddr)
if (ret) {
console.log('Application %d local state for account %s:', appId, accountAddr)
printAppStateArray(ret)
}
}
async function printAppGlobalState (algodClient, appId, accountAddr) {
const ret = await readAppGlobalState(algodClient, appId, accountAddr)
if (ret) {
console.log('Application %d global state:', appId)
printAppStateArray(ret)
}
}
async function readCreatedApps (algodClient, accountAddr) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
return accountInfoResponse['created-apps']
}
async function readOptedInApps (algodClient, accountAddr) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
return accountInfoResponse['apps-local-state']
}
// read global state of application
async function readAppGlobalState (algodClient, appId, accountAddr) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
for (let i = 0; i < accountInfoResponse['created-apps'].length; i++) {
if (accountInfoResponse['created-apps'][i].id === appId) {
const globalState = accountInfoResponse['created-apps'][i].params['global-state']
return globalState
}
}
}
async function readAppGlobalStateByKey (algodClient, appId, accountAddr, key) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
for (let i = 0; i < accountInfoResponse['created-apps'].length; i++) {
if (accountInfoResponse['created-apps'][i].id === appId) {
// console.log("Application's global state:")
const stateArray = accountInfoResponse['created-apps'][i].params['global-state']
for (let j = 0; j < stateArray.length; j++) {
const text = Buffer.from(stateArray[j].key, 'base64').toString()
if (key === text) {
return appValueState(stateArray[j].value)
}
}
}
}
}
// read local state of application from user account
async function readAppLocalState (algodClient, appId, accountAddr) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
for (let i = 0; i < accountInfoResponse['apps-local-state'].length; i++) {
if (accountInfoResponse['apps-local-state'][i].id === appId) {
// console.log(accountAddr + " opted in, local state:")
if (accountInfoResponse['apps-local-state'][i]['key-value']) {
return accountInfoResponse['apps-local-state'][i]['key-value']
}
}
}
}
async function readAppLocalStateByKey (algodClient, appId, accountAddr, key) {
const accountInfoResponse = await algodClient.accountInformation(accountAddr).do()
for (let i = 0; i < accountInfoResponse['apps-local-state'].length; i++) {
if (accountInfoResponse['apps-local-state'][i].id === appId) {
const stateArray = accountInfoResponse['apps-local-state'][i]['key-value']
if (!stateArray) {
return null
}
for (let j = 0; j < stateArray.length; j++) {
const text = Buffer.from(stateArray[j].key, 'base64').toString()
if (key === text) {
return appValueState(stateArray[j].value)
}
}
// not found assume 0
return 0
}
}
}
function uintArray8ToString (byteArray) {
return Array.from(byteArray, function (byte) {
// eslint-disable-next-line no-bitwise
return ('0' + (byte & 0xFF).toString(16)).slice(-2)
}).join('')
}
/**
* Verify if transactionResponse has any information about a transaction local or global state change.
* @param {Object} transactionResponse object containing the transaction response of an application call
* @return {Boolean} returns true if there is a local or global delta meanining that
* the transaction made a change in the local or global state
*/
function anyAppCallDelta (transactionResponse) {
return (transactionResponse['global-state-delta'] || transactionResponse['local-state-delta'])
}
/**
* Print to stdout the changes introduced by the transaction that generated the transactionResponse if any.
* @param {Object} transactionResponse object containing the transaction response of an application call
* @return {void}
*/
function printAppCallDelta (transactionResponse) {
if (transactionResponse['global-state-delta'] !== undefined) {
console.log('Global State updated:')
printAppCallDeltaArray(transactionResponse['global-state-delta'])
}
if (transactionResponse['local-state-delta'] !== undefined) {
console.log('Local State updated:')
printAppCallDeltaArray(transactionResponse['local-state-delta'])
}
}
module.exports = {
timeoutPromise,
getInt64Bytes,
addressFromByteBuffer,
printAppStateArray,
printAppState,
printAppLocalState,
printAppGlobalState,
readCreatedApps,
readOptedInApps,
readAppGlobalState,
readAppGlobalStateByKey,
readAppLocalState,
readAppLocalStateByKey,
uintArray8ToString,
anyAppCallDelta,
printAppCallDelta
}

View File

@ -0,0 +1,103 @@
/* eslint-disable linebreak-style */
const algosdk = require('algosdk')
const { exit } = require('process')
const readline = require('readline')
const PricecasterLib = require('../lib/pricecaster')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const spawnSync = require('child_process').spawnSync
const fs = require('fs')
function ask (questionText) {
return new Promise((resolve) => {
rl.question(questionText, input => resolve(input))
})
}
let globalMnemo = ''
function signCallback (sender, tx) {
const txSigned = tx.signTxn(algosdk.mnemonicToSecretKey(globalMnemo).sk)
return txSigned
}
async function startOp (algodClient, fromAddress, gexpTime, gkeys) {
console.log('Compiling VAA Processor program code...')
const out = spawnSync('python', ['teal/wormhole/pyteal/vaa-processor.py'])
console.log(out.output.toString())
// console.log('Compiling VAA Verify stateless program code...')
// out = spawnSync('python', ['teal/wormhole/pyteal/vaa-verify.py'])
// console.log(out.output.toString())
const pclib = new PricecasterLib.PricecasterLib(algodClient)
console.log('Creating new app...')
const txId = await pclib.createVaaProcessorApp(fromAddress, gexpTime, gkeys.join(''), signCallback)
console.log('txId: ' + txId)
const txResponse = await pclib.waitForTransactionResponse(txId)
const appId = pclib.appIdFromCreateAppResponse(txResponse)
console.log('Deployment App Id: %d', appId)
}
(async () => {
console.log('\nVAA Processor for Wormhole Deployment Tool -- (c)2021-22 Randlabs, Inc.')
console.log('-----------------------------------------------------------------------\n')
if (process.argv.length !== 6) {
console.log('Usage: deploy <glistfile> <from> <network>\n')
console.log('where:\n')
console.log('glistfile File containing the initial list of guardians')
console.log('gexptime Guardian set expiration time')
console.log('from Deployer account')
console.log('network Testnet, betanet or mainnet')
console.log('\nFile must contain one guardian key per line, formatted in hex, without hex prefix.')
exit(0)
}
const listfile = process.argv[2]
const gexpTime = process.argv[3]
const fromAddress = process.argv[4]
const network = process.argv[5]
const config = { server: '', apiToken: '', port: '' }
if (network === 'betanet') {
config.server = 'https://api.betanet.algoexplorer.io'
} else if (network === 'mainnet') {
config.server = 'https://api.algoexplorer.io'
} else if (network === 'testnet') {
config.server = 'https://api.testnet.algoexplorer.io'
} else {
console.error('Invalid network: ' + network)
exit(1)
}
const fileDataStr = fs.readFileSync(listfile).toString()
const gkeys = fileDataStr.match(/[^\r\n]+/g)
if (!algosdk.isValidAddress(fromAddress)) {
console.error('Invalid deployer address: ' + fromAddress)
exit(1)
}
const algodClient = new algosdk.Algodv2(config.apiToken, config.server, config.port)
console.log('Parameters for deployment: ')
console.log('From: ' + fromAddress)
console.log('Network: ' + network)
console.log('Guardian expiration time: ' + gexpTime)
console.log(`Guardian Keys: (${gkeys.length}) ` + gkeys)
const answer = await ask('\nEnter YES to confirm parameters, anything else to abort. ')
if (answer !== 'YES') {
console.warn('Aborted by user.')
exit(1)
}
globalMnemo = await ask('\nEnter mnemonic for sender account.\nBE SURE TO DO THIS FROM A SECURED SYSTEM\n')
try {
await startOp(algodClient, fromAddress, gexpTime, gkeys)
} catch (e) {
console.error('(!) Deployment Failed: ' + e.toString())
}
console.log('Bye.')
exit(0)
})()

View File

@ -0,0 +1,91 @@
/* eslint-disable linebreak-style */
const algosdk = require('algosdk')
const { exit } = require('process')
const readline = require('readline')
const PricecasterLib = require('../lib/pricecaster')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
function ask (questionText) {
return new Promise((resolve) => {
rl.question(questionText, input => resolve(input))
})
}
let globalMnemo = ''
function signCallback (sender, tx) {
const txSigned = tx.signTxn(algosdk.mnemonicToSecretKey(globalMnemo).sk)
return txSigned
}
async function startOp (algodClient, symbol, vaddr, fromAddress) {
const pclib = new PricecasterLib.PricecasterLib(algodClient)
console.log('Creating new app...')
const txId = await pclib.createApp(fromAddress, vaddr, symbol, signCallback)
console.log('txId: ' + txId)
const txResponse = await pclib.waitForTransactionResponse(txId)
const appId = pclib.appIdFromCreateAppResponse(txResponse)
console.log('Deployment App Id: %d', appId)
}
(async () => {
console.log('\nPricekeeper Deployment Tool -- (c)2021-22 Randlabs, Inc.')
console.log('----------------------------------------------------------\n')
if (process.argv.length !== 6) {
console.log('Usage: deploy <symbol> <vaddr> <from> <network>\n')
console.log('where:\n')
console.log('symbol The supported symbol for this priceKeeper (e.g BTC/USD)')
console.log('vaddr The validator address')
console.log('from Deployer account')
console.log('network Testnet, betanet or mainnet')
exit(0)
}
const symbol = process.argv[2]
const vaddr = process.argv[3]
const fromAddress = process.argv[4]
const network = process.argv[5]
const config = { server: '', apiToken: '', port: '' }
if (network === 'betanet') {
config.server = 'https://api.betanet.algoexplorer.io'
} else if (network === 'mainnet') {
config.server = 'https://api.algoexplorer.io'
} else if (network === 'testnet') {
config.server = 'https://api.testnet.algoexplorer.io'
} else {
console.error('Invalid network: ' + network)
exit(1)
}
if (!algosdk.isValidAddress(vaddr)) {
console.error('Invalid validator address: ' + vaddr)
exit(1)
}
if (!algosdk.isValidAddress(fromAddress)) {
console.error('Invalid deployer address: ' + fromAddress)
exit(1)
}
const algodClient = new algosdk.Algodv2(config.apiToken, config.server, config.port)
console.log('Parameters for deployment: ')
console.log('symbol: ' + symbol)
console.log('Validator addr: ' + vaddr)
console.log('From: ' + fromAddress)
console.log('Network: ' + network)
const answer = await ask('\nEnter YES to confirm parameters, anything else to abort. ')
if (answer !== 'YES') {
console.warn('Aborted by user.')
exit(1)
}
globalMnemo = await ask('\nEnter mnemonic for sender account.\nBE SURE TO DO THIS FROM A SECURED SYSTEM\n')
await startOp(algodClient, symbol, vaddr, fromAddress)
console.log('Bye.')
exit(0)
})()

View File

@ -0,0 +1,19 @@
13947Bd48b18E53fdAeEe77F3473391aC727C638
F18AbBac073741DD0F002147B735Ff642f3D113F
9925A94DC043D0803f8ef502D2dB15cAc9e02D76
9e4EC2D92af8602bCE74a27F99A836f93C4a31E4
9C40c4052A3092AfB8C99B985fcDfB586Ed19c98
B86020cF1262AA4dd5572Af76923E271169a2CA7
1937617fE1eD801fBa14Bd8BB9EDEcBA7A942FFe
9475b8D45DdE53614d92c779787C27fE2ef68752
15A53B22c28AbC7B108612146B6aAa4a537bA305
63842657C7aC7e37B04FBE76b8c54EFe014D04E1
948ca1bBF4B858DF1A505b4C69c5c61bD95A12Bd
A6923e2259F8B5541eD18e410b8DdEE618337ff0
F678Daf4b7f2789AA88A081618Aa966D6a39e064
8cF31021838A8B3fFA43a71a50609877846f9E6d
eB15bCF2ae4f957012330B4741ecE3242De96184
cc3766a03e4faec44Bda7a46D9Ea2A9D124e9Bf8
841f499Ba89a6a8E9dD273BAd82Beb175094E5d7
f5F2b82576e6CA17965dee853d08bbB471FA2433
2bC2B1204599D4cA0d4Dde4a658a42c4dD13103a

View File

@ -0,0 +1,36 @@
{
"compilerOptions": {
"alwaysStrict": true,
"declaration": true,
"declarationMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"inlineSourceMap": false,
"inlineSources": true,
"esModuleInterop": true,
"baseUrl": ".",
"target": "es2020",
"module": "CommonJS",
"moduleResolution": "node",
"sourceMap": true,
"strict": true,
"importHelpers": false,
"noEmitHelpers": false,
"noEmitOnError": true,
"resolveJsonModule": true,
"removeComments": true,
"outDir": "build",
"types": ["node"],
"lib": [ "ES2020.Promise" ],
},
"include": [
"backend/**/*.ts",
],
"exclude": [
"build",
"node_modules",
"test",
"**/*.spec.ts"
]
}