Skip to content

Commit

Permalink
Merge pull request #149 from tonkeeper/historical-apy
Browse files Browse the repository at this point in the history
Historical apy
  • Loading branch information
mr-tron committed Jul 21, 2023
2 parents 1c32333 + cfeaee1 commit a262860
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 23 deletions.
5 changes: 4 additions & 1 deletion api/example.http
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,7 @@ GET {{host}}/v2/accounts/EQDVcJxVsF27MHNKKDlP3iGcYxEU2TEt6QEmN-2MyEjMo7be/dns/ex
GET {{host}}/v2/blockchain/config

###
GET {{host}}/v2/blockchain/messages/81C7CC0C66452E5F1BC26A5D89B2B30AAB49B3B88EC9D035921B7DD3F343276F/transaction
GET {{host}}/v2/blockchain/messages/81C7CC0C66452E5F1BC26A5D89B2B30AAB49B3B88EC9D035921B7DD3F343276F/transaction

###
GET {{host}}/v2/staking/pool/EQANFsYyYn-GSZ4oajUJmboDURZU-udMHf9JxzO4vYM_hOh9/history
7 changes: 7 additions & 0 deletions internal/g/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,10 @@ func Opt[T any](t *T) struct {
Set bool
}{Value: *t, Set: true}
}

func Must[T any](t *T, err error) T {
if err != nil {
panic(err)
}
return *t
}
1 change: 1 addition & 0 deletions pkg/api/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type storage interface {
GetBlockTransactions(ctx context.Context, id tongo.BlockID) ([]*core.Transaction, error)
GetAccountTransactions(ctx context.Context, id tongo.AccountID, limit int, beforeLt, afterLt uint64) ([]*core.Transaction, error)
GetDnsExpiring(ctx context.Context, id tongo.AccountID, period *int) ([]core.DnsExpiring, error)
GetLogs(ctx context.Context, account tongo.AccountID, destination *tlb.MsgAddress, limit int, beforeLT uint64) ([]core.Message, error)

GetTrace(ctx context.Context, hash tongo.Bits256) (*core.Trace, error)
SearchTraces(ctx context.Context, a tongo.AccountID, limit int, beforeLT *int64, startTime *int64, endTime *int64) ([]tongo.Bits256, error)
Expand Down
49 changes: 48 additions & 1 deletion pkg/api/staking_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"errors"
"fmt"
"github.com/tonkeeper/opentonapi/internal/g"
"github.com/tonkeeper/tongo/boc"
"github.com/tonkeeper/tongo/tlb"

"github.com/tonkeeper/tongo"
Expand Down Expand Up @@ -243,5 +245,50 @@ func (h Handler) PoolsByNominators(ctx context.Context, params oas.PoolsByNomina
}

func (h Handler) StakingPoolHistory(ctx context.Context, params oas.StakingPoolHistoryParams) (oas.StakingPoolHistoryRes, error) {
return nil, fmt.Errorf("not implemented")
poolID, err := tongo.ParseAccountID(params.AccountID)
if err != nil {
return &oas.BadRequest{Error: err.Error()}, nil
}
_, err = h.storage.GetLiquidPool(ctx, poolID)
if errors.Is(err, core.ErrEntityNotFound) {
return &oas.NotFound{Error: err.Error()}, nil
}
logAddress := tlb.MsgAddress{SumType: "AddrExtern"}
logAddress.AddrExtern = &struct {
Len tlb.Uint9
ExternalAddress boc.BitString
}{Len: 256, ExternalAddress: g.Must(boc.BitStringFromFiftHex("0000000000000000000000000000000000000000000000000000000000000003"))}
logs, err := h.storage.GetLogs(ctx, poolID, &logAddress, 100, 0)
if err != nil {
return &oas.InternalError{Error: err.Error()}, nil
}
var result oas.StakingPoolHistoryOK
var prevTime uint32
for i, l := range logs {
if i == 0 {
prevTime = l.CreatedAt
continue
}
cells, err := boc.DeserializeBoc(l.Body)
if err != nil {
return &oas.InternalError{Error: err.Error()}, nil
}
var round struct {
RoundID tlb.Uint32
Borrowed tlb.Coins
Returned tlb.Coins
Profit tlb.SignedCoins
}
err = tlb.Unmarshal(cells[0], &round)
if err != nil {
return &oas.InternalError{Error: err.Error()}, nil
}
result.Apy = append(result.Apy, oas.ApyHistory{
Apy: float64(round.Profit) / float64(round.Borrowed) / float64(l.CreatedAt-prevTime) * 3600 * 24 * 365 * 100,
Time: int(l.CreatedAt),
})
prevTime = l.CreatedAt
fmt.Printf("%+v\n", round)
}
return &result, nil
}
22 changes: 12 additions & 10 deletions pkg/core/converters.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,11 +310,12 @@ func ConvertMessage(message tlb.Message, txLT uint64) (Message, error) {
CreatedLt: txLT,
Destination: dest,
},
ImportFee: int64(info.ImportFee),
Body: body,
OpCode: opCode,
DecodedBody: decodedBody,
Init: init,
SourceExtern: externalAddressFromTlb(info.Src),
ImportFee: int64(info.ImportFee),
Body: body,
OpCode: opCode,
DecodedBody: decodedBody,
Init: init,
}, nil
case "ExtOutMsgInfo":
info := message.Info.ExtOutMsgInfo
Expand All @@ -327,11 +328,12 @@ func ConvertMessage(message tlb.Message, txLT uint64) (Message, error) {
CreatedLt: info.CreatedLt,
Source: source,
},
Body: body,
DecodedBody: decodedBody,
CreatedAt: info.CreatedAt,
OpCode: opCode,
Init: []byte{},
DestinationExtern: externalAddressFromTlb(info.Dest),
Body: body,
DecodedBody: decodedBody,
CreatedAt: info.CreatedAt,
OpCode: opCode,
Init: []byte{},
}, nil
}
return Message{}, fmt.Errorf("invalid message")
Expand Down
37 changes: 26 additions & 11 deletions pkg/core/transactions.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package core

