From 901f5b9c3ca46327561334855d208cecf84b7385 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Mon, 12 Feb 2024 14:13:11 +0530 Subject: [PATCH 1/8] Setup a custom command to commit a bid --- go.mod | 16 +++++- go.sum | 44 +++++++++++++++- utils/json.go | 101 ++++++++++++++++++++++++++++++++++++ utils/mnemonic.go | 21 ++++++++ x/auction/client/cli/tx.go | 93 +++++++++++++++++++++++++++++++++ x/auction/module/autocli.go | 1 + x/auction/module/module.go | 7 +++ x/auction/msgs.go | 35 +++++++++++++ 8 files changed, 315 insertions(+), 3 deletions(-) create mode 100644 utils/json.go create mode 100644 utils/mnemonic.go create mode 100644 x/auction/client/cli/tx.go create mode 100644 x/auction/msgs.go diff --git a/go.mod b/go.mod index 3057cc88..fff27d9c 100644 --- a/go.mod +++ b/go.mod @@ -27,9 +27,13 @@ require ( github.com/cosmos/cosmos-db v1.0.0 github.com/cosmos/cosmos-proto v1.0.0-beta.3 github.com/cosmos/cosmos-sdk v0.50.3 + github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogoproto v1.4.11 + github.com/gibson042/canonicaljson-go v1.0.3 github.com/golang/protobuf v1.5.3 github.com/grpc-ecosystem/grpc-gateway v1.16.0 + github.com/ipfs/go-cid v0.4.1 + github.com/ipld/go-ipld-prime v0.21.0 github.com/spf13/cobra v1.8.0 github.com/spf13/viper v1.17.0 google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f @@ -58,7 +62,6 @@ require ( github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/cometbft/cometbft-db v0.9.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.0.0 // indirect github.com/cosmos/ics23/go v0.10.0 // indirect @@ -110,6 +113,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect github.com/klauspost/compress v1.17.4 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect @@ -120,15 +124,23 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect github.com/minio/highwayhash v1.0.2 // indirect + github.com/minio/sha256-simd v1.0.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mr-tron/base58 v1.2.0 // indirect github.com/mtibben/percent v0.2.1 // indirect + github.com/multiformats/go-base32 v0.0.3 // indirect + github.com/multiformats/go-base36 v0.1.0 // indirect + github.com/multiformats/go-multibase v0.0.3 // indirect + github.com/multiformats/go-multihash v0.2.3 // indirect + github.com/multiformats/go-varint v0.0.6 // indirect github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect github.com/oklog/run v1.1.0 // indirect github.com/pelletier/go-toml/v2 v2.1.0 // indirect github.com/petermattis/goid v0.0.0-20230904192822-1876fd5063bc // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/polydawn/refmt v0.89.0 // indirect github.com/prometheus/client_golang v1.17.0 // indirect github.com/prometheus/client_model v0.5.0 // indirect github.com/prometheus/common v0.45.0 // indirect @@ -141,6 +153,7 @@ require ( github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spf13/afero v1.10.0 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/spf13/pflag v1.0.5 // indirect @@ -166,6 +179,7 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect gotest.tools/v3 v3.5.1 // indirect + lukechampine.com/blake3 v1.1.6 // indirect nhooyr.io/websocket v1.8.6 // indirect pgregory.net/rapid v1.1.0 // indirect sigs.k8s.io/yaml v1.3.0 // indirect diff --git a/go.sum b/go.sum index 3365ecde..93472ff7 100644 --- a/go.sum +++ b/go.sum @@ -264,8 +264,8 @@ github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8 github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= -github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= @@ -273,6 +273,8 @@ github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbS github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gibson042/canonicaljson-go v1.0.3 h1:EAyF8L74AWabkyUmrvEFHEt/AGFQeD6RfwbAuf0j1bI= +github.com/gibson042/canonicaljson-go v1.0.3/go.mod h1:DsLpJTThXyGNO+KZlI85C1/KDcImpP67k/RKVjcaEqo= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU= @@ -307,6 +309,7 @@ github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJ github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= @@ -407,6 +410,7 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= @@ -484,6 +488,10 @@ github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANyt github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= +github.com/ipfs/go-cid v0.4.1 h1:A/T3qGvxi4kpKWWcPC/PgbvDA2bjVLO7n4UeVwnbs/s= +github.com/ipfs/go-cid v0.4.1/go.mod h1:uQHwDeX4c6CtyrFwdqyhpNcxVewur1M7l7fNU7LKwZk= +github.com/ipld/go-ipld-prime v0.21.0 h1:n4JmcpOlPDIxBcY037SVfpd1G+Sj1nKZah0m6QH9C2E= +github.com/ipld/go-ipld-prime v0.21.0/go.mod h1:3RLqy//ERg/y5oShXXdx5YIp50cFGOanyMctpPjsvxQ= github.com/jhump/protoreflect v1.15.3 h1:6SFRuqU45u9hIZPJAoZ8c28T3nK64BNdp9w6jFonzls= github.com/jhump/protoreflect v1.15.3/go.mod h1:4ORHmSBmlCW8fh3xHmJMGyul1zNqZK4Elxc8qKP+p1k= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= @@ -500,6 +508,7 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= @@ -512,6 +521,9 @@ github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= +github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= @@ -560,6 +572,8 @@ github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQth github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= +github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g= +github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -579,8 +593,23 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8= +github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= +github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= +github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI= +github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA= +github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4= +github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM= +github.com/multiformats/go-multibase v0.0.3 h1:l/B6bJDQjvQ5G52jw4QGSYeOTZoAwIO77RblWplfIqk= +github.com/multiformats/go-multibase v0.0.3/go.mod h1:5+1R4eQrT3PkYZ24C3W2Ue2tPwIdYQD509ZjSb5y9Oc= +github.com/multiformats/go-multicodec v0.9.0 h1:pb/dlPnzee/Sxv/j4PmkDRxCOi3hXTz3IbPKOXWJkmg= +github.com/multiformats/go-multicodec v0.9.0/go.mod h1:L3QTQvMIaVBkXOXXtVmYE+LI16i14xuaojr/H7Ai54k= +github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U= +github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM= +github.com/multiformats/go-varint v0.0.6 h1:gk85QWKxh3TazbLxED/NlDVv8+q+ReFJk7Y2W/KhfNY= +github.com/multiformats/go-varint v0.0.6/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= @@ -656,6 +685,8 @@ github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qR github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/polydawn/refmt v0.89.0 h1:ADJTApkvkeBZsN0tBTx8QjpD9JkmxbKp0cxfr9qszm4= +github.com/polydawn/refmt v0.89.0/go.mod h1:/zvteZs/GwLtCgZ4BL6CBsk9IKIlexP43ObX9AxTqTw= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= @@ -724,7 +755,11 @@ github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= +github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= +github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= @@ -787,6 +822,9 @@ github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0 github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ= +github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -1268,6 +1306,8 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +lukechampine.com/blake3 v1.1.6 h1:H3cROdztr7RCfoaTpGZFQsrqvweFLrqS73j7L7cmR5c= +lukechampine.com/blake3 v1.1.6/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= diff --git a/utils/json.go b/utils/json.go new file mode 100644 index 00000000..b10c501a --- /dev/null +++ b/utils/json.go @@ -0,0 +1,101 @@ +// +// Copyright 2020 Wireline, Inc. +// + +package utils + +import ( + "bytes" + "errors" + + canonicalJson "github.com/gibson042/canonicaljson-go" + "github.com/ipfs/go-cid" + "github.com/ipld/go-ipld-prime/codec/dagcbor" + "github.com/ipld/go-ipld-prime/codec/dagjson" + "github.com/ipld/go-ipld-prime/linking" + cidlink "github.com/ipld/go-ipld-prime/linking/cid" + "github.com/ipld/go-ipld-prime/multicodec" + basicnode "github.com/ipld/go-ipld-prime/node/basic" + "github.com/ipld/go-ipld-prime/storage/memstore" +) + +var store = memstore.Store{} + +func init() { + multicodec.RegisterEncoder(0x71, dagcbor.Encode) + multicodec.RegisterDecoder(0x71, dagcbor.Decode) +} + +// GenerateHash returns the hash of the canonicalized JSON input. +func GenerateHash(json map[string]interface{}) (string, []byte, error) { + content, err := canonicalJson.Marshal(json) + if err != nil { + return "", nil, err + } + + cidString, err := CIDFromJSONBytes(content) + if err != nil { + return "", nil, err + } + + return cidString, content, nil +} + +// GetAttributeAsString returns a map attribute as string, if possible. +func GetAttributeAsString(obj map[string]interface{}, attr string) (string, error) { + if value, ok := obj[attr]; ok { + if valueStr, ok := value.(string); ok { + return valueStr, nil + } + + return "", errors.New("attribute not of string type") + } + + return "", errors.New("attribute not found") +} + +// CIDFromJSONBytes returns CID (dagcbor) for json (as bytes). +// This is combination of samples for unmarshalling and linking +// see: https://pkg.go.dev/github.com/ipld/go-ipld-prime +func CIDFromJSONBytes(content []byte) (string, error) { + if len(content) == 0 { + return "", nil + } + + np := basicnode.Prototype.Any // Pick a stle for the in-memory data. + nb := np.NewBuilder() // Create a builder. + err := dagjson.Decode(nb, bytes.NewReader(content)) // Hand the builder to decoding -- decoding will fill it in! + if err != nil { + return "", err + } + n := nb.Build() // Call 'Build' to get the resulting Node. (It's immutable!) + + lsys := cidlink.DefaultLinkSystem() + + // We want to store the serialized data somewhere. + // We'll use an in-memory store for this. (It's a package scoped variable.) + // You can use any kind of storage system here; + // or if you need even more control, you could also write a function that conforms to the linking.BlockWriteOpener interface. + lsys.SetWriteStorage(&store) + // To create any links, first we need a LinkPrototype. + // This gathers together any parameters that might be needed when making a link. + // (For CIDs, the version, the codec, and the multihash type are all parameters we'll need.) + // Often, you can probably make this a constant for your whole application. + lp := cidlink.LinkPrototype{Prefix: cid.Prefix{ //nolint:golint + Version: 1, // Usually '1'. + Codec: 0x71, // 0x71 means "dag-cbor" -- See the multicodecs table: https://github.com/multiformats/multicodec/ + MhType: 0x12, // 0x12 means "sha2-256" -- See the multicodecs table: https://github.com/multiformats/multicodec/ + MhLength: 32, // sha2-256 hash has a 32-byte sum. + }} + + // Now: time to apply the LinkSystem, and do the actual store operation! + lnk, err := lsys.Store( + linking.LinkContext{}, // The zero value is fine. Configure it it you want cancellability or other features. + lp, // The LinkPrototype says what codec and hashing to use. + n, // And here's our data. + ) + if err != nil { + return "", err + } + return lnk.String(), nil +} diff --git a/utils/mnemonic.go b/utils/mnemonic.go new file mode 100644 index 00000000..e94469ec --- /dev/null +++ b/utils/mnemonic.go @@ -0,0 +1,21 @@ +package utils + +import "github.com/cosmos/go-bip39" + +const ( + mnemonicEntropySize = 256 +) + +func GenerateMnemonic() (string, error) { + entropySeed, err := bip39.NewEntropy(mnemonicEntropySize) + if err != nil { + return "", err + } + + mnemonic, err := bip39.NewMnemonic(entropySeed) + if err != nil { + return "", err + } + + return mnemonic, nil +} diff --git a/x/auction/client/cli/tx.go b/x/auction/client/cli/tx.go new file mode 100644 index 00000000..80f4fed3 --- /dev/null +++ b/x/auction/client/cli/tx.go @@ -0,0 +1,93 @@ +package cli + +import ( + "fmt" + "os" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + + wnsUtils "git.vdb.to/cerc-io/laconic2d/utils" + auctiontypes "git.vdb.to/cerc-io/laconic2d/x/auction" +) + +// GetTxCmd returns transaction commands for this module. +func GetTxCmd() *cobra.Command { + auctionTxCmd := &cobra.Command{ + Use: auctiontypes.ModuleName, + Short: "Auction transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + auctionTxCmd.AddCommand( + GetCmdCommitBid(), + ) + + return auctionTxCmd +} + +// GetCmdCommitBid is the CLI command for committing a bid. +func GetCmdCommitBid() *cobra.Command { + cmd := &cobra.Command{ + Use: "commit-bid [auction-id] [bid-amount]", + Short: "Commit sealed bid", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + bidAmount, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + mnemonic, err := wnsUtils.GenerateMnemonic() + if err != nil { + return err + } + + chainId := viper.GetString("chain-id") + auctionId := args[0] + + reveal := map[string]interface{}{ + "chainId": chainId, + "auctionId": auctionId, + "bidderAddress": clientCtx.GetFromAddress().String(), + "bidAmount": bidAmount.String(), + "noise": mnemonic, + } + + commitHash, content, err := wnsUtils.GenerateHash(reveal) + if err != nil { + return err + } + + // Save reveal file. + err = os.WriteFile(fmt.Sprintf("%s-%s.json", clientCtx.GetFromName(), commitHash), content, 0o600) + if err != nil { + return err + } + + msg := auctiontypes.NewMsgCommitBid(auctionId, commitHash, clientCtx.GetFromAddress()) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/auction/module/autocli.go b/x/auction/module/autocli.go index 0fbc9f9e..6f2b59b3 100644 --- a/x/auction/module/autocli.go +++ b/x/auction/module/autocli.go @@ -61,6 +61,7 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { }, }, }, + EnhanceCustomCommand: true, // Allow additional manual commands }, } } diff --git a/x/auction/module/module.go b/x/auction/module/module.go index 7a258a39..8105f88f 100644 --- a/x/auction/module/module.go +++ b/x/auction/module/module.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/core/appmodule" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -15,6 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "git.vdb.to/cerc-io/laconic2d/x/auction" + "git.vdb.to/cerc-io/laconic2d/x/auction/client/cli" "git.vdb.to/cerc-io/laconic2d/x/auction/keeper" ) @@ -125,3 +127,8 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { func (am AppModule) EndBlock(ctx context.Context) error { return EndBlocker(ctx, am.keeper) } + +// Get the root tx command of this module +func (AppModule) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} diff --git a/x/auction/msgs.go b/x/auction/msgs.go new file mode 100644 index 00000000..ed454d47 --- /dev/null +++ b/x/auction/msgs.go @@ -0,0 +1,35 @@ +package auction + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +var _ sdk.Msg = &MsgCommitBid{} + +// NewMsgCommitBid is the constructor function for MsgCommitBid. +func NewMsgCommitBid(auctionID string, commitHash string, signer sdk.AccAddress) MsgCommitBid { + return MsgCommitBid{ + AuctionId: auctionID, + CommitHash: commitHash, + Signer: signer.String(), + } +} + +// ValidateBasic Implements Msg. +func (msg MsgCommitBid) ValidateBasic() error { + if msg.Signer == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid signer address.") + } + + if msg.AuctionId == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid auction ID.") + } + + if msg.CommitHash == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid commit hash.") + } + + return nil +} -- 2.45.2 From e7c6eb69b3b72cb6820f0a8976502ee633d8f616 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Tue, 13 Feb 2024 17:56:33 +0530 Subject: [PATCH 2/8] Add a keeper method to commit bids --- x/auction/keeper/keeper.go | 139 +++++++++++++++++++++++++++++++++++-- x/auction/keys.go | 7 +- x/bond/keeper/keeper.go | 4 +- x/bond/keys.go | 5 +- 4 files changed, 143 insertions(+), 12 deletions(-) diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index 8bb95a21..635cbb89 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -37,6 +37,23 @@ func newAuctionIndexes(sb *collections.SchemaBuilder) AuctionsIndexes { } } +type BidsIndexes struct { + Bidder *indexes.ReversePair[string, string, auctiontypes.Bid] +} + +func (b BidsIndexes) IndexesList() []collections.Index[collections.Pair[string, string], auctiontypes.Bid] { + return []collections.Index[collections.Pair[string, string], auctiontypes.Bid]{b.Bidder} +} + +func newBidsIndexes(sb *collections.SchemaBuilder) BidsIndexes { + return BidsIndexes{ + Bidder: indexes.NewReversePair[auctiontypes.Bid]( + sb, auctiontypes.BidderAuctionIdIndexPrefix, "auction_id_by_bidder", + collections.PairKeyCodec(collections.StringKey, collections.StringKey), + ), + } +} + // TODO: Add required methods type Keeper struct { @@ -53,7 +70,8 @@ type Keeper struct { // state management Schema collections.Schema Params collections.Item[auctiontypes.Params] - Auctions *collections.IndexedMap[string, auctiontypes.Auction, AuctionsIndexes] + Auctions *collections.IndexedMap[string, auctiontypes.Auction, AuctionsIndexes] // map: auctionId -> Auction, index: owner -> Auctions + Bids *collections.IndexedMap[collections.Pair[string, string], auctiontypes.Bid, BidsIndexes] // map: (auctionId, bidder) -> Bid, index: bidder -> auctionId } // NewKeeper creates a new Keeper instance @@ -68,8 +86,9 @@ func NewKeeper( cdc: cdc, accountKeeper: accountKeeper, bankKeeper: bankKeeper, - Params: collections.NewItem(sb, auctiontypes.ParamsKeyPrefix, "params", codec.CollValue[auctiontypes.Params](cdc)), - Auctions: collections.NewIndexedMap(sb, auctiontypes.AuctionsKeyPrefix, "auctions", collections.StringKey, codec.CollValue[auctiontypes.Auction](cdc), newAuctionIndexes(sb)), + Params: collections.NewItem(sb, auctiontypes.ParamsPrefix, "params", codec.CollValue[auctiontypes.Params](cdc)), + Auctions: collections.NewIndexedMap(sb, auctiontypes.AuctionsPrefix, "auctions", collections.StringKey, codec.CollValue[auctiontypes.Auction](cdc), newAuctionIndexes(sb)), + Bids: collections.NewIndexedMap(sb, auctiontypes.BidsPrefix, "bids", collections.PairKeyCodec(collections.StringKey, collections.StringKey), codec.CollValue[auctiontypes.Bid](cdc), newBidsIndexes(sb)), // usageKeepers: usageKeepers, } @@ -98,6 +117,51 @@ func (k Keeper) SaveAuction(ctx sdk.Context, auction *auctiontypes.Auction) erro // return nil } +func (k Keeper) HasAuction(ctx sdk.Context, id string) (bool, error) { + has, err := k.Auctions.Has(ctx, id) + if err != nil { + return false, err + } + + return has, nil +} + +func (k Keeper) SaveBid(ctx sdk.Context, bid *auctiontypes.Bid) error { + key := collections.Join(bid.AuctionId, bid.BidderAddress) + return k.Bids.Set(ctx, key, *bid) + + // // Notify interested parties. + // for _, keeper := range k.usageKeepers { + // keeper.OnAuctionBid(ctx, bid.AuctionId, bid.BidderAddress) + // } + // return nil +} + +func (k Keeper) DeleteBid(ctx sdk.Context, bid auctiontypes.Bid) error { + key := collections.Join(bid.AuctionId, bid.BidderAddress) + return k.Bids.Remove(ctx, key) +} + +func (k Keeper) HasBid(ctx sdk.Context, id string, bidder string) (bool, error) { + key := collections.Join(id, bidder) + has, err := k.Bids.Has(ctx, key) + if err != nil { + return false, err + } + + return has, nil +} + +func (k Keeper) GetBid(ctx sdk.Context, id string, bidder string) (auctiontypes.Bid, error) { + key := collections.Join(id, bidder) + bid, err := k.Bids.Get(ctx, key) + if err != nil { + return auctiontypes.Bid{}, err + } + + return bid, nil +} + // ListAuctions - get all auctions. func (k Keeper) ListAuctions(ctx sdk.Context) ([]auctiontypes.Auction, error) { var auctions []auctiontypes.Auction @@ -185,13 +249,78 @@ func (k Keeper) CreateAuction(ctx sdk.Context, msg auctiontypes.MsgCreateAuction } // Save auction in store. - k.SaveAuction(ctx, &auction) + if err = k.SaveAuction(ctx, &auction); err != nil { + return nil, err + } return &auction, nil } func (k Keeper) CommitBid(ctx sdk.Context, msg auctiontypes.MsgCommitBid) (*auctiontypes.Bid, error) { - panic("unimplemented") + if has, err := k.HasAuction(ctx, msg.AuctionId); !has { + if err != nil { + return nil, err + } + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Auction not found.") + } + + auction, err := k.GetAuctionById(ctx, msg.AuctionId) + if err != nil { + return nil, err + } + + if auction.Status != auctiontypes.AuctionStatusCommitPhase { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Auction is not in commit phase.") + } + + signerAddress, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + return nil, err + } + + // Take auction fees from account. + totalFee := auction.CommitFee.Add(auction.RevealFee) + sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, signerAddress, auctiontypes.ModuleName, sdk.NewCoins(totalFee)) + if sdkErr != nil { + return nil, sdkErr + } + + // Check if an old bid already exists, if so, return old bids auction fee (update bid scenario). + bidder := signerAddress.String() + bidExists, err := k.HasBid(ctx, msg.AuctionId, bidder) + if err != nil { + return nil, err + } + + if bidExists { + oldBid, err := k.GetBid(ctx, msg.AuctionId, bidder) + if err != nil { + return nil, err + } + + oldTotalFee := oldBid.CommitFee.Add(oldBid.RevealFee) + sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, signerAddress, sdk.NewCoins(oldTotalFee)) + if sdkErr != nil { + return nil, sdkErr + } + } + + // Save new bid. + bid := auctiontypes.Bid{ + AuctionId: msg.AuctionId, + BidderAddress: bidder, + Status: auctiontypes.BidStatusCommitted, + CommitHash: msg.CommitHash, + CommitTime: ctx.BlockTime(), + CommitFee: auction.CommitFee, + RevealFee: auction.RevealFee, + } + + if err = k.SaveBid(ctx, &bid); err != nil { + return nil, err + } + + return &bid, nil } func (k Keeper) RevealBid(ctx sdk.Context, msg auctiontypes.MsgRevealBid) (*auctiontypes.Auction, error) { diff --git a/x/auction/keys.go b/x/auction/keys.go index f1c0c0a3..fe626433 100644 --- a/x/auction/keys.go +++ b/x/auction/keys.go @@ -12,8 +12,11 @@ const ( // Store prefixes var ( // ParamsKey is the prefix for params key - ParamsKeyPrefix = collections.NewPrefix(0) + ParamsPrefix = collections.NewPrefix(0) - AuctionsKeyPrefix = collections.NewPrefix(1) + AuctionsPrefix = collections.NewPrefix(1) AuctionOwnerIndexPrefix = collections.NewPrefix(2) + + BidsPrefix = collections.NewPrefix(3) + BidderAuctionIdIndexPrefix = collections.NewPrefix(4) ) diff --git a/x/bond/keeper/keeper.go b/x/bond/keeper/keeper.go index e1dd9eb9..2d2ff846 100644 --- a/x/bond/keeper/keeper.go +++ b/x/bond/keeper/keeper.go @@ -70,8 +70,8 @@ func NewKeeper( cdc: cdc, accountKeeper: accountKeeper, bankKeeper: bankKeeper, - Params: collections.NewItem(sb, bondtypes.ParamsKeyPrefix, "params", codec.CollValue[bondtypes.Params](cdc)), - Bonds: collections.NewIndexedMap(sb, bondtypes.BondsKeyPrefix, "bonds", collections.StringKey, codec.CollValue[bondtypes.Bond](cdc), newBondIndexes(sb)), + Params: collections.NewItem(sb, bondtypes.ParamsPrefix, "params", codec.CollValue[bondtypes.Params](cdc)), + Bonds: collections.NewIndexedMap(sb, bondtypes.BondsPrefix, "bonds", collections.StringKey, codec.CollValue[bondtypes.Bond](cdc), newBondIndexes(sb)), // usageKeepers: usageKeepers, } diff --git a/x/bond/keys.go b/x/bond/keys.go index deb56ef1..ddb5e32e 100644 --- a/x/bond/keys.go +++ b/x/bond/keys.go @@ -8,9 +8,8 @@ const ( // Store prefixes var ( - // ParamsKey is the prefix for params key - ParamsKeyPrefix = collections.NewPrefix(0) + ParamsPrefix = collections.NewPrefix(0) - BondsKeyPrefix = collections.NewPrefix(1) + BondsPrefix = collections.NewPrefix(1) BondOwnerIndexPrefix = collections.NewPrefix(2) ) -- 2.45.2 From 23e6e2f16af0487e7b34be16baa9aed4febac1a5 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Tue, 13 Feb 2024 18:32:17 +0530 Subject: [PATCH 3/8] Add commands to get bids for an auction --- utils/json.go | 4 ---- x/auction/keeper/keeper.go | 29 +++++++++++++++++------------ x/auction/keeper/query_server.go | 32 +++++++++++++++++++++++++++++--- x/auction/module/autocli.go | 17 +++++++++++++++++ 4 files changed, 63 insertions(+), 19 deletions(-) diff --git a/utils/json.go b/utils/json.go index b10c501a..7ae9d280 100644 --- a/utils/json.go +++ b/utils/json.go @@ -1,7 +1,3 @@ -// -// Copyright 2020 Wireline, Inc. -// - package utils import ( diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index 635cbb89..5ac0c61d 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -162,25 +162,30 @@ func (k Keeper) GetBid(ctx sdk.Context, id string, bidder string) (auctiontypes. return bid, nil } +// GetBids gets the auction bids. +func (k Keeper) GetBids(ctx sdk.Context, id string) ([]*auctiontypes.Bid, error) { + var bids []*auctiontypes.Bid + + // TODO: Optimize using return by value? + err := k.Bids.Walk(ctx, collections.NewPrefixedPairRange[string, string](id), func(key collections.Pair[string, string], value auctiontypes.Bid) (stop bool, err error) { + bids = append(bids, &value) + return false, nil + }) + if err != nil { + return nil, err + } + + return bids, nil +} + // ListAuctions - get all auctions. func (k Keeper) ListAuctions(ctx sdk.Context) ([]auctiontypes.Auction, error) { - var auctions []auctiontypes.Auction - iter, err := k.Auctions.Iterate(ctx, nil) if err != nil { return nil, err } - for ; iter.Valid(); iter.Next() { - auction, err := iter.Value() - if err != nil { - return nil, err - } - - auctions = append(auctions, auction) - } - - return auctions, nil + return iter.Values() } // GetAuction - gets a record from the store. diff --git a/x/auction/keeper/query_server.go b/x/auction/keeper/query_server.go index 5233a684..8ea8f89e 100644 --- a/x/auction/keeper/query_server.go +++ b/x/auction/keeper/query_server.go @@ -63,14 +63,40 @@ func (qs queryServer) GetAuction(c context.Context, req *auctiontypes.QueryAucti return &auctiontypes.QueryAuctionResponse{Auction: &auction}, nil } -// GetBid queries and auction bid +// GetBid queries an auction bid by auction-id and bidder func (qs queryServer) GetBid(c context.Context, req *auctiontypes.QueryBidRequest) (*auctiontypes.QueryBidResponse, error) { - panic("unimplemented") + ctx := sdk.UnwrapSDKContext(c) + + if req.AuctionId == "" { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required") + } + + if req.Bidder == "" { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "bidder address is required") + } + + bid, err := qs.k.GetBid(ctx, req.AuctionId, req.Bidder) + if err != nil { + return nil, err + } + + return &auctiontypes.QueryBidResponse{Bid: &bid}, nil } // GetBids queries all auction bids func (qs queryServer) GetBids(c context.Context, req *auctiontypes.QueryBidsRequest) (*auctiontypes.QueryBidsResponse, error) { - panic("unimplemented") + ctx := sdk.UnwrapSDKContext(c) + + if req.AuctionId == "" { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required") + } + + resp, err := qs.k.GetBids(ctx, req.AuctionId) + if err != nil { + return nil, err + } + + return &auctiontypes.QueryBidsResponse{Bids: resp}, nil } // AuctionsByBidder queries auctions by bidder diff --git a/x/auction/module/autocli.go b/x/auction/module/autocli.go index 6f2b59b3..ffaed1af 100644 --- a/x/auction/module/autocli.go +++ b/x/auction/module/autocli.go @@ -43,6 +43,23 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { {ProtoField: "owner_address"}, }, }, + { + RpcMethod: "GetBid", + Use: "get-bid [auction-id] [bidder]", + Short: "Get auction bid by auction id and bidder", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "auction_id"}, + {ProtoField: "bidder"}, + }, + }, + { + RpcMethod: "GetBids", + Use: "get-bids [auction-id]", + Short: "Get all auction bids", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "auction_id"}, + }, + }, }, }, Tx: &autocliv1.ServiceCommandDescriptor{ -- 2.45.2 From 513ad9975bd6a8949d941a5ace422e70766585a1 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Tue, 13 Feb 2024 19:13:00 +0530 Subject: [PATCH 4/8] Add a command to get auctions by bidder address --- x/auction/keeper/keeper.go | 28 +++++++++++++++++++++++++++- x/auction/keeper/query_server.go | 13 ++++++++++++- x/auction/module/autocli.go | 8 ++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index 5ac0c61d..f11e3259 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -204,12 +204,38 @@ func (k Keeper) GetAuctionById(ctx sdk.Context, id string) (auctiontypes.Auction func (k Keeper) GetAuctionsByOwner(ctx sdk.Context, owner string) ([]auctiontypes.Auction, error) { iter, err := k.Auctions.Indexes.Owner.MatchExact(ctx, owner) if err != nil { - return []auctiontypes.Auction{}, err + return nil, err } return indexes.CollectValues(ctx, k.Auctions, iter) } +// QueryAuctionsByBidder - query auctions by bidder +func (k Keeper) QueryAuctionsByBidder(ctx sdk.Context, bidderAddress string) ([]auctiontypes.Auction, error) { + auctions := []auctiontypes.Auction{} + + iter, err := k.Bids.Indexes.Bidder.MatchExact(ctx, bidderAddress) + if err != nil { + return nil, err + } + + for ; iter.Valid(); iter.Next() { + keyPair, err := iter.PrimaryKey() + if err != nil { + return nil, err + } + + auction, err := k.GetAuctionById(ctx, keyPair.K1()) + if err != nil { + return nil, err + } + + auctions = append(auctions, auction) + } + + return auctions, nil +} + // CreateAuction creates a new auction. func (k Keeper) CreateAuction(ctx sdk.Context, msg auctiontypes.MsgCreateAuction) (*auctiontypes.Auction, error) { // TODO: Setup checks diff --git a/x/auction/keeper/query_server.go b/x/auction/keeper/query_server.go index 8ea8f89e..77cb32a6 100644 --- a/x/auction/keeper/query_server.go +++ b/x/auction/keeper/query_server.go @@ -101,7 +101,18 @@ func (qs queryServer) GetBids(c context.Context, req *auctiontypes.QueryBidsRequ // AuctionsByBidder queries auctions by bidder func (qs queryServer) AuctionsByBidder(c context.Context, req *auctiontypes.QueryAuctionsByBidderRequest) (*auctiontypes.QueryAuctionsByBidderResponse, error) { - panic("unimplemented") + ctx := sdk.UnwrapSDKContext(c) + + if req.BidderAddress == "" { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "bidder address is required") + } + + auctions, err := qs.k.QueryAuctionsByBidder(ctx, req.BidderAddress) + if err != nil { + return nil, err + } + + return &auctiontypes.QueryAuctionsByBidderResponse{Auctions: &auctiontypes.Auctions{Auctions: auctions}}, nil } // AuctionsByOwner queries auctions by owner diff --git a/x/auction/module/autocli.go b/x/auction/module/autocli.go index ffaed1af..2861e133 100644 --- a/x/auction/module/autocli.go +++ b/x/auction/module/autocli.go @@ -60,6 +60,14 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { {ProtoField: "auction_id"}, }, }, + { + RpcMethod: "AuctionsByBidder", + Use: "by-bidder [bidder]", + Short: "Get auctions list by bidder", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "bidder_address"}, + }, + }, }, }, Tx: &autocliv1.ServiceCommandDescriptor{ -- 2.45.2 From de742a5a849086e8c689dcf5bb6cd5c93fb25588 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Tue, 13 Feb 2024 19:22:42 +0530 Subject: [PATCH 5/8] Update account address prefix --- app/app.yaml | 2 +- app/params/config.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/app.yaml b/app/app.yaml index 71bce538..e34deea4 100644 --- a/app/app.yaml +++ b/app/app.yaml @@ -17,7 +17,7 @@ modules: - name: auth config: "@type": cosmos.auth.module.v1.Module - bech32_prefix: photon + bech32_prefix: laconic module_account_permissions: - account: fee_collector - account: distribution diff --git a/app/params/config.go b/app/params/config.go index ae8f53a3..4fc14f08 100644 --- a/app/params/config.go +++ b/app/params/config.go @@ -15,7 +15,7 @@ const ( DefaultBondDenom = CoinUnit // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address. - Bech32PrefixAccAddr = "photon" + Bech32PrefixAccAddr = "laconic" ) var ( -- 2.45.2 From 842dfc618540bd753f9bf24505af86d50d32eab7 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Wed, 14 Feb 2024 09:25:10 +0530 Subject: [PATCH 6/8] Add a command to get auction module balance --- x/auction/keeper/keeper.go | 8 ++++++++ x/auction/keeper/query_server.go | 15 ++++++++------- x/auction/module/autocli.go | 6 ++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index f11e3259..33eae0ea 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -367,3 +367,11 @@ func (k Keeper) GetParams(ctx sdk.Context) (*auctiontypes.Params, error) { return ¶ms, nil } + +// GetAuctionModuleBalances gets the auction module account(s) balances. +func (k Keeper) GetAuctionModuleBalances(ctx sdk.Context) sdk.Coins { + moduleAddress := k.accountKeeper.GetModuleAddress(auctiontypes.ModuleName) + balances := k.bankKeeper.GetAllBalances(ctx, moduleAddress) + + return balances +} diff --git a/x/auction/keeper/query_server.go b/x/auction/keeper/query_server.go index 77cb32a6..4bcfc824 100644 --- a/x/auction/keeper/query_server.go +++ b/x/auction/keeper/query_server.go @@ -10,8 +10,6 @@ import ( auctiontypes "git.vdb.to/cerc-io/laconic2d/x/auction" ) -// TODO: Add required read methods - var _ auctiontypes.QueryServer = queryServer{} type queryServer struct { @@ -39,12 +37,12 @@ func (qs queryServer) Params(c context.Context, req *auctiontypes.QueryParamsReq func (qs queryServer) Auctions(c context.Context, req *auctiontypes.QueryAuctionsRequest) (*auctiontypes.QueryAuctionsResponse, error) { ctx := sdk.UnwrapSDKContext(c) - resp, err := qs.k.ListAuctions(ctx) + auctions, err := qs.k.ListAuctions(ctx) if err != nil { return nil, err } - return &auctiontypes.QueryAuctionsResponse{Auctions: &auctiontypes.Auctions{Auctions: resp}}, nil + return &auctiontypes.QueryAuctionsResponse{Auctions: &auctiontypes.Auctions{Auctions: auctions}}, nil } // GetAuction queries an auction by id @@ -91,12 +89,12 @@ func (qs queryServer) GetBids(c context.Context, req *auctiontypes.QueryBidsRequ return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required") } - resp, err := qs.k.GetBids(ctx, req.AuctionId) + bids, err := qs.k.GetBids(ctx, req.AuctionId) if err != nil { return nil, err } - return &auctiontypes.QueryBidsResponse{Bids: resp}, nil + return &auctiontypes.QueryBidsResponse{Bids: bids}, nil } // AuctionsByBidder queries auctions by bidder @@ -133,5 +131,8 @@ func (qs queryServer) AuctionsByOwner(c context.Context, req *auctiontypes.Query // GetAuctionModuleBalance queries the auction module account balance func (qs queryServer) GetAuctionModuleBalance(c context.Context, req *auctiontypes.QueryGetAuctionModuleBalanceRequest) (*auctiontypes.QueryGetAuctionModuleBalanceResponse, error) { - panic("unimplemented") + ctx := sdk.UnwrapSDKContext(c) + balances := qs.k.GetAuctionModuleBalances(ctx) + + return &auctiontypes.QueryGetAuctionModuleBalanceResponse{Balance: balances}, nil } diff --git a/x/auction/module/autocli.go b/x/auction/module/autocli.go index 2861e133..b6327a07 100644 --- a/x/auction/module/autocli.go +++ b/x/auction/module/autocli.go @@ -68,6 +68,12 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { {ProtoField: "bidder_address"}, }, }, + { + RpcMethod: "GetAuctionModuleBalance", + Use: "balance", + Short: "Get auction module account balances", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{}, + }, }, }, Tx: &autocliv1.ServiceCommandDescriptor{ -- 2.45.2 From 7681f889851bbdd1b15c24de2b5f6f236a7a54d0 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Wed, 14 Feb 2024 10:07:31 +0530 Subject: [PATCH 7/8] Add a command to reveal a bid --- x/auction/client/cli/tx.go | 37 ++++++++++++ x/auction/keeper/keeper.go | 112 ++++++++++++++++++++++++++++++++++++- x/auction/msgs.go | 32 ++++++++++- 3 files changed, 177 insertions(+), 4 deletions(-) diff --git a/x/auction/client/cli/tx.go b/x/auction/client/cli/tx.go index 80f4fed3..90e98030 100644 --- a/x/auction/client/cli/tx.go +++ b/x/auction/client/cli/tx.go @@ -1,6 +1,7 @@ package cli import ( + "encoding/hex" "fmt" "os" @@ -28,6 +29,7 @@ func GetTxCmd() *cobra.Command { auctionTxCmd.AddCommand( GetCmdCommitBid(), + GetCmdRevealBid(), ) return auctionTxCmd @@ -91,3 +93,38 @@ func GetCmdCommitBid() *cobra.Command { return cmd } + +// GetCmdRevealBid is the CLI command for revealing a bid. +func GetCmdRevealBid() *cobra.Command { + cmd := &cobra.Command{ + Use: "reveal-bid [auction-id] [reveal-file-path]", + Short: "Reveal bid", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + auctionId := args[0] + revealFilePath := args[1] + + revealBytes, err := os.ReadFile(revealFilePath) + if err != nil { + return err + } + + msg := auctiontypes.NewMsgRevealBid(auctionId, hex.EncodeToString(revealBytes), clientCtx.GetFromAddress()) + err = msg.ValidateBasic() + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index 33eae0ea..4f071bff 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -1,6 +1,8 @@ package keeper import ( + "encoding/hex" + "encoding/json" "errors" "cosmossdk.io/collections" @@ -14,6 +16,7 @@ import ( auth "github.com/cosmos/cosmos-sdk/x/auth/keeper" bank "github.com/cosmos/cosmos-sdk/x/bank/keeper" + wnsUtils "git.vdb.to/cerc-io/laconic2d/utils" auctiontypes "git.vdb.to/cerc-io/laconic2d/x/auction" ) @@ -355,7 +358,114 @@ func (k Keeper) CommitBid(ctx sdk.Context, msg auctiontypes.MsgCommitBid) (*auct } func (k Keeper) RevealBid(ctx sdk.Context, msg auctiontypes.MsgRevealBid) (*auctiontypes.Auction, error) { - panic("unimplemented") + if has, err := k.HasAuction(ctx, msg.AuctionId); !has { + if err != nil { + return nil, err + } + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Auction not found.") + } + + auction, err := k.GetAuctionById(ctx, msg.AuctionId) + if err != nil { + return nil, err + } + + if auction.Status != auctiontypes.AuctionStatusRevealPhase { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Auction is not in reveal phase.") + } + + signerAddress, err := sdk.AccAddressFromBech32(msg.Signer) + if err != nil { + return nil, err + } + + bidder := signerAddress.String() + bidExists, err := k.HasBid(ctx, msg.AuctionId, bidder) + if err != nil { + return nil, err + } + + if !bidExists { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Bid not found.") + } + + bid, err := k.GetBid(ctx, msg.AuctionId, bidder) + if err != nil { + return nil, err + } + + if bid.Status != auctiontypes.BidStatusCommitted { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Bid not in committed state.") + } + + revealBytes, err := hex.DecodeString(msg.Reveal) + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal string.") + } + + cid, err := wnsUtils.CIDFromJSONBytes(revealBytes) + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal JSON.") + } + + if bid.CommitHash != cid { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Commit hash mismatch.") + } + + var reveal map[string]interface{} + err = json.Unmarshal(revealBytes, &reveal) + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Reveal JSON unmarshal error.") + } + + chainID, err := wnsUtils.GetAttributeAsString(reveal, "chainId") + if err != nil || chainID != ctx.ChainID() { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal chainID.") + } + + auctionID, err := wnsUtils.GetAttributeAsString(reveal, "auctionId") + if err != nil || auctionID != msg.AuctionId { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal auction Id.") + } + + bidderAddress, err := wnsUtils.GetAttributeAsString(reveal, "bidderAddress") + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal bid address.") + } + + if bidderAddress != signerAddress.String() { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Reveal bid address mismatch.") + } + + bidAmountStr, err := wnsUtils.GetAttributeAsString(reveal, "bidAmount") + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal bid amount.") + } + + bidAmount, err := sdk.ParseCoinNormalized(bidAmountStr) + if err != nil { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal bid amount.") + } + + if bidAmount.IsLT(auction.MinimumBid) { + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Bid is lower than minimum bid.") + } + + // Lock bid amount. + sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, signerAddress, auctiontypes.ModuleName, sdk.NewCoins(bidAmount)) + if sdkErr != nil { + return nil, sdkErr + } + + // Update bid. + bid.BidAmount = bidAmount + bid.RevealTime = ctx.BlockTime() + bid.Status = auctiontypes.BidStatusRevealed + if err = k.SaveBid(ctx, &bid); err != nil { + return nil, err + } + + return &auction, nil } // GetParams gets the auction module's parameters. diff --git a/x/auction/msgs.go b/x/auction/msgs.go index ed454d47..3a3ae2d5 100644 --- a/x/auction/msgs.go +++ b/x/auction/msgs.go @@ -20,15 +20,41 @@ func NewMsgCommitBid(auctionID string, commitHash string, signer sdk.AccAddress) // ValidateBasic Implements Msg. func (msg MsgCommitBid) ValidateBasic() error { if msg.Signer == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid signer address.") + return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid signer address") } if msg.AuctionId == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid auction ID.") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid auction id") } if msg.CommitHash == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid commit hash.") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid commit hash") + } + + return nil +} + +// NewMsgRevealBid is the constructor function for MsgRevealBid. +func NewMsgRevealBid(auctionId string, reveal string, signer sdk.AccAddress) MsgRevealBid { + return MsgRevealBid{ + AuctionId: auctionId, + Reveal: reveal, + Signer: signer.String(), + } +} + +// ValidateBasic Implements Msg. +func (msg MsgRevealBid) ValidateBasic() error { + if msg.Signer == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "invalid signer address") + } + + if msg.AuctionId == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid auction id") + } + + if msg.Reveal == "" { + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "invalid reveal data") } return nil -- 2.45.2 From 667fd2f9eb41aaf64a3d0a7ad7bc58035ae9ac82 Mon Sep 17 00:00:00 2001 From: Prathamesh Musale Date: Wed, 14 Feb 2024 12:13:14 +0530 Subject: [PATCH 8/8] Implement end blocker to process auctions --- x/auction/keeper/keeper.go | 252 +++++++++++++++++++++++++++++++++++++ x/auction/module/abci.go | 7 +- 2 files changed, 256 insertions(+), 3 deletions(-) diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go index 4f071bff..578fc361 100644 --- a/x/auction/keeper/keeper.go +++ b/x/auction/keeper/keeper.go @@ -4,6 +4,8 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" + "time" "cosmossdk.io/collections" "cosmossdk.io/collections/indexes" @@ -20,6 +22,9 @@ import ( auctiontypes "git.vdb.to/cerc-io/laconic2d/x/auction" ) +// CompletedAuctionDeleteTimeout => Completed auctions are deleted after this timeout (after reveals end time). +const CompletedAuctionDeleteTimeout = time.Hour * 24 + type AuctionsIndexes struct { Owner *indexes.Multi[string, string, auctiontypes.Auction] } @@ -120,6 +125,23 @@ func (k Keeper) SaveAuction(ctx sdk.Context, auction *auctiontypes.Auction) erro // return nil } +// DeleteAuction - deletes the auction. +func (k Keeper) DeleteAuction(ctx sdk.Context, auction auctiontypes.Auction) error { + // Delete all bids first. + bids, err := k.GetBids(ctx, auction.Id) + if err != nil { + return err + } + + for _, bid := range bids { + if err := k.DeleteBid(ctx, *bid); err != nil { + return err + } + } + + return k.Auctions.Remove(ctx, auction.Id) +} + func (k Keeper) HasAuction(ctx sdk.Context, id string) (bool, error) { has, err := k.Auctions.Has(ctx, id) if err != nil { @@ -191,6 +213,29 @@ func (k Keeper) ListAuctions(ctx sdk.Context) ([]auctiontypes.Auction, error) { return iter.Values() } +// MatchAuctions - get all matching auctions. +func (k Keeper) MatchAuctions(ctx sdk.Context, matchFn func(*auctiontypes.Auction) (bool, error)) ([]*auctiontypes.Auction, error) { + var auctions []*auctiontypes.Auction + + err := k.Auctions.Walk(ctx, nil, func(key string, value auctiontypes.Auction) (stop bool, err error) { + auctionMatched, err := matchFn(&value) + if err != nil { + return false, err + } + + if auctionMatched { + auctions = append(auctions, &value) + } + + return true, nil + }) + if err != nil { + return nil, err + } + + return auctions, nil +} + // GetAuction - gets a record from the store. func (k Keeper) GetAuctionById(ctx sdk.Context, id string) (auctiontypes.Auction, error) { auction, err := k.Auctions.Get(ctx, id) @@ -485,3 +530,210 @@ func (k Keeper) GetAuctionModuleBalances(ctx sdk.Context) sdk.Coins { return balances } + +func (k Keeper) EndBlockerProcessAuctions(ctx sdk.Context) error { + var err error + + // Transition auction state (commit, reveal, expired, completed). + if err = k.processAuctionPhases(ctx); err != nil { + return err + } + + // Delete stale auctions. + return k.deleteCompletedAuctions(ctx) +} + +func (k Keeper) processAuctionPhases(ctx sdk.Context) error { + auctions, err := k.MatchAuctions(ctx, func(_ *auctiontypes.Auction) (bool, error) { + return true, nil + }) + if err != nil { + return err + } + + for _, auction := range auctions { + // Commit -> Reveal state. + if auction.Status == auctiontypes.AuctionStatusCommitPhase && ctx.BlockTime().After(auction.CommitsEndTime) { + auction.Status = auctiontypes.AuctionStatusRevealPhase + if err = k.SaveAuction(ctx, auction); err != nil { + return err + } + + ctx.Logger().Info(fmt.Sprintf("Moved auction %s to reveal phase.", auction.Id)) + } + + // Reveal -> Expired state. + if auction.Status == auctiontypes.AuctionStatusRevealPhase && ctx.BlockTime().After(auction.RevealsEndTime) { + auction.Status = auctiontypes.AuctionStatusExpired + if err = k.SaveAuction(ctx, auction); err != nil { + return err + } + + ctx.Logger().Info(fmt.Sprintf("Moved auction %s to expired state.", auction.Id)) + } + + // If auction has expired, pick a winner from revealed bids. + if auction.Status == auctiontypes.AuctionStatusExpired { + if err = k.pickAuctionWinner(ctx, auction); err != nil { + return err + } + } + } + + return nil +} + +// Delete completed stale auctions. +func (k Keeper) deleteCompletedAuctions(ctx sdk.Context) error { + auctions, err := k.MatchAuctions(ctx, func(auction *auctiontypes.Auction) (bool, error) { + deleteTime := auction.RevealsEndTime.Add(CompletedAuctionDeleteTimeout) + return auction.Status == auctiontypes.AuctionStatusCompleted && ctx.BlockTime().After(deleteTime), nil + }) + if err != nil { + return err + } + + for _, auction := range auctions { + ctx.Logger().Info(fmt.Sprintf("Deleting completed auction %s after timeout.", auction.Id)) + if err := k.DeleteAuction(ctx, *auction); err != nil { + return err + } + } + + return nil +} + +func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction) error { + ctx.Logger().Info(fmt.Sprintf("Picking auction %s winner.", auction.Id)) + + var highestBid *auctiontypes.Bid + var secondHighestBid *auctiontypes.Bid + + bids, err := k.GetBids(ctx, auction.Id) + if err != nil { + return err + } + + for _, bid := range bids { + ctx.Logger().Info(fmt.Sprintf("Processing bid %s %s", bid.BidderAddress, bid.BidAmount.String())) + + // Only consider revealed bids. + if bid.Status != auctiontypes.BidStatusRevealed { + ctx.Logger().Info(fmt.Sprintf("Ignoring unrevealed bid %s %s", bid.BidderAddress, bid.BidAmount.String())) + continue + } + + // Init highest bid. + if highestBid == nil { + highestBid = bid + ctx.Logger().Info(fmt.Sprintf("Initializing 1st bid %s %s", bid.BidderAddress, bid.BidAmount.String())) + continue + } + + //nolint: all + if highestBid.BidAmount.IsLT(bid.BidAmount) { + ctx.Logger().Info(fmt.Sprintf("New highest bid %s %s", bid.BidderAddress, bid.BidAmount.String())) + + secondHighestBid = highestBid + highestBid = bid + + ctx.Logger().Info(fmt.Sprintf("Updated 1st bid %s %s", highestBid.BidderAddress, highestBid.BidAmount.String())) + ctx.Logger().Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String())) + + } else if secondHighestBid == nil || secondHighestBid.BidAmount.IsLT(bid.BidAmount) { + ctx.Logger().Info(fmt.Sprintf("New 2nd highest bid %s %s", bid.BidderAddress, bid.BidAmount.String())) + + secondHighestBid = bid + ctx.Logger().Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String())) + } else { + ctx.Logger().Info(fmt.Sprintf("Ignoring bid as it doesn't affect 1st/2nd price %s %s", bid.BidderAddress, bid.BidAmount.String())) + } + } + + // Highest bid is the winner, but pays second highest bid price. + auction.Status = auctiontypes.AuctionStatusCompleted + + if highestBid != nil { + auction.WinnerAddress = highestBid.BidderAddress + auction.WinningBid = highestBid.BidAmount + + // Winner pays 2nd price, if a 2nd price exists. + auction.WinningPrice = highestBid.BidAmount + if secondHighestBid != nil { + auction.WinningPrice = secondHighestBid.BidAmount + } + ctx.Logger().Info(fmt.Sprintf("Auction %s winner %s.", auction.Id, auction.WinnerAddress)) + ctx.Logger().Info(fmt.Sprintf("Auction %s winner bid %s.", auction.Id, auction.WinningBid.String())) + ctx.Logger().Info(fmt.Sprintf("Auction %s winner price %s.", auction.Id, auction.WinningPrice.String())) + } else { + ctx.Logger().Info(fmt.Sprintf("Auction %s has no valid revealed bids (no winner).", auction.Id)) + } + + if err := k.SaveAuction(ctx, auction); err != nil { + return err + } + + for _, bid := range bids { + bidderAddress, err := sdk.AccAddressFromBech32(bid.BidderAddress) + if err != nil { + ctx.Logger().Error(fmt.Sprintf("Invalid bidderAddress address. %v", err)) + panic("Invalid bidder address.") + } + + if bid.Status == auctiontypes.BidStatusRevealed { + // Send reveal fee back to bidders that've revealed the bid. + sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, bidderAddress, sdk.NewCoins(bid.RevealFee)) + if sdkErr != nil { + ctx.Logger().Error(fmt.Sprintf("Auction error returning reveal fee: %v", sdkErr)) + panic(sdkErr) + } + } + + // Send back locked bid amount to all bidders. + sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, bidderAddress, sdk.NewCoins(bid.BidAmount)) + if sdkErr != nil { + ctx.Logger().Error(fmt.Sprintf("Auction error returning bid amount: %v", sdkErr)) + panic(sdkErr) + } + } + + // Process winner account (if nobody bids, there won't be a winner). + if auction.WinnerAddress != "" { + winnerAddress, err := sdk.AccAddressFromBech32(auction.WinnerAddress) + if err != nil { + ctx.Logger().Error(fmt.Sprintf("Invalid winner address. %v", err)) + panic("Invalid winner address.") + } + + // Take 2nd price from winner. + sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, winnerAddress, auctiontypes.ModuleName, sdk.NewCoins(auction.WinningPrice)) + if sdkErr != nil { + ctx.Logger().Error(fmt.Sprintf("Auction error taking funds from winner: %v", sdkErr)) + panic(sdkErr) + } + + // Burn anything over the min. bid amount. + amountToBurn := auction.WinningPrice.Sub(auction.MinimumBid) + if amountToBurn.IsNegative() { + ctx.Logger().Error("Auction coins to burn cannot be negative.") + panic("Auction coins to burn cannot be negative.") + } + + // Use auction burn module account instead of actually burning coins to better keep track of supply. + sdkErr = k.bankKeeper.SendCoinsFromModuleToModule(ctx, auctiontypes.ModuleName, auctiontypes.AuctionBurnModuleAccountName, sdk.NewCoins(amountToBurn)) + if sdkErr != nil { + ctx.Logger().Error(fmt.Sprintf("Auction error burning coins: %v", sdkErr)) + panic(sdkErr) + } + } + + // TODO + // Notify other modules (hook). + // ctx.Logger().Info(fmt.Sprintf("Auction %s notifying %d modules.", auction.Id, len(k.usageKeepers))) + // for _, keeper := range k.usageKeepers { + // ctx.Logger().Info(fmt.Sprintf("Auction %s notifying module %s.", auction.Id, keeper.ModuleName())) + // keeper.OnAuctionWinnerSelected(ctx, auction.Id) + // } + + return nil +} diff --git a/x/auction/module/abci.go b/x/auction/module/abci.go index 42d1b245..63701487 100644 --- a/x/auction/module/abci.go +++ b/x/auction/module/abci.go @@ -3,13 +3,14 @@ package module import ( "context" + sdk "github.com/cosmos/cosmos-sdk/types" + "git.vdb.to/cerc-io/laconic2d/x/auction/keeper" ) // EndBlocker is called every block func EndBlocker(ctx context.Context, k keeper.Keeper) error { - // TODO: Implement - // k.EndBlockerProcessAuctions(ctx) + sdkCtx := sdk.UnwrapSDKContext(ctx) - return nil + return k.EndBlockerProcessAuctions(sdkCtx) } -- 2.45.2