Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add airdrop tool #174

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,9 @@ dependency-graph.png
*.out
*.synctex.gz
contract_tests/*

#Airdrop tool
balance.json
rewards.json
balancenft.json
.env
145 changes: 145 additions & 0 deletions airdrop/akash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package main

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"

"github.com/eve-network/eve/airdrop/config"
"github.com/joho/godotenv"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"

"cosmossdk.io/math"

"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/cosmos/cosmos-sdk/types/query"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

func akash() ([]banktypes.Balance, []config.Reward) {
block_height := getLatestHeight(config.GetAkashConfig().RPC + "/status")

Check failure on line 27 in airdrop/akash.go

View workflow job for this annotation

GitHub Actions / lint

string `/status` has 6 occurrences, make it a constant (goconst)
err := godotenv.Load()
if err != nil {
fmt.Println("Error loading env:", err)
panic("")
}
grpcAddr := config.GetAkashConfig().GRPCAddr
grpcConn, err := grpc.Dial(grpcAddr, grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(nil).GRPCCodec())))
if err != nil {
panic(err)
}
defer grpcConn.Close()
stakingClient := stakingtypes.NewQueryClient(grpcConn)

delegators := []stakingtypes.DelegationResponse{}

validators := getValidators(stakingClient, block_height)
fmt.Println("Validators: ", len(validators))
for validatorIndex, validator := range validators {
var header metadata.MD
delegationsResponse, _ := stakingClient.ValidatorDelegations(
metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, block_height), // Add metadata to request
&stakingtypes.QueryValidatorDelegationsRequest{
ValidatorAddr: validator.OperatorAddress,
Pagination: &query.PageRequest{
CountTotal: true,
Limit: LIMIT_PER_PAGE,
},
},
grpc.Header(&header), // Retrieve header from response
)
total := delegationsResponse.Pagination.Total
fmt.Println("Response ", len(delegationsResponse.DelegationResponses))
fmt.Println("Akash validator "+strconv.Itoa(validatorIndex)+" ", total)
delegators = append(delegators, delegationsResponse.DelegationResponses...)
}

usd := math.LegacyMustNewDecFromStr("20")

apiUrl := API_COINGECKO + config.GetAkashConfig().CoinId + "&vs_currencies=usd"

Check failure on line 66 in airdrop/akash.go

View workflow job for this annotation

GitHub Actions / lint

string `&vs_currencies=usd` has 10 occurrences, make it a constant (goconst)
tokenInUsd := fetchAkashTokenPrice(apiUrl)
tokenIn20Usd := usd.QuoTruncate(tokenInUsd)

rewardInfo := []config.Reward{}
balanceInfo := []banktypes.Balance{}

totalTokenDelegate := math.LegacyMustNewDecFromStr("0")
for _, delegator := range delegators {
validatorIndex := findValidatorInfo(validators, delegator.Delegation.ValidatorAddress)
validatorInfo := validators[validatorIndex]
token := (delegator.Delegation.Shares.MulInt(validatorInfo.Tokens)).QuoTruncate(validatorInfo.DelegatorShares)
if token.LT(tokenIn20Usd) {
continue
}
totalTokenDelegate = totalTokenDelegate.Add(token)
}
eveAirdrop := math.LegacyMustNewDecFromStr(EVE_AIRDROP)
testAmount, _ := math.LegacyNewDecFromStr("0")
for _, delegator := range delegators {
validatorIndex := findValidatorInfo(validators, delegator.Delegation.ValidatorAddress)
validatorInfo := validators[validatorIndex]
token := (delegator.Delegation.Shares.MulInt(validatorInfo.Tokens)).QuoTruncate(validatorInfo.DelegatorShares)
if token.LT(tokenIn20Usd) {
continue
}
eveAirdrop := (eveAirdrop.MulInt64(int64(config.GetAkashConfig().Percent))).QuoInt64(100).Mul(token).QuoTruncate(totalTokenDelegate)
eveBech32Address := convertBech32Address(delegator.Delegation.DelegatorAddress)
rewardInfo = append(rewardInfo, config.Reward{
Address: delegator.Delegation.DelegatorAddress,
EveAddress: eveBech32Address,
Shares: delegator.Delegation.Shares,
Token: token,
EveAirdropToken: eveAirdrop,
ChainId: config.GetAkashConfig().ChainID,
})
testAmount = eveAirdrop.Add(testAmount)
balanceInfo = append(balanceInfo, banktypes.Balance{
Address: eveBech32Address,
Coins: sdk.NewCoins(sdk.NewCoin("eve", eveAirdrop.TruncateInt())),
})
}
fmt.Println("Akash ", testAmount)
// Write delegations to file
// fileForDebug, _ := json.MarshalIndent(rewardInfo, "", " ")
// _ = os.WriteFile("rewards.json", fileForDebug, 0644)

// fileBalance, _ := json.MarshalIndent(balanceInfo, "", " ")
// _ = os.WriteFile("balance.json", fileBalance, 0644)
return balanceInfo, rewardInfo
}

func fetchAkashTokenPrice(apiUrl string) math.LegacyDec {
// Make a GET request to the API
response, err := http.Get(apiUrl) //nolint
if err != nil {
fmt.Println("Error making GET request:", err)
panic("")
}
defer response.Body.Close()

// Read the response body
responseBody, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
panic("")
}

var data config.AkashPrice

// Unmarshal the JSON byte slice into the defined struct
err = json.Unmarshal(responseBody, &data)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
panic("")
}

tokenInUsd := math.LegacyMustNewDecFromStr(data.Token.USD.String())
return tokenInUsd
}
122 changes: 122 additions & 0 deletions airdrop/bostrom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"

"github.com/eve-network/eve/airdrop/config"

"cosmossdk.io/math"

sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)

func bostrom() ([]banktypes.Balance, []config.Reward) {
delegators := []stakingtypes.DelegationResponse{}

rpc := config.GetBostromConfig().API + "/cosmos/staking/v1beta1/validators?pagination.limit=" + strconv.Itoa(LIMIT_PER_PAGE) + "&pagination.count_total=true"

Check failure on line 23 in airdrop/bostrom.go

View workflow job for this annotation

GitHub Actions / lint

string `/cosmos/staking/v1beta1/validators?pagination.limit=` has 4 occurrences, make it a constant (goconst)
validatorsResponse := fetchValidators(rpc)
validators := validatorsResponse.Validators
fmt.Println("Validators: ", len(validators))
for validatorIndex, validator := range validators {
url := config.GetBostromConfig().API + "/cosmos/staking/v1beta1/validators/" + validator.OperatorAddress + "/delegations?pagination.limit=" + strconv.Itoa(LIMIT_PER_PAGE) + "&pagination.count_total=true"

Check failure on line 28 in airdrop/bostrom.go

View workflow job for this annotation

GitHub Actions / lint

string `/delegations?pagination.limit=` has 5 occurrences, make it a constant (goconst)
delegations, total := fetchDelegations(url)
fmt.Println(validator.OperatorAddress)
fmt.Println("Response ", len(delegations))
fmt.Println("Bostrom validator "+strconv.Itoa(validatorIndex)+" ", total)
delegators = append(delegators, delegations...)
}

usd := math.LegacyMustNewDecFromStr("20")

apiUrl := API_COINGECKO + config.GetBostromConfig().CoinId + "&vs_currencies=usd"
tokenInUsd := fetchBostromTokenPrice(apiUrl)
tokenIn20Usd := usd.QuoTruncate(tokenInUsd)

rewardInfo := []config.Reward{}
balanceInfo := []banktypes.Balance{}

totalTokenDelegate := math.LegacyMustNewDecFromStr("0")
for _, delegator := range delegators {
validatorIndex := findValidatorInfoCustomType(validators, delegator.Delegation.ValidatorAddress)
validatorInfo := validators[validatorIndex]
token := (delegator.Delegation.Shares.MulInt(validatorInfo.Tokens)).QuoTruncate(validatorInfo.DelegatorShares)
if token.LT(tokenIn20Usd) {
continue
}
totalTokenDelegate = totalTokenDelegate.Add(token)
}
eveAirdrop := math.LegacyMustNewDecFromStr(EVE_AIRDROP)
testAmount, _ := math.LegacyNewDecFromStr("0")
for _, delegator := range delegators {
validatorIndex := findValidatorInfoCustomType(validators, delegator.Delegation.ValidatorAddress)
validatorInfo := validators[validatorIndex]
token := (delegator.Delegation.Shares.MulInt(validatorInfo.Tokens)).QuoTruncate(validatorInfo.DelegatorShares)
if token.LT(tokenIn20Usd) {
continue
}
eveAirdrop := (eveAirdrop.MulInt64(int64(config.GetBostromConfig().Percent))).QuoInt64(100).Mul(token).QuoTruncate(totalTokenDelegate)
eveBech32Address := convertBech32Address(delegator.Delegation.DelegatorAddress)
rewardInfo = append(rewardInfo, config.Reward{
Address: delegator.Delegation.DelegatorAddress,
EveAddress: eveBech32Address,
Shares: delegator.Delegation.Shares,
Token: token,
EveAirdropToken: eveAirdrop,
ChainId: config.GetBostromConfig().ChainID,
})
testAmount = eveAirdrop.Add(testAmount)
balanceInfo = append(balanceInfo, banktypes.Balance{
Address: eveBech32Address,
Coins: sdk.NewCoins(sdk.NewCoin("eve", eveAirdrop.TruncateInt())),
})
}
fmt.Println("bostrom ", testAmount)
// Write delegations to file
// fileForDebug, _ := json.MarshalIndent(rewardInfo, "", " ")
// _ = os.WriteFile("rewards.json", fileForDebug, 0644)

// fileBalance, _ := json.MarshalIndent(balanceInfo, "", " ")
// _ = os.WriteFile("balance.json", fileBalance, 0644)
return balanceInfo, rewardInfo
}

func fetchBostromTokenPrice(apiUrl string) math.LegacyDec {
// Make a GET request to the API
response, err := http.Get(apiUrl) //nolint
if err != nil {
fmt.Println("Error making GET request:", err)
panic("")
}
defer response.Body.Close()

// Read the response body
responseBody, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
panic("")
}

var data config.BostromPrice

// Unmarshal the JSON byte slice into the defined struct
err = json.Unmarshal(responseBody, &data)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
panic("")
}
rawPrice := strings.Split(data.Token.USD.String(), "e-")
base := rawPrice[0]
power := rawPrice[1]
powerInt, _ := strconv.ParseUint(power, 10, 64)
baseDec, _ := math.LegacyNewDecFromStr(base)
tenDec, _ := math.LegacyNewDecFromStr("10")
tokenInUsd := baseDec.Quo(tenDec.Power(powerInt))
return tokenInUsd
}
Loading
Loading