import (
"github.com/tonkeeper/tongo/boc"
"math/big"

"github.com/tonkeeper/tongo/abi"
Expand Down Expand Up @@ -123,17 +124,19 @@ func (m Message) IsEmission() bool {

type Message struct {
MessageID
IhrDisabled bool
Bounce bool
Bounced bool
Value int64
FwdFee int64
IhrFee int64
ImportFee int64
Init []byte
InitInterfaces []abi.ContractInterface
Body []byte
CreatedAt uint32
SourceExtern *ExternalAddress
DestinationExtern *ExternalAddress
IhrDisabled bool
Bounce bool
Bounced bool
Value int64
FwdFee int64
IhrFee int64
ImportFee int64
Init []byte
InitInterfaces []abi.ContractInterface
Body []byte
CreatedAt uint32
// OpCode is the first 32 bits of a message body indicating a possible operation.
OpCode *uint32
DecodedBody *DecodedMessageBody
Expand All @@ -144,3 +147,15 @@ type DecodedMessageBody struct {
Operation string
Value any
}

// ExternalAddress represents either the source or destination address of
// external inbound(ExtInMsg) or external outbound(ExtOutMsg) message correspondingly.
type ExternalAddress = boc.BitString

func externalAddressFromTlb(address tlb.MsgAddress) *ExternalAddress {
if address.SumType != "AddrExtern" {
return nil
}
external := address.AddrExtern.ExternalAddress
return &external
}
53 changes: 53 additions & 0 deletions pkg/litestorage/transactions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package litestorage

import (
"context"
"fmt"
"github.com/tonkeeper/opentonapi/pkg/core"
"github.com/tonkeeper/tongo"
"github.com/tonkeeper/tongo/tlb"
)

func (s *LiteStorage) GetLogs(ctx context.Context, account tongo.AccountID, destination *tlb.MsgAddress, limit int, beforeLT uint64) ([]core.Message, error) {
var messages []core.Message
if beforeLT == 0 {
beforeLT = 1 << 63
}
txLt := beforeLT
for {
txs, err := s.GetAccountTransactions(ctx, account, limit, txLt, 0)
if err != nil {
return nil, err
}
if len(txs) == 0 {
return messages, nil
}
fmt.Println(len(txs), txs[0].Lt, txs[1].Lt)
for _, tx := range txs {
txLt = tx.Lt
for _, m := range tx.OutMsgs {
if m.CreatedLt >= beforeLT {
continue
}
if m.Destination != nil {
continue
}
if destination != nil {
if destination.SumType == "AddrNone" && m.DestinationExtern != nil {
continue
}
if destination.SumType == "AddrExtern" && (m.DestinationExtern == nil || m.DestinationExtern.ToFiftHex() != destination.AddrExtern.ExternalAddress.ToFiftHex()) {
continue
}
}
messages = append(messages, m)
if len(messages) == limit {
return messages, nil
}
}
}
if len(txs) < limit {
return messages, nil
}
}
}
41 changes: 41 additions & 0 deletions pkg/sentry/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package sentry

import (
"fmt"
"os"
"time"
)

type SentryInfoData map[string]interface{}

var inited = false

func init() {
dsn := os.Getenv("SENTRY_DSN")
if dsn == "" {
return
}
err := sentry.Init(sentry.ClientOptions{

Check failure on line 18 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
Dsn: dsn,
TracesSampleRate: 1.0,
})
if err != nil {
fmt.Printf("failed to sentry init: %s", err)
}
inited = true
sentry.Flush(2 * time.Second)

Check failure on line 26 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
}

func Send(title string, data SentryInfoData, logLevel sentry.Level) {

Check failure on line 29 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
if !inited {
return
}

go func(localHub *sentry.Hub) {

Check failure on line 34 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
localHub.ConfigureScope(func(scope *sentry.Scope) {

Check failure on line 35 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
scope.SetLevel(logLevel)
scope.SetExtras(data)
})
localHub.CaptureMessage(title)
}(sentry.CurrentHub().Clone())

Check failure on line 40 in pkg/sentry/main.go

View workflow job for this annotation

GitHub Actions / unit-tests

undefined: sentry
}

0 comments on commit a262860

Please sign in to comment.