Skip to content

Commit

Permalink
I balances (#208)
Browse files Browse the repository at this point in the history
* add balance

* update BlockData

* update parseevent
  • Loading branch information
AstaFrode authored May 14, 2024
1 parent 97865cc commit 452883c
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 51 deletions.
45 changes: 45 additions & 0 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"context"
"io"
"log"
"math"
"math/big"
"os"
"sync"
"time"
Expand Down Expand Up @@ -41,6 +43,7 @@ type ChainClient struct {
networkEnv string
signatureAcc string
name string
balance uint64
rpcState bool
}

Expand Down Expand Up @@ -113,6 +116,22 @@ func NewChainClient(ctx context.Context, name string, rpcs []string, mnemonic st
if err != nil {
return nil, err
}
accInfo, err := chainClient.QueryAccountInfoByAccountID(chainClient.keyring.PublicKey, -1)
if err != nil {
return nil, err
}
if len(accInfo.Data.Free.Bytes()) <= 0 {
chainClient.balance = 0
} else {
free_bi, _ := new(big.Int).SetString(accInfo.Data.Free.String(), 10)
minBanlance_bi, _ := new(big.Int).SetString(MinTransactionBalance, 10)
free_bi = free_bi.Div(free_bi, minBanlance_bi)
if free_bi.IsUint64() {
chainClient.balance = free_bi.Uint64()
} else {
chainClient.balance = math.MaxUint64
}
}
}
properties, err := chainClient.SystemProperties()
if err != nil {
Expand Down Expand Up @@ -198,6 +217,16 @@ func (c *ChainClient) GetURI() string {
return c.keyring.URI
}

// GetBalances get current account balance, the unit is CESS
func (c *ChainClient) GetBalances() uint64 {
return c.balance
}

// SetBalances update current account balance, the unit is CESS
func (c *ChainClient) SetBalances(balance uint64) {
c.balance = balance
}

// Sign with the mnemonic of your current account
func (c *ChainClient) Sign(msg []byte) ([]byte, error) {
return signature.Sign(msg, c.keyring.URI)
Expand Down Expand Up @@ -232,7 +261,23 @@ func (c *ChainClient) ReconnectRpc() error {
if err != nil {
return err
}
accInfo, err := c.QueryAccountInfoByAccountID(c.keyring.PublicKey, -1)
if err != nil {
return err
}
c.SetRpcState(true)
if len(accInfo.Data.Free.Bytes()) <= 0 {
c.balance = 0
} else {
free_bi, _ := new(big.Int).SetString(accInfo.Data.Free.String(), 10)
minBanlance_bi, _ := new(big.Int).SetString(MinTransactionBalance, 10)
free_bi = free_bi.Div(free_bi, minBanlance_bi)
if free_bi.IsUint64() {
c.balance = free_bi.Uint64()
} else {
c.balance = math.MaxUint64
}
}
return nil
}

Expand Down
3 changes: 2 additions & 1 deletion chain/chainer.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ type Chainer interface {
GetTokenSymbol() string
GetNetworkEnv() string
GetURI() string
GetBalances() uint64
SetBalances(balance uint64)
Sign(msg []byte) ([]byte, error)
Verify(msg []byte, sig []byte) (bool, error)
ReconnectRpc() error
Expand All @@ -154,7 +156,6 @@ type Chainer interface {
// event
DecodeEventNameFromBlock(block uint64) ([]string, error)
DecodeEventNameFromBlockhash(blockhash types.Hash) ([]string, error)
// retrieve event
RetrieveEvent_Audit_SubmitIdleProof(blockhash types.Hash) (Event_SubmitIdleProof, error)
RetrieveEvent_Audit_SubmitServiceProof(blockhash types.Hash) (Event_SubmitServiceProof, error)
RetrieveEvent_Audit_SubmitIdleVerifyResult(blockhash types.Hash) (Event_SubmitIdleVerifyResult, error)
Expand Down
44 changes: 44 additions & 0 deletions chain/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -2286,6 +2286,30 @@ func (c *ChainClient) ParseBlockData(blocknumber uint64) (BlockData, error) {
Miner: acc,
Result: result,
})
} else if e.Name == SminerRegisterPoisKey {
acc, err := ParseAccountFromEvent(e)
if err != nil {
return blockdata, err
}
blockdata.MinerRegPoiskeys = append(blockdata.MinerRegPoiskeys, MinerRegPoiskey{
ExtrinsicHash: blockdata.Extrinsics[extrinsicIndex].Hash,
Miner: acc,
})
} else if e.Name == OssOssRegister {
acc, err := ParseAccountFromEvent(e)
if err != nil {
return blockdata, err
}
blockdata.GatewayReg = append(blockdata.GatewayReg, GatewayReg{
ExtrinsicHash: blockdata.Extrinsics[extrinsicIndex].Hash,
Account: acc,
})
} else if e.Name == FileBankStorageCompleted {
fid, err := ParseStringFromEvent(e)
if err != nil {
return blockdata, err
}
blockdata.StorageCompleted = append(blockdata.StorageCompleted, fid)
} else if e.Name == SystemExtrinsicSuccess {
extInfo.Events = append(make([]string, 0), eventsBuf...)
extInfo.Name = name
Expand Down Expand Up @@ -2398,6 +2422,26 @@ func (c *ChainClient) ParseBlockData(blocknumber uint64) (BlockData, error) {
break
}
}
for m := 0; m < len(blockdata.MinerRegPoiskeys); m++ {
if blockdata.MinerRegPoiskeys[m].ExtrinsicHash == blockdata.Extrinsics[extrinsicIndex].Hash {
if len(blockdata.MinerRegPoiskeys) == 1 {
blockdata.MinerRegPoiskeys = nil
} else {
blockdata.MinerRegPoiskeys = append(blockdata.MinerRegPoiskeys[:m], blockdata.MinerRegPoiskeys[m+1:]...)
}
break
}
}
for m := 0; m < len(blockdata.GatewayReg); m++ {
if blockdata.GatewayReg[m].ExtrinsicHash == blockdata.Extrinsics[extrinsicIndex].Hash {
if len(blockdata.GatewayReg) == 1 {
blockdata.GatewayReg = nil
} else {
blockdata.GatewayReg = append(blockdata.GatewayReg[:m], blockdata.GatewayReg[m+1:]...)
}
break
}
}
extInfo.Events = append(make([]string, 0), eventsBuf...)
extInfo.Name = name
extInfo.Signer = signer
Expand Down
13 changes: 13 additions & 0 deletions chain/event_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,7 @@ type BlockData struct {
SysEvents []string
NewAccounts []string
GenChallenge []string
StorageCompleted []string
MinerReg []MinerRegInfo
Extrinsics []ExtrinsicsInfo
TransferInfo []TransferInfo
Expand All @@ -654,6 +655,8 @@ type BlockData struct {
SubmitIdleResult []SubmitIdleResult
SubmitServiceResult []SubmitServiceResult
Punishment []Punishment
MinerRegPoiskeys []MinerRegPoiskey
GatewayReg []GatewayReg
}

type ExtrinsicsInfo struct {
Expand Down Expand Up @@ -731,3 +734,13 @@ type Punishment struct {
To string
Amount string
}

type MinerRegPoiskey struct {
ExtrinsicHash string
Miner string
}

type GatewayReg struct {
ExtrinsicHash string
Account string
}
8 changes: 3 additions & 5 deletions chain/pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,16 @@ const DOT = "."
// Unit precision of CESS token
const TokenPrecision_CESS = "000000000000000000"

// the minimum account balance required for transaction
const MinTransactionBalance = "1000000000000000000"

const StakingStakePerTiB = 4000

const BlockIntervalSec = 6

// BlockInterval is the time interval for generating blocks, in seconds
const BlockInterval = time.Second * time.Duration(BlockIntervalSec)

const MaxSubmitedIdleFileMeta = 30

const PublicDeoss = "http://deoss-pub-gateway.cess.cloud/"
const PublicDeossAccount = "cXhwBytXqrZLr1qM5NHJhCzEMckSTzNKw17ci2aHft6ETSQm9"

const TreasuryAccount = "cXhT9Xh3DhrBMDmXcGeMPDmTzDm1J8vDxBtKvogV33pPshnWS"

// pallet names
Expand Down
7 changes: 6 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ const (
MaxDomainNameLength = 100
)

// default name
const (
// default name
CharacterName_Default = "cess-sdk-go"

// offcial gateway address
PublicGatewayAddr = "http://deoss-pub-gateway.cess.cloud/"
// offcial gateway account
PublicGatewayAccount = "cXhwBytXqrZLr1qM5NHJhCzEMckSTzNKw17ci2aHft6ETSQm9"
)
57 changes: 13 additions & 44 deletions example/parseEvent/parseevent.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,6 @@ type MyEvent struct {
}

func main() {
// fmt.Println(time.Now().UTC().Truncate(24 * time.Hour).Add(time.Second).UnixMilli())
// fmt.Println(time.UnixMilli(1706699208000).UTC().Truncate(24 * time.Hour).Add(time.Hour * 24).UnixMilli())
// fmt.Println(time.Now().UTC())
// fmt.Println(time.Now().UTC().Hour())
// fmt.Println(time.Now().UTC().Minute())
// return
sdk, err := cess.New(
context.Background(),
cess.ConnectRpcAddrs(RPC_ADDRS),
Expand All @@ -46,18 +40,7 @@ func main() {
if err != nil {
panic(err)
}

defer sdk.Close()
// fmeta, err := sdk.QueryFileMetadataByBlock("bf7e61cf8abe365dc30e525be5058fd3f502245322300d76fe169c9292c6ba48", 2)
// if err != nil {
// log.Fatal(err)
// }
// for _, segment := range fmeta.SegmentList {
// for _, fragment := range segment.FragmentList {
// fmt.Println(utils.EncodePublicKeyAsCessAccount(fragment.Miner[:]))
// }
// }
// return
sdk.InitExtrinsicsName()

// RetrieveEvent_FileBank_CalculateReport
Expand Down Expand Up @@ -90,7 +73,7 @@ func main() {

//fmt.Println(sdk.RetrieveAllEventFromBlock(bhash))

blockData, err := sdk.ParseBlockData(12975)
blockData, err := sdk.ParseBlockData(72094)
if err != nil {
fmt.Println("ERR: ", err)
return
Expand Down Expand Up @@ -145,6 +128,18 @@ func main() {
fmt.Println(" SubmitServiceResult miner: ", v.Miner)
fmt.Println(" SubmitServiceResult miner result: ", v.Result)
}
fmt.Println("MinerRegPoiskeys:")
for _, v := range blockData.MinerRegPoiskeys {
fmt.Println(" MinerRegPoiskeys miner: ", v.Miner)
}
fmt.Println("GatewayReg:")
for _, v := range blockData.GatewayReg {
fmt.Println(" GatewayReg account: ", v.Account)
}
fmt.Println("StorageCompleted:")
for _, v := range blockData.StorageCompleted {
fmt.Println(" StorageCompleted fid: ", v)
}
fmt.Println("system events: ", blockData.SysEvents)
fmt.Println("transfer info: ", blockData.TransferInfo)
fmt.Println("minerReg info: ", blockData.MinerReg)
Expand All @@ -156,30 +151,4 @@ func main() {
fmt.Println("timpstamp: ", blockData.Timestamp)
fmt.Println("allGasFee: ", blockData.AllGasFee)
fmt.Println("IsNewEra: ", blockData.IsNewEra)
return
sysEvents, extrinsics, transferInfo, minerReg, newAccounts, blockhash, preHash, extHash, stHash, allGasFee, t, err := sdk.RetrieveBlockAndAll(351)
if err != nil {
panic(err)
}
fmt.Println(" --------- ")

fmt.Println("extrinsics:")
for k, v := range extrinsics {
fmt.Println(" ", k, ": ", v.Name)
fmt.Println(" Singer: ", v.Signer)
fmt.Println(" Hash: ", v.Hash)
fmt.Println(" FeePaid: ", v.FeePaid)
fmt.Println(" Events: ", v.Events)
}
fmt.Println("system events: ", sysEvents)
fmt.Println("transfer info: ", transferInfo)
fmt.Println("minerReg info: ", minerReg)
fmt.Println("newAccounts info: ", newAccounts)
fmt.Println("blockhash: ", blockhash)
fmt.Println("preHash: ", preHash)
fmt.Println("extHash: ", extHash)
fmt.Println("stHash: ", stHash)
fmt.Println("timpstamp: ", t)
fmt.Println("allGasFee: ", allGasFee)
//fmt.Println(sdk.RetrieveEvent_FileBank_CalculateReport(bhash))
}

0 comments on commit 452883c

Please sign in to comment.