process-transfer.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package p
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "fmt"
  7. "log"
  8. "math"
  9. "strconv"
  10. "time"
  11. "github.com/certusone/wormhole/node/pkg/vaa"
  12. "github.com/cosmos/cosmos-sdk/types/bech32"
  13. "cloud.google.com/go/bigtable"
  14. "github.com/gagliardetto/solana-go"
  15. )
  16. // terra native tokens do not have a bech32 address like cw20s do, handle them manually.
  17. var tokenAddressExceptions = map[string]string{
  18. "0100000000000000000000000000000000000000000000000000000075757364": "ust",
  19. "010000000000000000000000000000000000000000000000000000756c756e61": "uluna",
  20. }
  21. // returns a pair of dates before and after the input time.
  22. // useful for creating a time rage for querying historical price APIs.
  23. func rangeFromTime(t time.Time, hours int) (start time.Time, end time.Time) {
  24. duration := time.Duration(hours) * time.Hour
  25. return t.Add(-duration), t.Add(duration)
  26. }
  27. func transformHexAddressToNative(chain vaa.ChainID, address string) string {
  28. switch chain {
  29. case vaa.ChainIDSolana:
  30. addr, err := hex.DecodeString(address)
  31. if err != nil {
  32. log.Fatalf("failed to decode solana string: %v", err)
  33. }
  34. if len(addr) != 32 {
  35. log.Fatalf("address must be 32 bytes. address: %v", address)
  36. }
  37. solPk := solana.PublicKeyFromBytes(addr[:])
  38. return solPk.String()
  39. case vaa.ChainIDEthereum,
  40. vaa.ChainIDBSC,
  41. vaa.ChainIDPolygon:
  42. addr := fmt.Sprintf("0x%v", address[(len(address)-40):])
  43. return addr
  44. case vaa.ChainIDTerra:
  45. // handle terra native assets manually
  46. if val, ok := tokenAddressExceptions[address]; ok {
  47. return val
  48. }
  49. trimmed := address[(len(address) - 40):]
  50. data, decodeErr := hex.DecodeString(trimmed)
  51. if decodeErr != nil {
  52. fmt.Printf("failed to decode unpadded string: %v\n", decodeErr)
  53. }
  54. encodedAddr, convertErr := bech32.ConvertAndEncode("terra", data)
  55. if convertErr != nil {
  56. fmt.Println("convert error from cosmos bech32. err", convertErr)
  57. }
  58. return encodedAddr
  59. default:
  60. panic(fmt.Errorf("cannot process address for unknown chain: %v", chain))
  61. }
  62. }
  63. // ProcessTransfer is triggered by a PubSub message, once a TokenTransferPayload is written to a row.
  64. func ProcessTransfer(ctx context.Context, m PubSubMessage) error {
  65. data := string(m.Data)
  66. if data == "" {
  67. return fmt.Errorf("no data to process in message")
  68. }
  69. signedVaa, err := vaa.Unmarshal(m.Data)
  70. if err != nil {
  71. log.Println("failed Unmarshaling VAA")
  72. return err
  73. }
  74. // create the bigtable identifier from the VAA data
  75. rowKey := makeRowKey(signedVaa.EmitterChain, signedVaa.EmitterAddress, signedVaa.Sequence)
  76. row, err := tbl.ReadRow(ctx, rowKey)
  77. if err != nil {
  78. log.Fatalf("Could not read row with key %s: %v", rowKey, err)
  79. }
  80. // get the payload data for this transfer
  81. var tokenAddress string
  82. var tokenChain vaa.ChainID
  83. var amount string
  84. for _, item := range row[columnFamilies[2]] {
  85. switch item.Column {
  86. case "TokenTransferPayload:OriginAddress":
  87. tokenAddress = string(item.Value)
  88. case "TokenTransferPayload:OriginChain":
  89. chainInt, _ := strconv.ParseUint(string(item.Value), 10, 32)
  90. chainID := vaa.ChainID(chainInt)
  91. tokenChain = chainID
  92. case "TokenTransferPayload:Amount":
  93. amount = string(item.Value)
  94. }
  95. }
  96. // lookup the asset meta for this transfer.
  97. // find an AssetMeta message that matches the OriginChain & TokenAddress of the transfer
  98. var result bigtable.Row
  99. chainIDPrefix := fmt.Sprintf("%d", tokenChain) // create a string containing the tokenChain chainID, ie "2"
  100. queryErr := tbl.ReadRows(ctx, bigtable.PrefixRange(chainIDPrefix), func(row bigtable.Row) bool {
  101. result = row
  102. return true
  103. }, bigtable.RowFilter(
  104. bigtable.ChainFilters(
  105. bigtable.FamilyFilter(columnFamilies[3]),
  106. bigtable.ColumnFilter("TokenAddress"),
  107. bigtable.ValueFilter(tokenAddress),
  108. )))
  109. if queryErr != nil {
  110. log.Fatalf("failed to read rows: %v", queryErr)
  111. }
  112. if result == nil {
  113. log.Printf("did not find AssetMeta row for tokenAddress: %v. Transfer rowKey: %v\n", tokenAddress, rowKey)
  114. return fmt.Errorf("did not find AssetMeta row for tokenAddress %v", tokenAddress)
  115. }
  116. // now get the entire row
  117. assetMetaRow, assetMetaErr := tbl.ReadRow(ctx, result.Key(), bigtable.RowFilter(bigtable.LatestNFilter(1)))
  118. if assetMetaErr != nil {
  119. log.Fatalf("Could not read row with key %s: %v", rowKey, assetMetaErr)
  120. }
  121. if _, ok := assetMetaRow[columnFamilies[3]]; !ok {
  122. log.Println("did not find AssetMeta matching TokenAddress", tokenAddress)
  123. return fmt.Errorf("did not find AssetMeta matching TokenAddress %v", tokenAddress)
  124. }
  125. // get AssetMeta values
  126. var decimals int
  127. var symbol string
  128. var name string
  129. var coinId string
  130. var nativeTokenAddress string
  131. for _, item := range assetMetaRow[columnFamilies[3]] {
  132. switch item.Column {
  133. case "AssetMetaPayload:Decimals":
  134. decimalStr := string(item.Value)
  135. dec, err := strconv.Atoi(decimalStr)
  136. if err != nil {
  137. log.Fatalf("failed parsing decimals of row %v", assetMetaRow.Key())
  138. }
  139. decimals = dec
  140. case "AssetMetaPayload:Symbol":
  141. symbol = string(item.Value)
  142. case "AssetMetaPayload:Name":
  143. name = string(item.Value)
  144. case "AssetMetaPayload:CoinGeckoCoinId":
  145. coinId = string(item.Value)
  146. case "AssetMetaPayload:NativeAddress":
  147. nativeTokenAddress = string(item.Value)
  148. }
  149. }
  150. if coinId == "" {
  151. log.Printf("no coinId for symbol: %v, nothing to lookup.\n", symbol)
  152. // no coinId for this asset, cannot get price from coingecko.
  153. return nil
  154. }
  155. // transfers created by the bridge UI will have at most 8 decimals.
  156. if decimals > 8 {
  157. decimals = 8
  158. }
  159. // ensure amount string is long enough
  160. if len(amount) < decimals {
  161. amount = fmt.Sprintf("%0*v", decimals, amount)
  162. }
  163. intAmount := amount[:len(amount)-decimals]
  164. decAmount := amount[len(amount)-decimals:]
  165. calculatedAmount := intAmount + "." + decAmount
  166. timestamp := signedVaa.Timestamp.UTC()
  167. price, _ := fetchCoinGeckoPrice(coinId, timestamp)
  168. if price == 0 {
  169. // no price found, don't save
  170. log.Printf("no price for symbol: %v, name: %v, address: %v, at: %v. rowKey: %v\n", symbol, name, nativeTokenAddress, timestamp.String(), rowKey)
  171. return nil
  172. }
  173. // convert the amount string so it can be used for math
  174. amountFloat, convErr := strconv.ParseFloat(calculatedAmount, 64)
  175. if convErr != nil {
  176. log.Fatalf("failed parsing calculatedAmount '%v' to float64. err %v", calculatedAmount, convErr)
  177. }
  178. notional := amountFloat * price
  179. notionalStr := fmt.Sprintf("%f", notional)
  180. log.Printf("processed transfer of $%0.2f = %v %v * $%0.2f\n", notional, calculatedAmount, symbol, price)
  181. // write to BigTable
  182. colFam := columnFamilies[5]
  183. mutation := bigtable.NewMutation()
  184. ts := bigtable.Now()
  185. mutation.Set(colFam, "Amount", ts, []byte(calculatedAmount))
  186. mutation.Set(colFam, "Decimals", ts, []byte(fmt.Sprint(decimals)))
  187. var notionalbuf [8]byte
  188. binary.BigEndian.PutUint64(notionalbuf[:], math.Float64bits(notional))
  189. mutation.Set(colFam, "NotionalUSD", ts, notionalbuf[:])
  190. mutation.Set(colFam, "NotionalUSDStr", ts, []byte(notionalStr))
  191. var priceBuf [8]byte
  192. binary.BigEndian.PutUint64(priceBuf[:], math.Float64bits(price))
  193. mutation.Set(colFam, "TokenPriceUSD", ts, priceBuf[:])
  194. mutation.Set(colFam, "TokenPriceUSDStr", ts, []byte(fmt.Sprintf("%f", price)))
  195. mutation.Set(colFam, "TransferTimestamp", ts, []byte(timestamp.String()))
  196. mutation.Set(colFam, "OriginSymbol", ts, []byte(symbol))
  197. mutation.Set(colFam, "OriginName", ts, []byte(name))
  198. mutation.Set(colFam, "OriginTokenAddress", ts, []byte(nativeTokenAddress))
  199. // TODO - find the symbol & name of the asset on the target chain?
  200. // mutation.Set(colFam, "TargetSymbol", ts, []byte())
  201. // mutation.Set(colFam, "TargetName", ts, []byte())
  202. // conditional mutation - don't write if row already has an Amount value.
  203. filter := bigtable.ChainFilters(
  204. bigtable.FamilyFilter(colFam),
  205. bigtable.ColumnFilter("Amount"))
  206. conditionalMutation := bigtable.NewCondMutation(filter, nil, mutation)
  207. writeErr := tbl.Apply(ctx, rowKey, conditionalMutation)
  208. if writeErr != nil {
  209. log.Printf("Failed to write TokenTransferDetails for %v to BigTable. err: %v\n", rowKey, writeErr)
  210. return writeErr
  211. }
  212. // success
  213. return nil
  214. }