Skip to content

Commit

Permalink
Go fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
b-j-roberts committed Feb 10, 2025
1 parent b9fc032 commit 8dd8b46
Show file tree
Hide file tree
Showing 6 changed files with 261 additions and 260 deletions.
143 changes: 72 additions & 71 deletions apps/backend/cmd/inscriber/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,75 +14,76 @@ import (
)

type FeeRateResponse struct {
FastestFee int `json:"fastestFee"`
HalfHourFee int `json:"halfHourFee"`
HourFee int `json:"hourFee"`
EconomyFee int `json:"economyFee"`
MinimumFee int `json:"minimumFee"`
FastestFee int `json:"fastestFee"`
HalfHourFee int `json:"halfHourFee"`
HourFee int `json:"hourFee"`
EconomyFee int `json:"economyFee"`
MinimumFee int `json:"minimumFee"`
}

type BtcToStrkResponse struct {
Status string `json:"status"`
Btc float64 `json:"BTC"`
Strk float64 `json:"STRK"`
Status string `json:"status"`
Btc float64 `json:"BTC"`
Strk float64 `json:"STRK"`
}

var strkPerVbyte big.Int

func updateStrkPerVbyte() {
btcToSats := 100000000.0
btcToStrkResponse, err := http.Get("https://api.coinconvert.net/convert/btc/strk?amount=1")
if err != nil {
fmt.Println("Error while querying the backend for the conversion rate")
return
}
btcToStrkJson, err := routeutils.ReadJsonResponse[BtcToStrkResponse](btcToStrkResponse)
if err != nil {
fmt.Println("Error while parsing the response as Json")
return
}
btcToStrk := btcToStrkJson.Strk

satsFeeRateResponse, err := http.Get("https://mempool.space/api/v1/fees/recommended")
if err != nil {
fmt.Println("Error while querying the backend for the fee rate")
return
}
satsFeeRateJson, err := routeutils.ReadJsonResponse[FeeRateResponse](satsFeeRateResponse)
if err != nil {
fmt.Println("Error while parsing the response as Json")
return
}
satsFeeRate := float64(satsFeeRateJson.FastestFee)
strkPerVbyteFloat := satsFeeRate * btcToStrk / btcToSats

// strkDecimals := big.NewFloat(1000000000000000000) // 10^18
strkPerVByteU256 := big.NewFloat(strkPerVbyteFloat)
// strkPerVByteU256.Mul(strkPerVByteU256, strkDecimals)
strkPerVByteU256.Int(&strkPerVbyte)
btcToSats := 100000000.0
btcToStrkResponse, err := http.Get("https://api.coinconvert.net/convert/btc/strk?amount=1")
if err != nil {
fmt.Println("Error while querying the backend for the conversion rate")
return
}
btcToStrkJson, err := routeutils.ReadJsonResponse[BtcToStrkResponse](btcToStrkResponse)
if err != nil {
fmt.Println("Error while parsing the response as Json")
return
}
btcToStrk := btcToStrkJson.Strk

satsFeeRateResponse, err := http.Get("https://mempool.space/api/v1/fees/recommended")
if err != nil {
fmt.Println("Error while querying the backend for the fee rate")
return
}
satsFeeRateJson, err := routeutils.ReadJsonResponse[FeeRateResponse](satsFeeRateResponse)
if err != nil {
fmt.Println("Error while parsing the response as Json")
return
}
satsFeeRate := float64(satsFeeRateJson.FastestFee)
strkPerVbyteFloat := satsFeeRate * btcToStrk / btcToSats

// strkDecimals := big.NewFloat(1000000000000000000) // 10^18
strkPerVByteU256 := big.NewFloat(strkPerVbyteFloat)
// strkPerVByteU256.Mul(strkPerVByteU256, strkDecimals)
strkPerVByteU256.Int(&strkPerVbyte)
}

