github.com/stellar/stellar-etl@v1.0.1-0.20240312145900-4874b6bf2b89/internal/toid/synt_offer_id.go (about)

     1  package toid
     2  
     3  type OfferIDType uint64
     4  
     5  const (
     6  	CoreOfferIDType OfferIDType = 0
     7  	TOIDType        OfferIDType = 1
     8  
     9  	mask uint64 = 0xC000000000000000
    10  )
    11  
    12  // Taken from https://github.com/stellar/go/tree/master/services/horizon/internal/db2/history
    13  
    14  // EncodeOfferId creates synthetic offer ids to be used by trade resources
    15  //
    16  // This is required because stellar-core does not allocate offer ids for immediately filled offers,
    17  // while clients expect them for aggregated views.
    18  //
    19  // The encoded value is of type int64 for sql compatibility. The 2nd bit is used to differentiate between stellar-core
    20  // offer ids and operation ids, which are toids.
    21  //
    22  // Due to the 2nd bit being used, the largest possible toid is:
    23  // 0011111111111111111111111111111100000000000000000001000000000001
    24  // \          ledger              /\    transaction   /\    op    /
    25  //            = 1073741823
    26  //              with avg. 5 sec close time will reach in ~170 years
    27  func EncodeOfferId(id uint64, typ OfferIDType) int64 {
    28  	// First ensure the bits we're going to change are 0s
    29  	if id&mask != 0 {
    30  		panic("Value too big to encode")
    31  	}
    32  	return int64(id | uint64(typ)<<62)
    33  }
    34  
    35  // DecodeOfferID performs the reverse operation of EncodeOfferID
    36  func DecodeOfferID(encodedId int64) (uint64, OfferIDType) {
    37  	if encodedId < 0 {
    38  		panic("Negative offer ids can not be decoded")
    39  	}
    40  	return uint64(encodedId<<2) >> 2, OfferIDType(encodedId >> 62)
    41  }