-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
391 lines (353 loc) · 11.1 KB
/
Copy pathclient.go
File metadata and controls
391 lines (353 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package relayer
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/GoPolymarket/go-builder-relayer-client/internal/builder"
"github.com/GoPolymarket/go-builder-relayer-client/internal/encoder"
"github.com/GoPolymarket/go-builder-relayer-client/pkg/signer"
"github.com/GoPolymarket/go-builder-relayer-client/pkg/types"
)
// RelayClient provides access to Polymarket relayer endpoints.
type RelayClient struct {
relayerURL string
chainID int64
relayTxType types.RelayerTxType
contractConfig types.ContractConfig
httpClient *HTTPClient
signer signer.Signer
builderConfig *BuilderConfig
sleepFn func(context.Context, time.Duration) error
}
func NewRelayClient(relayerURL string, chainID int64, signer signer.Signer, builderConfig *BuilderConfig, relayTxType types.RelayerTxType) (*RelayClient, error) {
cleanURL := strings.TrimRight(relayerURL, "/")
if relayTxType == "" {
relayTxType = types.RelayerTxSafe
}
config, err := GetContractConfig(chainID)
if err != nil {
return nil, err
}
return &RelayClient{
relayerURL: cleanURL,
chainID: chainID,
relayTxType: relayTxType,
contractConfig: config,
httpClient: NewHTTPClient(nil),
signer: signer,
builderConfig: builderConfig,
sleepFn: sleepWithContext,
}, nil
}
// SetHTTPClient allows overriding the underlying HTTP client.
func (c *RelayClient) SetHTTPClient(client *HTTPClient) {
if client != nil {
c.httpClient = client
}
}
func (c *RelayClient) GetNonce(ctx context.Context, signerAddress string, signerType string) (types.NoncePayload, error) {
var resp types.NoncePayload
err := c.send(ctx, GetNonceEndpoint, "GET", &RequestOptions{Params: map[string]string{"address": signerAddress, "type": signerType}}, &resp)
return resp, err
}
func (c *RelayClient) GetRelayPayload(ctx context.Context, signerAddress string, signerType string) (types.RelayPayload, error) {
var resp types.RelayPayload
err := c.send(ctx, GetRelayPayloadEndpoint, "GET", &RequestOptions{Params: map[string]string{"address": signerAddress, "type": signerType}}, &resp)
return resp, err
}
func (c *RelayClient) GetTransaction(ctx context.Context, transactionID string) ([]types.RelayerTransaction, error) {
var resp []types.RelayerTransaction
err := c.send(ctx, GetTransactionEndpoint, "GET", &RequestOptions{Params: map[string]string{"id": transactionID}}, &resp)
return resp, err
}
func (c *RelayClient) GetTransactions(ctx context.Context) ([]types.RelayerTransaction, error) {
var resp []types.RelayerTransaction
err := c.sendAuthedRequest(ctx, "GET", GetTransactionsEndpoint, "", &resp)
return resp, err
}
func (c *RelayClient) GetDeployed(ctx context.Context, safeAddress string) (bool, error) {
var resp types.GetDeployedResponse
err := c.send(ctx, GetDeployedEndpoint, "GET", &RequestOptions{Params: map[string]string{"address": safeAddress}}, &resp)
return resp.Deployed, err
}
// Execute executes a batch of transactions.
func (c *RelayClient) Execute(ctx context.Context, txns []types.Transaction, metadata string) (*ClientRelayerTransactionResponse, error) {
if c.signer == nil {
return nil, types.ErrSignerUnavailable
}
if len(txns) == 0 {
return nil, types.ErrNoTransactions
}
switch c.relayTxType {
case types.RelayerTxSafe:
safeTxns := make([]types.SafeTransaction, 0, len(txns))
for _, tx := range txns {
value := tx.Value
if value == "" {
value = "0"
}
safeTxns = append(safeTxns, types.SafeTransaction{To: tx.To, Operation: types.OperationCall, Data: tx.Data, Value: value})
}
return c.executeSafeTransactions(ctx, safeTxns, metadata)
case types.RelayerTxProxy:
proxyTxns := make([]types.ProxyTransaction, 0, len(txns))
for _, tx := range txns {
value := tx.Value
if value == "" {
value = "0"
}
proxyTxns = append(proxyTxns, types.ProxyTransaction{To: tx.To, TypeCode: types.CallTypeCall, Data: tx.Data, Value: value})
}
return c.executeProxyTransactions(ctx, proxyTxns, metadata)
default:
return nil, fmt.Errorf("%w: %s", types.ErrUnsupportedTxType, c.relayTxType)
}
}
func (c *RelayClient) executeProxyTransactions(ctx context.Context, txns []types.ProxyTransaction, metadata string) (*ClientRelayerTransactionResponse, error) {
if !IsProxyContractConfigValid(c.contractConfig.ProxyContracts) {
return nil, types.ErrConfigUnsupported
}
from := c.signer.Address().Hex()
relayPayload, err := c.GetRelayPayload(ctx, from, string(types.TransactionTypeProxy))
if err != nil {
return nil, err
}
data, err := encoder.EncodeProxyTransactionData(txns)
if err != nil {
return nil, err
}
args := types.ProxyTransactionArgs{
From: from,
GasPrice: "0",
Data: data,
Relay: relayPayload.Address,
Nonce: relayPayload.Nonce,
}
request, err := builder.BuildProxyTransactionRequest(ctx, c.signer, args, c.contractConfig.ProxyContracts, metadata)
if err != nil {
return nil, err
}
payload, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
var resp types.RelayerTransactionResponse
if err := c.sendAuthedRequest(ctx, "POST", SubmitTransactionEndpoint, string(payload), &resp); err != nil {
return nil, err
}
return &ClientRelayerTransactionResponse{
TransactionID: resp.TransactionID,
State: resp.State,
TransactionHash: resp.TransactionHash,
client: c,
}, nil
}
func (c *RelayClient) executeSafeTransactions(ctx context.Context, txns []types.SafeTransaction, metadata string) (*ClientRelayerTransactionResponse, error) {
if !IsSafeContractConfigValid(c.contractConfig.SafeContracts) {
return nil, types.ErrConfigUnsupported
}
safe, err := c.getExpectedSafe()
if err != nil {
return nil, err
}
deployed, err := c.GetDeployed(ctx, safe)
if err != nil {
return nil, err
}
if !deployed {
return nil, types.ErrSafeNotDeployed
}
from := c.signer.Address().Hex()
noncePayload, err := c.GetNonce(ctx, from, string(types.TransactionTypeSafe))
if err != nil {
return nil, err
}
if noncePayload.Nonce == "" {
return nil, types.ErrInvalidNoncePayload
}
args := types.SafeTransactionArgs{
From: from,
Nonce: noncePayload.Nonce,
ChainID: c.chainID,
Transactions: txns,
}
request, err := builder.BuildSafeTransactionRequest(c.signer, args, c.contractConfig.SafeContracts, metadata)
if err != nil {
return nil, err
}
payload, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
var resp types.RelayerTransactionResponse
if err := c.sendAuthedRequest(ctx, "POST", SubmitTransactionEndpoint, string(payload), &resp); err != nil {
return nil, err
}
return &ClientRelayerTransactionResponse{
TransactionID: resp.TransactionID,
State: resp.State,
TransactionHash: resp.TransactionHash,
client: c,
}, nil
}
// Deploy deploys a Safe contract.
func (c *RelayClient) Deploy(ctx context.Context) (*ClientRelayerTransactionResponse, error) {
if c.signer == nil {
return nil, types.ErrSignerUnavailable
}
safe, err := c.getExpectedSafe()
if err != nil {
return nil, err
}
deployed, err := c.GetDeployed(ctx, safe)
if err != nil {
return nil, err
}
if deployed {
return nil, types.ErrSafeDeployed
}
return c.deploySafe(ctx)
}
func (c *RelayClient) deploySafe(ctx context.Context) (*ClientRelayerTransactionResponse, error) {
if !IsSafeContractConfigValid(c.contractConfig.SafeContracts) {
return nil, types.ErrConfigUnsupported
}
from := c.signer.Address().Hex()
args := types.SafeCreateTransactionArgs{
From: from,
ChainID: c.chainID,
PaymentToken: types.ZeroAddress,
Payment: "0",
PaymentReceiver: types.ZeroAddress,
}
request, err := builder.BuildSafeCreateTransactionRequest(c.signer, c.contractConfig.SafeContracts, args)
if err != nil {
return nil, err
}
payload, err := json.Marshal(request)
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
var resp types.RelayerTransactionResponse
if err := c.sendAuthedRequest(ctx, "POST", SubmitTransactionEndpoint, string(payload), &resp); err != nil {
return nil, err
}
return &ClientRelayerTransactionResponse{
TransactionID: resp.TransactionID,
State: resp.State,
TransactionHash: resp.TransactionHash,
client: c,
}, nil
}
func sleepWithContext(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func (c *RelayClient) PollUntilState(ctx context.Context, transactionID string, states []types.RelayerTransactionState, failState types.RelayerTransactionState, maxPolls int, pollFrequency time.Duration) (*types.RelayerTransaction, error) {
stateSet := make(map[types.RelayerTransactionState]struct{}, len(states))
for _, s := range states {
stateSet[s] = struct{}{}
}
if maxPolls <= 0 {
maxPolls = 10
}
if pollFrequency < time.Second {
pollFrequency = 2 * time.Second
}
for i := 0; i < maxPolls; i++ {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
txns, err := c.GetTransaction(ctx, transactionID)
if err != nil {
return nil, err
}
if len(txns) > 0 {
txn := txns[0]
if _, ok := stateSet[txn.State]; ok {
return &txn, nil
}
if failState != "" && txn.State == failState {
return nil, fmt.Errorf("%w: %s", types.ErrTransactionFailed, txn.TransactionHash)
}
}
if i == maxPolls-1 {
continue
}
sleepFn := c.sleepFn
if sleepFn == nil {
sleepFn = sleepWithContext
}
if err := sleepFn(ctx, pollFrequency); err != nil {
return nil, err
}
}
return nil, types.ErrTransactionTimeout
}
func (c *RelayClient) send(ctx context.Context, path string, method string, options *RequestOptions, out interface{}) error {
if options == nil {
options = &RequestOptions{}
}
signedPath := path
if len(options.Params) > 0 {
q := url.Values{}
for k, v := range options.Params {
q.Set(k, v)
}
if encoded := q.Encode(); encoded != "" {
signedPath = path + "?" + encoded
}
}
headers := options.Headers
if headers == nil {
headers = http.Header{}
}
if c.builderConfig != nil && c.builderConfig.IsValid() {
signBody := ""
if len(options.Body) > 0 {
signBody = string(options.Body)
}
headersToAdd, err := c.builderConfig.Headers(ctx, method, signedPath, &signBody, 0)
if err != nil {
return err
}
for k, vals := range headersToAdd {
for _, v := range vals {
headers.Add(k, v)
}
}
} else {
return types.ErrMissingBuilderConfig
}
options.Headers = headers
url := c.relayerURL + path
return c.httpClient.Do(ctx, method, url, options, out)
}
func (c *RelayClient) sendAuthedRequest(ctx context.Context, method, path string, body string, out interface{}) error {
opts := &RequestOptions{}
if body != "" {
opts.Body = []byte(body)
}
return c.send(ctx, path, method, opts, out)
}
func (c *RelayClient) getExpectedSafe() (string, error) {
if c.signer == nil {
return "", types.ErrSignerUnavailable
}
return builder.DeriveSafeAddress(c.signer.Address().Hex(), c.contractConfig.SafeContracts.SafeFactory)
}