Skip to content

Commit

Permalink
Merge branch 'master' into widget/chain-update
Browse files Browse the repository at this point in the history
  • Loading branch information
abtestingalpha committed Oct 24, 2024
2 parents a657d6b + 6595fb4 commit 0aaeda8
Show file tree
Hide file tree
Showing 31 changed files with 1,123 additions and 79 deletions.
20 changes: 13 additions & 7 deletions core/ginhelper/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,24 @@ func NewWithExperimentalLogger(ctx context.Context, logger logger.ExperimentalLo
return server
}

// TODO: this is an anti-pattern and needs to be replaced by an option asap.
var CorsEnabled = true

func newBase() *gin.Engine {
server := gin.New()
// required for opentracing.
server.ContextWithFallback = true
server.Use(helmet.Default())

server.Use(gin.Recovery())
server.Use(cors.New(cors.Config{
AllowAllOrigins: true,
AllowHeaders: []string{"*"},
AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodOptions},
MaxAge: 12 * time.Hour,
}))
if CorsEnabled {
server.Use(helmet.Default())
server.Use(cors.New(cors.Config{
AllowAllOrigins: true,
AllowHeaders: []string{"*"},
AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodOptions},
MaxAge: 12 * time.Hour,
}))
}

// configure the request id
server.Use(requestid.New(
Expand Down
9 changes: 9 additions & 0 deletions core/metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ The metrics endpoint is exposed on `/metrics` on port `8080` by default and is c

**Note: this server failing to bind to `METRICS_PORT` will not cause the application to fail to start. The error will be logged.**

Most metrics come with a `# HELP` explanation that explains them, for example:

```promql
# HELP process_uptime_seconds The uptime of the process in seconds
# TYPE process_uptime_seconds gauge
process_uptime_seconds{otel_scope_name="standard_metrics",otel_scope_version=""} 24.241680459
```

## Logger

Currently, the entire sanguine codebase uses [ipfs go-log]("https://github.com/ipfs/go-log"). As pointed out in [#1521](https://github.com/synapsecns/sanguine/issues/1521), this is not a good long term solution since the logs are not currently appended to opentelemetry, and so new traces require telemtry.
Expand All @@ -80,3 +88,4 @@ Note: because both [ipfs go-log]("https://github.com/ipfs/go-log") and [otelzap
### Using the logger

Since the logger is dependent on the `context` to derive the current span, you need to always use `logger.Ctx(ctx)` or `logger.InfoCtx`. One thing under consideration is removing the non-ctx methods

8 changes: 5 additions & 3 deletions core/metrics/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package metrics
import (
"context"
"fmt"
"net/http"

"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/synapsecns/sanguine/core"
Expand All @@ -30,6 +28,7 @@ import (
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
"gorm.io/gorm"
"net/http"
)

const pyroscopeEndpoint = internal.PyroscopeEndpoint
Expand All @@ -44,7 +43,8 @@ type baseHandler struct {
tracer trace.Tracer
name string
propagator propagation.TextMapPropagator
meter MeterProvider
// Deprecated: will be removed in a future version
meter MeterProvider
// handler is an integrated handler for everything exported over http. This includes prometheus
// or http-based sampling methods for other providers.
handler http.Handler
Expand Down Expand Up @@ -78,6 +78,8 @@ func (b *baseHandler) Start(ctx context.Context) error {
otel.SetMeterProvider(b.meter)
b.handler = promhttp.Handler()

newStandardMetrics(ctx, b)

go func() {
<-ctx.Done()
// shutting down this way will not flush.
Expand Down
41 changes: 41 additions & 0 deletions core/metrics/standard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package metrics

import (
"context"
"go.opentelemetry.io/otel/metric"
"time"
)

// standardMetrics records metrics across any service using the metrics handler.
type standardMetrics struct {
metrics Handler
meter metric.Meter
uptimeGauge metric.Float64ObservableGauge
startTime time.Time
}

const processUptimeSecondsMetric = "process_uptime_seconds"

func newStandardMetrics(ctx context.Context, handler Handler) {
str := standardMetrics{
metrics: handler,
meter: handler.Meter("standard_metrics"),
startTime: time.Now(),
}

var err error
if str.uptimeGauge, err = str.meter.Float64ObservableGauge(processUptimeSecondsMetric, metric.WithDescription("The uptime of the process in seconds"), metric.WithUnit("seconds")); err != nil {
handler.ExperimentalLogger().Errorf(ctx, "failed to create %s gauge: %v", processUptimeSecondsMetric, err)
}

// Register callback
if _, err = str.meter.RegisterCallback(str.uptimeCallback, str.uptimeGauge); err != nil {
handler.ExperimentalLogger().Warnf(ctx, "failed to register callback: %v", err)
}
}

func (str *standardMetrics) uptimeCallback(_ context.Context, observer metric.Observer) error {
uptimeDuration := time.Since(str.startTime).Seconds()
observer.ObserveFloat64(str.uptimeGauge, uptimeDuration)
return nil
}
8 changes: 8 additions & 0 deletions docs/bridge/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [0.4.5](https://github.com/synapsecns/sanguine/compare/@synapsecns/[email protected]...@synapsecns/[email protected]) (2024-10-21)

**Note:** Version bump only for package @synapsecns/bridge-docs





## [0.4.4](https://github.com/synapsecns/sanguine/compare/@synapsecns/[email protected]...@synapsecns/[email protected]) (2024-10-15)

**Note:** Version bump only for package @synapsecns/bridge-docs
Expand Down
4 changes: 2 additions & 2 deletions docs/bridge/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@synapsecns/bridge-docs",
"version": "0.4.4",
"version": "0.4.5",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
Expand Down Expand Up @@ -34,7 +34,7 @@
"@docusaurus/utils-validation": "3.5.2",
"@easyops-cn/docusaurus-search-local": "^0.44.5",
"@mdx-js/react": "^3.0.0",
"@synapsecns/synapse-constants": "^1.7.0",
"@synapsecns/synapse-constants": "^1.8.0",
"clsx": "^2.0.0",
"docusaurus-plugin-openapi-docs": "^4.0.1",
"docusaurus-theme-openapi-docs": "^4.0.1",
Expand Down
5 changes: 5 additions & 0 deletions packages/contracts-rfq/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ SCROLL_RPC=https://rpc.scroll.io
SCROLL_VERIFIER=etherscan
SCROLL_VERIFIER_URL=https://api.scrollscan.com/api
SCROLL_VERIFIER_KEY=YourScrollScanKey
# World Chain
WORLDCHAIN_RPC=https://worldchain-mainnet.g.alchemy.com/public
WORLDCHAIN_VERIFIER=etherscan
WORLDCHAIN_VERIFIER_URL=https://api.worldscan.org/api
WORLDCHAIN_VERIFIER_KEY=YourWorldScanKey

# TESTNET CHAINS
# Arbitrum Sepolia
Expand Down
16 changes: 16 additions & 0 deletions packages/contracts-rfq/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [0.9.3](https://github.com/synapsecns/sanguine/compare/@synapsecns/[email protected]...@synapsecns/[email protected]) (2024-10-24)

**Note:** Version bump only for package @synapsecns/contracts-rfq





## [0.9.2](https://github.com/synapsecns/sanguine/compare/@synapsecns/[email protected]...@synapsecns/[email protected]) (2024-10-22)

**Note:** Version bump only for package @synapsecns/contracts-rfq





## [0.9.1](https://github.com/synapsecns/sanguine/compare/@synapsecns/[email protected]...@synapsecns/[email protected]) (2024-10-18)

**Note:** Version bump only for package @synapsecns/contracts-rfq
Expand Down
49 changes: 27 additions & 22 deletions packages/contracts-rfq/contracts/FastBridgeV2.sol
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,16 @@ contract FastBridgeV2 is Admin, IFastBridgeV2, IFastBridgeV2Errors {
/// @inheritdoc IFastBridge
function dispute(bytes32 transactionId) external onlyRole(GUARD_ROLE) {
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

// Aggregate the read operations from the same storage slot
address disputedRelayer = $.proofRelayer;
BridgeStatus status = $.status;
uint40 proofBlockTimestamp = $.proofBlockTimestamp;

// Can only dispute a RELAYER_PROVED transaction within the dispute period
if (status != BridgeStatus.RELAYER_PROVED) revert StatusIncorrect();
if (_timeSince(proofBlockTimestamp) > DISPUTE_PERIOD) {
revert DisputePeriodPassed();
}

// Update status to REQUESTED and delete the disputed proof details
// Note: these are storage writes
$.status = BridgeStatus.REQUESTED;
$.proofRelayer = address(0);
Expand All @@ -107,33 +107,34 @@ contract FastBridgeV2 is Admin, IFastBridgeV2, IFastBridgeV2Errors {
request.validateV2();
bytes32 transactionId = keccak256(request);
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

// Can only refund a REQUESTED transaction after its deadline expires
if ($.status != BridgeStatus.REQUESTED) revert StatusIncorrect();

uint256 deadline = request.deadline();
// Permissionless refund is allowed after REFUND_DELAY
// Permissionless refund is only allowed after REFUND_DELAY on top of the deadline
if (!hasRole(REFUNDER_ROLE, msg.sender)) deadline += REFUND_DELAY;
if (block.timestamp <= deadline) revert DeadlineNotExceeded();
// Update status to REFUNDED and return the full amount (collateral + protocol fees) to the original sender.
// The protocol fees are only updated when the transaction is claimed, so we don't need to update them here.
// Note: this is a storage write
$.status = BridgeStatus.REFUNDED;

// transfer origin collateral back to original sender
address to = request.originSender();
address token = request.originToken();
uint256 amount = request.originAmount() + request.originFeeAmount();
// Emit the event before any external calls
emit BridgeDepositRefunded(transactionId, to, token, amount);
// Complete the user refund as the last transaction action
if (token == UniversalTokenLib.ETH_ADDRESS) {
Address.sendValue(payable(to), amount);
} else {
IERC20(token).safeTransfer(to, amount);
}

emit BridgeDepositRefunded(transactionId, to, token, amount);
}

/// @inheritdoc IFastBridge
function canClaim(bytes32 transactionId, address relayer) external view returns (bool) {
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

// The correct relayer can only claim a RELAYER_PROVED transaction after the dispute period
if ($.status != BridgeStatus.RELAYER_PROVED) revert StatusIncorrect();
if ($.proofRelayer != relayer) revert SenderIncorrect();
return _timeSince($.proofBlockTimestamp) > DISPUTE_PERIOD;
Expand Down Expand Up @@ -288,8 +289,9 @@ contract FastBridgeV2 is Admin, IFastBridgeV2, IFastBridgeV2Errors {
function prove(bytes32 transactionId, bytes32 destTxHash, address relayer) public onlyRole(RELAYER_ROLE) {
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

// update bridge tx status given proof provided
// Can only prove a REQUESTED transaction
if ($.status != BridgeStatus.REQUESTED) revert StatusIncorrect();
// Update status to RELAYER_PROVED and store the proof details
// Note: these are storage writes
$.status = BridgeStatus.RELAYER_PROVED;
$.proofBlockTimestamp = uint40(block.timestamp);
Expand All @@ -304,47 +306,50 @@ contract FastBridgeV2 is Admin, IFastBridgeV2, IFastBridgeV2Errors {
request.validateV2();
bytes32 transactionId = keccak256(request);
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

// Aggregate the read operations from the same storage slot
address proofRelayer = $.proofRelayer;
BridgeStatus status = $.status;
uint40 proofBlockTimestamp = $.proofBlockTimestamp;

// update bridge tx status if able to claim origin collateral
// Can only claim a RELAYER_PROVED transaction after the dispute period
if (status != BridgeStatus.RELAYER_PROVED) revert StatusIncorrect();
if (_timeSince(proofBlockTimestamp) <= DISPUTE_PERIOD) {
revert DisputePeriodNotPassed();
}

// if "to" is zero addr, permissionlessly send funds to proven relayer
if (to == address(0)) {
// Anyone could claim the funds to the proven relayer on their behalf
to = proofRelayer;
} else if (proofRelayer != msg.sender) {
// Only the proven relayer could specify an address to claim the funds to
revert SenderIncorrect();
}

if (_timeSince(proofBlockTimestamp) <= DISPUTE_PERIOD) {
revert DisputePeriodNotPassed();
}
// Update status to RELAYER_CLAIMED and transfer the origin collateral to the specified claim address
// Note: this is a storage write
$.status = BridgeStatus.RELAYER_CLAIMED;

// update protocol fees if origin fee amount exists
address token = request.originToken();
uint256 amount = request.originAmount();
// Update protocol fees if origin fee amount exists
uint256 originFeeAmount = request.originFeeAmount();
if (originFeeAmount > 0) protocolFees[token] += originFeeAmount;

// transfer origin collateral to specified address (protocol fee was pre-deducted at deposit)
// Emit the event before any external calls
emit BridgeDepositClaimed(transactionId, proofRelayer, to, token, amount);
// Complete the relayer claim as the last transaction action
if (token == UniversalTokenLib.ETH_ADDRESS) {
Address.sendValue(payable(to), amount);
} else {
IERC20(token).safeTransfer(to, amount);
}

emit BridgeDepositClaimed(transactionId, proofRelayer, to, token, amount);
}

/// @inheritdoc IFastBridgeV2
function bridgeStatuses(bytes32 transactionId) public view returns (BridgeStatus status) {
return bridgeTxDetails[transactionId].status;
}

/// @inheritdoc IFastBridgeV2
function bridgeProofs(bytes32 transactionId) public view returns (uint96 timestamp, address relayer) {
BridgeTxDetails storage $ = bridgeTxDetails[transactionId];

Expand Down
1 change: 1 addition & 0 deletions packages/contracts-rfq/deployments/worldchain/.chainId
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
480
Loading

0 comments on commit 0aaeda8

Please sign in to comment.