func InscriberLockingService() {
sleepTime := 30 // Wait 30 seconds before starting the service
time.Sleep(time.Duration(sleepTime) * time.Second)

updateInterval := 60 * 5 // Update every 5 minutes
timerState := 0
updateInterval := 60 * 5 // Update every 5 minutes
timerState := 0
backendUrl := "http://" + config.Conf.Api.Host + ":" + strconv.Itoa(config.Conf.Api.Port)
for {
sleepTime := 10 // Wait 10 seconds before querying the backend
time.Sleep(time.Duration(sleepTime) * time.Second)

timerState += sleepTime
if timerState >= updateInterval {
updateStrkPerVbyte()
timerState = 0
}
timerState += sleepTime
if timerState >= updateInterval {
updateStrkPerVbyte()
timerState = 0
}

// Query the backend for open inscription requests
fmt.Println("Querying the backend for open inscription requests with fee rate: ", strkPerVbyte.String())
fmt.Println("Querying the backend for open inscription requests with fee rate: ", strkPerVbyte.String())
getOpenRequestsUrl := backendUrl + "/inscriptions/get-open-requests"
// getOpenRequestsUrl := backendUrl + "/inscriptions/get-profitable-requests?feeRate=" + strkPerVbyte.String()
// strconv.FormatFloat(strkPerVbyte, 'f', -1, 64)
// strconv.FormatFloat(strkPerVbyte, 'f', -1, 64)
response, err := http.Get(getOpenRequestsUrl) // TODO: Use pagination
if err != nil {
fmt.Println("Error while querying the backend for open inscription requests")
Expand Down Expand Up @@ -120,17 +121,17 @@ func InscriberLockingService() {
continue
}

fmt.Println("Estimating fee to inscribe: ", responseJson.Data[0].InscriptionId)
res, err := scripts.EstimateFeeInvokeScript(responseJson.Data[0].InscriptionData)
if err != nil {
fmt.Println("Error while estimating the fee to inscribe")
continue
}
if res > responseJson.Data[0].FeeAmount {
// TODO: Go to next request
fmt.Printf("Insufficient fee to inscribe: %f < %f\n", res, responseJson.Data[0].FeeAmount)
continue
}
fmt.Println("Estimating fee to inscribe: ", responseJson.Data[0].InscriptionId)
res, err := scripts.EstimateFeeInvokeScript(responseJson.Data[0].InscriptionData)
if err != nil {
fmt.Println("Error while estimating the fee to inscribe")
continue
}
if res > responseJson.Data[0].FeeAmount {
// TODO: Go to next request
fmt.Printf("Insufficient fee to inscribe: %f < %f\n", res, responseJson.Data[0].FeeAmount)
continue
}

// Inscribe on Bitcoin
fmt.Println("Inscribing on Bitcoin: ", responseJson.Data[0].InscriptionId)
Expand All @@ -152,18 +153,18 @@ func InscriberLockingService() {
continue
}

// TODO: Estimate fee then check next if insufficent funds
fmt.Println("Estimating fee to inscribe (lock): ", responseJson.Data[0].InscriptionId)
res, err := scripts.EstimateFeeInvokeScript(responseJson.Data[0].InscriptionData)
if err != nil {
fmt.Println("Error while estimating the fee to inscribe")
continue
}
if res > responseJson.Data[0].FeeAmount {
// TODO: Go to next request
fmt.Printf("Insufficient fee to inscribe: %f < %f\n", res, responseJson.Data[0].FeeAmount)
continue
}
// TODO: Estimate fee then check next if insufficent funds
fmt.Println("Estimating fee to inscribe (lock): ", responseJson.Data[0].InscriptionId)
res, err := scripts.EstimateFeeInvokeScript(responseJson.Data[0].InscriptionData)
if err != nil {
fmt.Println("Error while estimating the fee to inscribe")
continue
}
if res > responseJson.Data[0].FeeAmount {
// TODO: Go to next request
fmt.Printf("Insufficient fee to inscribe: %f < %f\n", res, responseJson.Data[0].FeeAmount)
continue
}

// TODO: Determine which requests to use
// Lock the inscription request
Expand All @@ -181,7 +182,7 @@ func main() {
config.InitConfig()
scripts.InitScriptConfig()

updateStrkPerVbyte()
updateStrkPerVbyte()

// TODO: To go routine and run in parallel with InscriberSubmitService
InscriberLockingService()
Expand Down
144 changes: 72 additions & 72 deletions apps/backend/indexer/orderbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,42 +67,42 @@ func readFeltString(data string) (string, error) {
}

func readU256(low string, high string) (string, error) {
// TODO: Check if this is correct
return "0x" + high[2:] + low[2:], nil
// TODO: Check if this is correct
return "0x" + high[2:] + low[2:], nil
}

type TransactionCall struct {
contractAddress string
selector string
calldata []string
contractAddress string
selector string
calldata []string
}

type TransactionCalldata struct {
calls []TransactionCall
calls []TransactionCall
}

func parseCalldata(calldata []string) (TransactionCalldata, error) {
calls := []TransactionCall{}
callsCount, err := strconv.ParseInt(calldata[0], 0, 64)
if err != nil {
return TransactionCalldata{}, err
}
offset := 1
for i := 0; i < int(callsCount); i++ {
contractAddress := calldata[offset]
selector := calldata[offset+1]
callDataLength, err := strconv.ParseInt(calldata[offset+2], 0, 64)
if err != nil {
return TransactionCalldata{}, err
}
callData := []string{}
for j := 0; j < int(callDataLength); j++ {
callData = append(callData, calldata[offset+3+j])
}
calls = append(calls, TransactionCall{contractAddress, selector, callData})
offset += 3 + int(callDataLength)
}
return TransactionCalldata{calls}, nil
calls := []TransactionCall{}
callsCount, err := strconv.ParseInt(calldata[0], 0, 64)
if err != nil {
return TransactionCalldata{}, err
}
offset := 1
for i := 0; i < int(callsCount); i++ {
contractAddress := calldata[offset]
selector := calldata[offset+1]
callDataLength, err := strconv.ParseInt(calldata[offset+2], 0, 64)
if err != nil {
return TransactionCalldata{}, err
}
callData := []string{}
for j := 0; j < int(callDataLength); j++ {
callData = append(callData, calldata[offset+3+j])
}
calls = append(calls, TransactionCall{contractAddress, selector, callData})
offset += 3 + int(callDataLength)
}
return TransactionCalldata{calls}, nil
}

func processRequestCreatedEvent(event IndexerEventWithTransaction) {
Expand All @@ -115,31 +115,31 @@ func processRequestCreatedEvent(event IndexerEventWithTransaction) {
caller := event.Event.Keys[2][2:] // remove 0x prefix

// TODO: InvokeV0 & V3?
var callDataRaw []string
if len(event.Transaction.InvokeV1.Calldata) > 0 {
callDataRaw = event.Transaction.InvokeV1.Calldata
} else if len(event.Transaction.InvokeV3.Calldata) > 0 {
callDataRaw = event.Transaction.InvokeV3.Calldata
} else {
callDataRaw = event.Transaction.InvokeV0.Calldata
}
calldata, err := parseCalldata(callDataRaw)
if err != nil {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}

// TODO: If multi-call other than standard
// TODO: Hardcoded
var requestInscriptionCalldata []string
for _, call := range calldata.calls {
contractAddress := os.Getenv("BROLY_ORDERBOOK_CONTRACT_ADDRESS")
if call.contractAddress == contractAddress &&
call.selector == "0x02678cd90d58e18b88458577e7f7ddeaf93824a1e715f9e17a5b3842958541af" {
requestInscriptionCalldata = call.calldata
break
}
}
var callDataRaw []string
if len(event.Transaction.InvokeV1.Calldata) > 0 {
callDataRaw = event.Transaction.InvokeV1.Calldata
} else if len(event.Transaction.InvokeV3.Calldata) > 0 {
callDataRaw = event.Transaction.InvokeV3.Calldata
} else {
callDataRaw = event.Transaction.InvokeV0.Calldata
}
calldata, err := parseCalldata(callDataRaw)
if err != nil {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}

// TODO: If multi-call other than standard
// TODO: Hardcoded
var requestInscriptionCalldata []string
for _, call := range calldata.calls {
contractAddress := os.Getenv("BROLY_ORDERBOOK_CONTRACT_ADDRESS")
if call.contractAddress == contractAddress &&
call.selector == "0x02678cd90d58e18b88458577e7f7ddeaf93824a1e715f9e17a5b3842958541af" {
requestInscriptionCalldata = call.calldata
break
}
}

inscriptionData, _, err := readByteArray(requestInscriptionCalldata, 0)
if err != nil {
Expand Down Expand Up @@ -167,22 +167,22 @@ func processRequestCreatedEvent(event IndexerEventWithTransaction) {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}
feeAmountHex, err := readU256(event.Event.Data[offset+1], event.Event.Data[offset+2])
feeAmountHex, err := readU256(event.Event.Data[offset+1], event.Event.Data[offset+2])
if err != nil {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}
feeAmountU256, ok := new(big.Int).SetString(feeAmountHex[2:], 16)
if !ok {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}
strkDecimals := big.NewInt(1000000000000000000)
feeAmount := new(big.Float).SetInt(feeAmountU256)
feeAmount = new(big.Float).Quo(feeAmount, new(big.Float).SetInt(strkDecimals))
feeAmountF64, _ := feeAmount.Float64()
feeAmountU256, ok := new(big.Int).SetString(feeAmountHex[2:], 16)
if !ok {
PrintIndexerEventError("processRequestCreatedEvent", event, err)
return
}
strkDecimals := big.NewInt(1000000000000000000)
feeAmount := new(big.Float).SetInt(feeAmountU256)
feeAmount = new(big.Float).Quo(feeAmount, new(big.Float).SetInt(strkDecimals))
feeAmountF64, _ := feeAmount.Float64()

inscriptionByteSize := len(inscriptionData)
inscriptionByteSize := len(inscriptionData)

// Insert into Postgres
_, err = db.Db.Postgres.Exec(context.Background(), "INSERT INTO InscriptionRequests (inscription_id, requester, bitcoin_address, fee_token, fee_amount, bytes) VALUES ($1, $2, $3, $4, $5, $6)", inscriptionId, caller, bitcoinAddress, feeToken, feeAmountF64, inscriptionByteSize)
Expand Down Expand Up @@ -289,15 +289,15 @@ func processRequestCompletedEvent(event IndexerEventWithTransaction) {
return
}

txHashStr, _, err := readByteArray(event.Event.Data, 0)
if err != nil {
PrintIndexerEventError("processRequestCompletedEvent", event, err)
return
}
// Remove 0x and surrounding spaces
txHashTrimmed := strings.ReplaceAll(txHashStr[2:], " ", "")
// TODO: Multi inscription
txIndex := 0
txHashStr, _, err := readByteArray(event.Event.Data, 0)
if err != nil {
PrintIndexerEventError("processRequestCompletedEvent", event, err)
return
}
// Remove 0x and surrounding spaces
txHashTrimmed := strings.ReplaceAll(txHashStr[2:], " ", "")
// TODO: Multi inscription
txIndex := 0

// Insert into Postgres
_, err = db.Db.Postgres.Exec(context.Background(), "UPDATE InscriptionRequestsStatus SET status = 2 WHERE inscription_id = $1", inscriptionId)
Expand Down
Loading

0 comments on commit 8dd8b46

Please sign in to comment.