-
Notifications
You must be signed in to change notification settings - Fork 1
Add thorchain support #382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
neavra
wants to merge
8
commits into
main
Choose a base branch
from
362-add-thorchain-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9c92d39
add thorchain to validateAndSign
neavra 9146734
thorchain tx_indexer
neavra 547de5a
add rpc client
neavra 9f5822f
add thorchain rpc to list
neavra 272d7a6
Merge branch 'main' into 362-add-thorchain-support
neavra b811fd7
fixes + add logs
neavra 06617b2
Merge branch 'main' into 362-add-thorchain-support
neavra d7c4674
Merge branch 'main' into 362-add-thorchain-support
neavra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package chain | ||
|
|
||
| import ( | ||
| "crypto/sha256" | ||
| "encoding/hex" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/vultisig/mobile-tss-lib/tss" | ||
| "github.com/vultisig/recipes/sdk/thorchain" | ||
| ) | ||
|
|
||
| type THORChainIndexer struct { | ||
| sdk *thorchain.SDK | ||
| } | ||
|
|
||
| func NewTHORChainIndexer(sdk *thorchain.SDK) *THORChainIndexer { | ||
| return &THORChainIndexer{ | ||
| sdk: sdk, | ||
| } | ||
| } | ||
|
|
||
| func (t *THORChainIndexer) ComputeTxHash(proposedTx []byte, sigs map[string]tss.KeysignResponse) (string, error) { | ||
| signed, err := t.sdk.Sign(proposedTx, sigs) | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to sign: %w", err) | ||
| } | ||
|
|
||
| // For Cosmos-based chains like THORChain, the transaction hash is computed | ||
| // according to CometBFT/Tendermint standards: SHA256 hash of the signed transaction bytes, | ||
| // but this needs to match exactly what the blockchain network expects. | ||
| // The SDK Sign() method returns the final serialized transaction that will be broadcast. | ||
| hash := sha256.Sum256(signed) | ||
| return strings.ToUpper(hex.EncodeToString(hash[:])), nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| package rpc | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "math" | ||
| "math/rand" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/sirupsen/logrus" | ||
| "golang.org/x/time/rate" | ||
| ) | ||
|
|
||
| type THORChain struct { | ||
| client *http.Client | ||
| baseURL string | ||
| limiter *rate.Limiter | ||
| } | ||
|
|
||
| func NewTHORChain(rpcURL string) (*THORChain, error) { | ||
| client := &http.Client{ | ||
| Timeout: 30 * time.Second, | ||
| } | ||
|
|
||
| // Clean up URL | ||
| baseURL := strings.TrimSuffix(rpcURL, "/") | ||
|
|
||
| // Rate limiter: 1 req/s with burst of 3 (more lenient) | ||
| limiter := rate.NewLimiter(rate.Limit(1), 3) | ||
|
|
||
| return &THORChain{ | ||
| client: client, | ||
| baseURL: baseURL, | ||
| limiter: limiter, | ||
| }, nil | ||
| } | ||
|
|
||
| // THORChain Tendermint RPC transaction response structure | ||
| type thorchainTxResponse struct { | ||
| Result struct { | ||
| Hash string `json:"hash"` | ||
| Height string `json:"height"` | ||
| TxResult struct { | ||
| Code int `json:"code"` | ||
| } `json:"tx_result"` | ||
| } `json:"result"` | ||
| Error *struct { | ||
| Code int `json:"code"` | ||
| Message string `json:"message"` | ||
| } `json:"error"` | ||
| } | ||
|
|
||
| func (t *THORChain) GetTxStatus(ctx context.Context, txHash string) (TxOnChainStatus, error) { | ||
| // Use Tendermint RPC format: prefix with 0x and ensure uppercase | ||
| formattedHash := strings.ToUpper(strings.TrimPrefix(txHash, "0x")) | ||
| url := fmt.Sprintf("%s/tx?hash=0x%s", t.baseURL, formattedHash) | ||
|
|
||
| return t.makeRequestWithRetry(ctx, url) | ||
| } | ||
|
|
||
| func (t *THORChain) makeRequestWithRetry(ctx context.Context, url string) (TxOnChainStatus, error) { | ||
| maxRetries := 3 | ||
| baseDelay := 2 * time.Second | ||
|
|
||
| for attempt := 0; attempt <= maxRetries; attempt++ { | ||
| // Rate limiting | ||
| if err := t.limiter.Wait(ctx); err != nil { | ||
| return TxOnChainFail, fmt.Errorf("rate limiter context error: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "GET", url, nil) | ||
| if err != nil { | ||
| return TxOnChainFail, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| resp, err := t.client.Do(req) | ||
| if err != nil { | ||
| if attempt == maxRetries { | ||
| return TxOnChainFail, fmt.Errorf("failed to make request after %d attempts: %w", maxRetries+1, err) | ||
| } | ||
| delay := t.calculateBackoff(attempt, baseDelay) | ||
| logrus.WithFields(logrus.Fields{ | ||
| "attempt": attempt + 1, | ||
| "max_attempts": maxRetries + 1, | ||
| "delay_seconds": delay.Seconds(), | ||
| "error": err.Error(), | ||
| }).Info("THORChain RPC request failed, retrying") | ||
| t.sleep(ctx, delay) | ||
| continue | ||
| } | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| resp.Body.Close() | ||
| if err != nil { | ||
| return TxOnChainFail, fmt.Errorf("failed to read response: %w", err) | ||
| } | ||
|
|
||
| // Handle rate limiting (429) - don't fail, just return pending | ||
| if resp.StatusCode == http.StatusTooManyRequests { | ||
| if attempt == maxRetries { | ||
| logrus.WithFields(logrus.Fields{ | ||
| "attempt": attempt + 1, | ||
| "max_attempts": maxRetries + 1, | ||
| }).Warn("THORChain RPC rate limited after max retries, returning pending") | ||
| return TxOnChainPending, nil | ||
| } | ||
|
|
||
| delay := t.getRetryAfterDelay(resp, t.calculateBackoff(attempt, baseDelay)) | ||
| t.sleep(ctx, delay) | ||
| continue | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return TxOnChainPending, fmt.Errorf("HTTP error: %d, body: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| var txResp thorchainTxResponse | ||
| if err := json.Unmarshal(body, &txResp); err != nil { | ||
| return TxOnChainPending, fmt.Errorf("failed to unmarshal response: %w", err) | ||
| } | ||
|
|
||
| // Check for RPC error response | ||
| if txResp.Error != nil { | ||
| // Transaction not found - still pending | ||
| return TxOnChainPending, nil | ||
| } | ||
|
|
||
| // Check if transaction exists and has a height (confirmed) | ||
| if txResp.Result.Hash != "" && txResp.Result.Height != "" { | ||
| // Tendermint RPC: code 0 = success, non-zero = failure | ||
| if txResp.Result.TxResult.Code == 0 { | ||
| return TxOnChainSuccess, nil | ||
| } | ||
| return TxOnChainFail, nil | ||
| } | ||
|
|
||
| return TxOnChainPending, nil | ||
| } | ||
|
|
||
| // Don't crash on max retries - just return pending | ||
| return TxOnChainPending, nil | ||
| } | ||
|
|
||
| func (t *THORChain) calculateBackoff(attempt int, baseDelay time.Duration) time.Duration { | ||
| // Exponential backoff: 1s → 2s → 4s → 8s, max 30s | ||
| delay := baseDelay * time.Duration(math.Pow(2, float64(attempt))) | ||
neavra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| maxDelay := 30 * time.Second | ||
| if delay > maxDelay { | ||
| delay = maxDelay | ||
| } | ||
|
|
||
| // Add jitter (±25%) | ||
| jitter := time.Duration(rand.Float64()*0.5-0.25) * delay | ||
| return delay + jitter | ||
| } | ||
|
|
||
| func (t *THORChain) getRetryAfterDelay(resp *http.Response, fallback time.Duration) time.Duration { | ||
| retryAfter := resp.Header.Get("Retry-After") | ||
| if retryAfter == "" { | ||
| return fallback | ||
| } | ||
|
|
||
| // Try parsing as seconds | ||
| if seconds, err := strconv.Atoi(retryAfter); err == nil { | ||
| delay := time.Duration(seconds) * time.Second | ||
| maxDelay := 30 * time.Second | ||
| if delay > maxDelay { | ||
| delay = maxDelay | ||
| } | ||
| return delay | ||
| } | ||
|
|
||
| return fallback | ||
| } | ||
|
|
||
| func (t *THORChain) sleep(ctx context.Context, duration time.Duration) { | ||
| timer := time.NewTimer(duration) | ||
| defer timer.Stop() | ||
|
|
||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| case <-timer.C: | ||
| return | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.