Skip to content

Commit

Permalink
feat: Update scripting for cryptocurrency management
Browse files Browse the repository at this point in the history
Here is the summary of the commit:

**Update Blockchain Components**

- Implement price feed script for Orbs network.
- Enhance bitcoin script to display transaction details, transfer cryptocurrency, and improve API request error handling.

Note: The most significant changes are highlighted, and the file summaries are not repeated in the commit message. The description and bullet points provide a high-level overview of the changes made in the commit.
  • Loading branch information
Laisky committed May 27, 2024
1 parent 0d65826 commit b8433f2
Show file tree
Hide file tree
Showing 2 changed files with 191 additions and 0 deletions.
76 changes: 76 additions & 0 deletions blockchain/arweave/ao/0rbit/0rbit-Price-Feed.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
local json = require("json")

_0RBIT = "BaMK1dfayo75s3q1ow6AO64UDpD9SEFbeE8xYrY2fyQ"
_0RBT_TOKEN = "BUhZLMwQ6yZHguLtJYA5lLUa9LQzLXMXRfaq9FVcPJc"

BASE_URL = "https://api.coingecko.com/api/v3/simple/price"
FEE_AMOUNT = "1000000000000" -- 1 $0RBT

TOKEN_PRICES = TOKEN_PRICES or {
BTC = {
coingecko_id = "bitcoin",
price = 0,
last_update_timestamp = 0
},
ETH = {
coingecko_id = "ethereum",
price = 0,
last_update_timestamp = 0
},
SOL = {
coingecko_id = "solana",
price = 0,
last_update_timestamp = 0
}
}
ID_TOKEN = ID_TOKEN or {
bitcoin = "BTC",
ethereum = "ETH",
solana = "SOL"
}
LOGS = LOGS or {}

function fetchPrice()
local url;
local token_ids;

for _, v in pairs(TOKEN_PRICES) do
token_ids = token_ids .. v.coingecko_id .. ","
end

url = BASE_URL .. "?ids=" .. token_ids .. "&vs_currencies=usd"

Send({
Target = _0RBT_TOKEN,
Action = "Transfer",
Recipient = _0RBIT,
Quantity = FEE_AMOUNT,
["X-Url"] = url,
["X-Action"] = "Get-Real-Data"
})
print(Colors.green .. "GET Request sent to the 0rbit process.")
end

function receiveData(msg)
local res = json.decode(msg.Data)
for k, v in pairs(res) do
TOKEN_PRICES[ID_TOKEN[k]].price = tonumber(v.usd)
TOKEN_PRICES[ID_TOKEN[k]].last_update_timestamp = msg.Timestamp
end
end

function getTokenPrice(msg)
local token = msg.Tags.Token
local price = TOKEN_PRICES[token].price
if price == 0 then
Handlers.utils.reply("Price not available!!!")(msg)
else
Handlers.utils.reply(tostring(price))(msg)
end
end

Handlers.add("GetTokenPrice", Handlers.utils.hasMatchingTag("Action", "Get-Token-Price"), getTokenPrice)

Handlers.add("FetchPrice", Handlers.utils.hasMatchingTag("Action", "Fetch-Price"), fetchPrice)

Handlers.add("ReceiveData", Handlers.utils.hasMatchingTag("Action", "Receive-Response"), receiveData)
115 changes: 115 additions & 0 deletions blockchain/bitcoin/scripts/show.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -15,6 +16,14 @@ func init() {

showBalanceCMD.Flags().StringVarP(&showBalanceCMDArgs.Address, "address", "a", "", "address to show balance")
showCMD.AddCommand(showBalanceCMD)

showTransactionCMD.Flags().StringVarP(&showTransactionCMDArgs.Txid, "txid", "t", "", "transaction id to show")
showCMD.AddCommand(showTransactionCMD)

transferCMD.Flags().StringVarP(&transferCMDArgs.From, "from", "f", "", "sender address")
transferCMD.Flags().StringVarP(&transferCMDArgs.To, "to", "t", "", "receiver address")
transferCMD.Flags().Float64VarP(&transferCMDArgs.Amount, "amount", "m", 0, "amount to transfer")
rootCMD.AddCommand(transferCMD)
}

var showCMD = &cobra.Command{
Expand Down Expand Up @@ -68,3 +77,109 @@ func showBalance(address string) error {

return nil
}

var showTransactionCMDArgs = struct {
Txid string
}{}

var showTransactionCMD = &cobra.Command{
Use: "tx",
Args: gcmd.NoExtraArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return showTransaction(showTransactionCMDArgs.Txid)
},
}

func showTransaction(txid string) error {
url := fmt.Sprintf("https://blockchain.info/rawtx/%s", txid)
resp, err := http.Get(url)
if err != nil {
return errors.Wrap(err, "error requesting transaction")
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return errors.Errorf("error requesting transaction, status code: %d", resp.StatusCode)
}

var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return errors.Wrap(err, "error decoding response")
}

fmt.Printf("Transaction: %s\n", txid)
fmt.Printf("Inputs:\n")
for _, input := range result["inputs"].([]interface{}) {
inputMap := input.(map[string]interface{})
prevOut := inputMap["prev_out"].(map[string]interface{})
fmt.Printf(" %s: %.8f BTC\n", prevOut["addr"], float64(prevOut["value"].(float64))/1e8)
}

fmt.Printf("Outputs:\n")
for _, output := range result["out"].([]interface{}) {
outputMap := output.(map[string]interface{})
fmt.Printf(" %s: %.8f BTC\n", outputMap["addr"], float64(outputMap["value"].(float64))/1e8)
}

return nil
}

var transferCMDArgs = struct {
From string
To string
Amount float64
}{}

var transferCMD = &cobra.Command{
Use: "transfer",
Args: gcmd.NoExtraArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return transfer(transferCMDArgs.From, transferCMDArgs.To, transferCMDArgs.Amount)
},
}

func transfer(from, to string, amount float64) error {
if from == "" || to == "" {
return errors.New("both from and to addresses are required")
}
if amount <= 0 {
return errors.New("amount must be greater than zero")
}

payload := map[string]interface{}{
"from": from,
"to": to,
"amount": amount,
}

payloadBytes, err := json.Marshal(payload)
if err != nil {
return errors.Wrap(err, "error marshaling payload")
}

url := "https://api.cryptoservice.com/transfer" // Hypothetical URL
resp, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return errors.Wrap(err, "error creating transaction")
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return errors.Errorf("error creating transaction, status code: %d", resp.StatusCode)
}

var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return errors.Wrap(err, "error decoding response")
}

txid, ok := result["txid"].(string)
if !ok {
return errors.New("invalid response from server, missing txid")
}

fmt.Printf("Transaction successful!\nTXID: %s\n", txid)
return nil
}

0 comments on commit b8433f2

Please sign in to comment.