/
marketplace_encoder.go
562 lines (508 loc) · 17.5 KB
/
marketplace_encoder.go
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package web3sdks
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/web3sdks/go-sdk/v2/abi"
)
// The marketplace encoder class is used to get the unsigned transaction data for marketplace contract
// contract calls that can be signed at a later time after generation.
//
// It can be accessed from the SDK through the `Encoder` namespace of the marketplace contract:
//
// You can access the Marketplace interface from the SDK as follows:
//
// import (
// "github.com/web3sdks/go-sdk/v2/web3sdks"
// )
//
// privateKey = "..."
//
// sdk, err := web3sdks.NewWeb3sdksSDK("mumbai", &web3sdks.SDKOptions{
// PrivateKey: privateKey,
// })
//
// marketplace, err := sdk.GetMarketplace("{{contract_address}}")
//
// // Now the encoder can be accessed from the contract
// marketplace.Encoder.CreateListing(...)
type MarketplaceEncoder struct {
abi *abi.Marketplace
helper *contractHelper
storage storage
*ContractEncoder
}
func newMarketplaceEncoder(contractAbi *abi.Marketplace, helper *contractHelper, storage storage) (*MarketplaceEncoder, error) {
encoder, err := newContractEncoder(abi.MarketplaceABI, helper)
if err != nil {
return nil, err
}
return &MarketplaceEncoder{
abi: contractAbi,
helper: helper,
storage: storage,
ContractEncoder: encoder,
}, nil
}
// Get the data for the transaction required to cancel a listing on the marketplace
//
// signerAddress: the address intended to sign the transaction
//
// listingId: the ID of the listing to cancel
//
// returns: the transaction data for the cancellation
//
// Example
//
// // Address of the wallet we expect to sign this message
// signerAddress := "0x..."
// // ID of the listing to cancel
// listingId := 1
//
// // Transaction data required for this request
// tx, err := marketplace.Encoder.CancelListing(context.Background(), signerAddress, listingId)
//
// // Now you can get transaction all the standard data as needed
// fmt.Println(tx.Data()) // Ex: get the data field or the nonce field (others are available)
// fmt.Println(tx.Nonce())
func (encoder *MarketplaceEncoder) CancelListing(ctx context.Context, signerAddress string, listingId int) (*types.Transaction, error) {
txOpts, err := encoder.helper.getUnsignedTxOptions(ctx, signerAddress)
if err != nil {
return nil, err
}
return encoder.abi.CancelDirectListing(txOpts, big.NewInt(int64(listingId)))
}
// Get the transaction data to approve the tokens needed for a buyout listing transaction. If the transaction
// wouldn't require any additional token approvals, this method will return nil.
//
// signerAddress: the address intended to sign the transaction
//
// listingId: the ID of the listing to buyout
//
// quantityDesired: the quantity of the listed tokens to purchase
//
// receiver: the address to receive the purchased tokens
//
// returns: the transaction data for the token approval if an approval is needed, or nil
//
// Example
//
// // Address of the wallet we expect to sign this message
// signerAddress := "0x..."
// // ID of the listing to buyout
// listingId := 1
// // Quantity of the listed tokens to purchase
// quantityDesired := 1
// // receiver address to receive the purchased tokens
// receiver := "0x..."
//
// // Transaction data required for this request
// tx, err := marketplace.Encoder.ApproveBuyoutListing(context.Background(), signerAddress, listingId, quantityDesired, receiver)
//
// // Now you can get transaction all the standard data as needed
// fmt.Println(tx.Data()) // Ex: get the data field or the nonce field (others are available)
// fmt.Println(tx.Nonce())
func (encoder *MarketplaceEncoder) ApproveBuyoutListing(
ctx context.Context,
signerAddress string,
listingId int,
quantityDesired int,
receiver string,
) (*types.Transaction, error) {
listing, err := encoder.validateListing(ctx, listingId)
if err != nil {
return nil, err
}
valid, err := isStillValidListing(ctx, encoder.helper, listing, quantityDesired)
if err != nil {
return nil, err
}
if !valid {
return nil, errors.New("The asset on this listing has been moved from the lister's wallet, this listing is now invalid")
}
quantity := big.NewInt(int64(quantityDesired))
value := listing.BuyoutCurrencyValuePerToken.Value.Mul(listing.BuyoutCurrencyValuePerToken.Value, quantity)
return setErc20AllowanceEncoder(
ctx,
encoder.helper,
signerAddress,
value,
listing.CurrencyContractAddress,
)
}
// Get the transaction data for the buyout listing transaction. This method will throw an error if the listing requires
// payment in ERC20 tokens and the ERC20 tokens haven't yet been approved by the spender. You can get the
// transaction data of this required approval transaction from the `ApproveBuyoutListing` method.
//
// signerAddress: the address intended to sign the transaction
//
// listingId: the ID of the listing to buyout
//
// quantityDesired: the quantity of the listed tokens to purchase
//
// receiver: the address to receive the purchased tokens
//
// returns: the transaction data for this purchase
//
// Example
//
// // Address of the wallet we expect to sign this message
// signerAddress := "0x..."
// // ID of the listing to buyout
// listingId := 1
// // Quantity of the listed tokens to purchase
// quantityDesired := 1
// // receiver address to receive the purchased tokens
// receiver := "0x..."
//
// // Transaction data required for this request
// tx, err := marketplace.Encoder.BuyoutListing(context.Background(), signerAddress, listingId, quantityDesired, receiver)
//
// // Now you can get transaction all the standard data as needed
// fmt.Println(tx.Data()) // Ex: get the data field or the nonce field (others are available)
// fmt.Println(tx.Nonce())
func (encoder *MarketplaceEncoder) BuyoutListing(
ctx context.Context,
signerAddress string,
listingId int,
quantityDesired int,
receiver string,
) (*types.Transaction, error) {
listing, err := encoder.validateListing(ctx, listingId)
if err != nil {
return nil, err
}
valid, err := isStillValidListing(ctx, encoder.helper, listing, quantityDesired)
if err != nil {
return nil, err
}
if !valid {
return nil, errors.New("The asset on this listing has been moved from the lister's wallet, this listing is now invalid")
}
quantity := big.NewInt(int64(quantityDesired))
value := listing.BuyoutCurrencyValuePerToken.Value.Mul(listing.BuyoutCurrencyValuePerToken.Value, quantity)
if err := encoder.checkErc20Allowance(
ctx,
signerAddress,
value,
listing.CurrencyContractAddress,
); err != nil {
return nil, err
}
txOpts, err := encoder.helper.getUnsignedTxOptions(ctx, signerAddress)
return encoder.abi.Buy(
txOpts,
big.NewInt(int64(listingId)),
common.HexToAddress(receiver),
big.NewInt(int64(quantityDesired)),
common.HexToAddress(listing.CurrencyContractAddress),
value,
)
}
// Get the transaction data to approve the tokens needed for a create liting transaction. If the transaction
// wouldn't require any additional token approvals, this method will return nil.
//
// signerAddress: the address intended to sign the transaction
//
// listing: the parameters for the new direct listing to create
//
// returns: the transaction data for the create listing transaction
//
// Example
//
// // Address of the wallet we expect to sign this message
// signerAddress := "0x..."
//
// listing := &NewDirectListing{
// AssetContractAddress: "0x...", // Address of the asset contract
// TokenId: 0, // Token ID of the asset to list
// StartTimeInEpochSeconds: int(time.Now().Unix()), // Defaults to current time
// ListingDurationInSeconds: int(time.Now().Unix() + 3600), // Defaults to current time + 1 hour
// Quantity: 1, // Quantity of the asset to list
// CurrencyContractAddress: "0x...", // Contract address of currency to sell for, defaults to native token
// BuyoutPricePerToken: 1, // Price per token of the asset to list
// }
//
// // Transaction data required for this request
// tx, err := marketplace.Encoder.ApproveCreateListing(context.Background(), signerAddress, listing)
//
// // Now you can get transaction data as needed
// fmt.Println(tx.Data()) // Ex: get the data field or the nonce field (others are available)
// fmt.Println(tx.Nonce())
func (encoder *MarketplaceEncoder) ApproveCreateListing(ctx context.Context, signerAddress string, listing *NewDirectListing) (*types.Transaction, error) {
listing.fillDefaults()
return encoder.handleTokenApproval(
ctx,
signerAddress,
encoder.helper.GetProvider(),
encoder.helper,
encoder.helper.getAddress().Hex(),
listing.AssetContractAddress,
listing.TokenId,
encoder.helper.GetSignerAddress().Hex(),
)
}
// Get the data for the transaction required to create a direct listing. This method will throw an error if
// the tokens needed for the listing have not yet been approved by the asset owner for the marketplace to spend.
// You can get the transaction data of this required approval transaction from the `ApproveCreateListing` method.
//
// signerAddress: the address intended to sign the transaction
//
// listing: the parameters for the new direct listing to create
//
// returns: the transaction data for the create listing transaction
//
// Example
//
// // Address of the wallet we expect to sign this message
// signerAddress := "0x..."
//
// listing := &NewDirectListing{
// AssetContractAddress: "0x...", // Address of the asset contract
// TokenId: 0, // Token ID of the asset to list
// StartTimeInEpochSeconds: int(time.Now().Unix()), // Defaults to current time
// ListingDurationInSeconds: int(time.Now().Unix() + 3600), // Defaults to current time + 1 hour
// Quantity: 1, // Quantity of the asset to list
// CurrencyContractAddress: "0x...", // Contract address of currency to sell for, defaults to native token
// BuyoutPricePerToken: 1, // Price per token of the asset to list
// }
//
// // Transaction data required for this request
// tx, err := marketplace.Encoder.CreateListing(context.Background(), signerAddress, listing)
//
// // Now you can get transaction data as needed
// fmt.Println(tx.Data()) // Ex: get the data field or the nonce field (others are available)
// fmt.Println(tx.Nonce())
func (encoder *MarketplaceEncoder) CreateListing(ctx context.Context, signerAddress string, listing *NewDirectListing) (*types.Transaction, error) {
listing.fillDefaults()
err := encoder.checkTokenApproval(
ctx,
signerAddress,
encoder.helper.GetProvider(),
encoder.helper,
encoder.helper.getAddress().Hex(),
listing.AssetContractAddress,
listing.TokenId,
encoder.helper.GetSignerAddress().Hex(),
)
if err != nil {
return nil, err
}
normalizedPricePerToken, err := normalizePriceValue(
ctx,
encoder.helper.GetProvider(),
listing.BuyoutPricePerToken,
listing.CurrencyContractAddress,
)
if err != nil {
return nil, err
}
txOpts, err := encoder.helper.getUnsignedTxOptions(ctx, signerAddress)
if err != nil {
return nil, err
}
return encoder.abi.CreateListing(txOpts, abi.IMarketplaceListingParameters{
AssetContract: common.HexToAddress(listing.AssetContractAddress),
TokenId: big.NewInt(int64(listing.TokenId)),
StartTime: big.NewInt(int64(listing.StartTimeInEpochSeconds)),
SecondsUntilEndTime: big.NewInt(int64(listing.ListingDurationInSeconds)),
QuantityToList: big.NewInt(int64(listing.Quantity)),
CurrencyToAccept: common.HexToAddress(listing.CurrencyContractAddress),
ReservePricePerToken: normalizedPricePerToken,
BuyoutPricePerToken: normalizedPricePerToken,
ListingType: 0,
})
}
func (encoder *MarketplaceEncoder) validateListing(ctx context.Context, listingId int) (*DirectListing, error) {
listing, err := encoder.abi.Listings(&bind.CallOpts{Context: ctx}, big.NewInt(int64(listingId)))
if err != nil {
return nil, err
}
if listing.AssetContract.String() == zeroAddress {
return nil, fmt.Errorf("Failed to find listing with ID %d", listingId)
}
if listing.ListingType == 0 {
return mapListing(ctx, encoder.helper, encoder.storage, listing)
} else {
return nil, fmt.Errorf("Unknown listing type: %d", listingId)
}
}
func (encoder *MarketplaceEncoder) checkErc20Allowance(
ctx context.Context,
signerAddress string,
value *big.Int,
currencyAddress string,
) error {
if isNativeToken(currencyAddress) {
return nil
} else {
provider := encoder.helper.GetProvider()
erc20, err := abi.NewIERC20(common.HexToAddress(currencyAddress), provider)
if err != nil {
return err
}
owner := common.HexToAddress(signerAddress)
spender := encoder.helper.getAddress()
allowance, err := erc20.Allowance(&bind.CallOpts{Context: ctx}, owner, spender)
if err != nil {
return err
}
if allowance.Cmp(value) < 0 {
return fmt.Errorf(
"Marketplace contract '%s' has insufficient allowance to spend ERC20 token '%s' on behalf of the user wallet '%s' "+
"Please approve the contract to spend tokens with the "+
"'marketplace.Encoder.ApproveBuyoutListing(signerAddress, listingId, quantityDesired, receiver)' method",
encoder.helper.getAddress().Hex(),
currencyAddress,
signerAddress,
)
}
return nil
}
}
func (encoder *MarketplaceEncoder) checkTokenApproval(
ctx context.Context,
signerAddress string,
provider *ethclient.Client,
helper *contractHelper,
marketplaceAddress string,
assetContract string,
tokenId int,
from string,
) error {
erc165, err := abi.NewIERC165(common.HexToAddress(assetContract), provider)
if err != nil {
return err
}
isErc721, err := erc165.SupportsInterface(&bind.CallOpts{Context: ctx}, [4]byte{0x80, 0xAC, 0x58, 0xCD})
if err != nil {
return err
}
isErc1155, err := erc165.SupportsInterface(&bind.CallOpts{Context: ctx}, [4]byte{0xD9, 0xB6, 0x7A, 0x26})
if err != nil {
return err
}
if isErc721 {
contract, err := abi.NewTokenERC721(common.HexToAddress(assetContract), provider)
if err != nil {
return err
}
approved, err := contract.IsApprovedForAll(&bind.CallOpts{Context: ctx}, common.HexToAddress(from), common.HexToAddress(marketplaceAddress))
if err != nil {
return err
}
if !approved {
tokenApproved, err := contract.GetApproved(&bind.CallOpts{Context: ctx}, big.NewInt(int64(tokenId)))
if err != nil {
return err
}
if strings.ToLower(tokenApproved.String()) != strings.ToLower(marketplaceAddress) {
return fmt.Errorf(
"Marketplace contract '%s' doesn't have approval to transfer ERC721 token '%s' with ID %d from the user wallet '%s' "+
"Please approve the contract to transfer tokens with the "+
"'marketplace.Encoder.ApproveCreateListing(signerAddress, listing)' method",
helper.getAddress().Hex(),
assetContract,
tokenId,
signerAddress,
)
}
}
} else if isErc1155 {
contract, err := abi.NewTokenERC1155(common.HexToAddress(assetContract), provider)
if err != nil {
return err
}
approved, err := contract.IsApprovedForAll(&bind.CallOpts{Context: ctx}, common.HexToAddress(from), common.HexToAddress(marketplaceAddress))
if err != nil {
return err
}
if !approved {
return fmt.Errorf(
"Marketplace contract '%s' doesn't have approval to transfer ERC1155 token '%s' with ID %d from the user wallet '%s' "+
"Please approve the contract to transfer tokens with the "+
"'marketplace.Encoder.ApproveCreateListing(signerAddress, listing)' method",
helper.getAddress().Hex(),
assetContract,
tokenId,
signerAddress,
)
}
} else {
return errors.New("Contract does not implement ERC721 or ERC1155.")
}
return nil
}
func (encoder *MarketplaceEncoder) handleTokenApproval(
ctx context.Context,
signerAddress string,
provider *ethclient.Client,
helper *contractHelper,
marketplaceAddress string,
assetContract string,
tokenId int,
from string,
) (*types.Transaction, error) {
erc165, err := abi.NewIERC165(common.HexToAddress(assetContract), provider)
if err != nil {
return nil, err
}
isErc721, err := erc165.SupportsInterface(&bind.CallOpts{Context: ctx}, [4]byte{0x80, 0xAC, 0x58, 0xCD})
if err != nil {
return nil, err
}
isErc1155, err := erc165.SupportsInterface(&bind.CallOpts{Context: ctx}, [4]byte{0xD9, 0xB6, 0x7A, 0x26})
if err != nil {
return nil, err
}
if isErc721 {
contract, err := abi.NewTokenERC721(common.HexToAddress(assetContract), provider)
if err != nil {
return nil, err
}
approved, err := contract.IsApprovedForAll(&bind.CallOpts{
Context: ctx,
}, common.HexToAddress(from), common.HexToAddress(marketplaceAddress))
if err != nil {
return nil, err
}
if !approved {
tokenApproved, err := contract.GetApproved(&bind.CallOpts{Context: ctx}, big.NewInt(int64(tokenId)))
if err != nil {
return nil, err
}
txOpts, err := helper.getUnsignedTxOptions(ctx, signerAddress)
if err != nil {
return nil, err
}
if strings.ToLower(tokenApproved.String()) != strings.ToLower(marketplaceAddress) {
return contract.SetApprovalForAll(txOpts, common.HexToAddress(marketplaceAddress), true)
}
}
} else if isErc1155 {
contract, err := abi.NewTokenERC1155(common.HexToAddress(assetContract), provider)
if err != nil {
return nil, err
}
approved, err := contract.IsApprovedForAll(&bind.CallOpts{Context: ctx}, common.HexToAddress(from), common.HexToAddress(marketplaceAddress))
if err != nil {
return nil, err
}
if !approved {
txOpts, err := helper.getUnsignedTxOptions(ctx, signerAddress)
if err != nil {
return nil, err
}
return contract.SetApprovalForAll(txOpts, common.HexToAddress(marketplaceAddress), true)
}
} else {
return nil, errors.New("Contract does not implement ERC721 or ERC1155")
}
return nil, nil
}