@imtbl/sdk 0.1.7-alpha.1 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,23 +1,14 @@
1
1
  import { ImmutableX, Config, generateLegacyStarkPrivateKey, createStarkSigner, TransfersApi, OrdersApi, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi } from '@imtbl/core-sdk';
2
2
  export { createStarkSigner as imxClientCreateStarkSigner, generateLegacyStarkPrivateKey as imxClientGenerateLegacyStarkPrivateKey } from '@imtbl/core-sdk';
3
- import * as guardian from '@imtbl/guardian';
4
- export { guardian };
5
3
  import { UserManager } from 'oidc-client-ts';
6
- import { ethers, utils, Contract, BigNumber, constants } from 'ethers';
4
+ import { ethers } from 'ethers';
7
5
  import { Magic } from 'magic-sdk';
8
6
  import { OpenIdExtension } from '@magic-ext/oidc';
9
7
  import BN from 'bn.js';
10
8
  import * as encUtils from 'enc-utils';
11
- import { ItemType, SEAPORT_CONTRACT_NAME, SEAPORT_CONTRACT_VERSION_V1_4, EIP_712_ORDER_TYPE, OrderType } from '@opensea/seaport-js/lib/constants';
12
- import FormData from 'form-data';
13
- import fetch, { Headers } from 'node-fetch';
14
- import { Seaport as Seaport$1 } from '@opensea/seaport-js';
15
9
  import { parseUnits } from '@ethersproject/units';
16
- import { BigNumber as BigNumber$1 } from '@ethersproject/bignumber';
10
+ import { BigNumber } from '@ethersproject/bignumber';
17
11
  import detectEthereumProvider from '@metamask/detect-provider';
18
- import { Web3Provider } from '@ethersproject/providers';
19
- import { jsx } from 'react/jsx-runtime';
20
- import 'react';
21
12
 
22
13
  var Environment;
23
14
  (function (Environment) {
@@ -41,7 +32,7 @@ const production = () => Config.createConfig({
41
32
  chainID: 1,
42
33
  coreContractAddress: '0x5FDCCA53617f4d2b9134B29090C87D01058e27e9',
43
34
  registrationContractAddress: '0x72a06bf2a1CE5e39cBA06c0CAb824960B587d64c',
44
- sdkVersion: 'ts-immutable-sdk-0.1.7-alpha.1',
35
+ sdkVersion: 'ts-immutable-sdk-0.0.0',
45
36
  });
46
37
  /**
47
38
  * Set `sdkVersion` on config
@@ -51,7 +42,7 @@ const sandbox = () => Config.createConfig({
51
42
  chainID: 5,
52
43
  coreContractAddress: '0x7917eDb51ecD6CdB3F9854c3cc593F33de10c623',
53
44
  registrationContractAddress: '0x1C97Ada273C9A52253f463042f29117090Cd7D83',
54
- sdkVersion: 'ts-immutable-sdk-0.1.7-alpha.1',
45
+ sdkVersion: 'ts-immutable-sdk-0.0.0',
55
46
  });
56
47
  class ImxConfiguration {
57
48
  immutableXConfig;
@@ -1012,12 +1003,12 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, pass
1012
1003
  }, PassportErrorType.TRANSFER_ERROR);
1013
1004
  }
1014
1005
 
1015
- const ERC721$2 = 'ERC721';
1006
+ const ERC721 = 'ERC721';
1016
1007
  async function createOrder$1({ starkSigner, user, request, ordersApi, passportConfig, }) {
1017
1008
  return withPassportError(async () => {
1018
1009
  const ethAddress = user.etherKey;
1019
- const amountSell = request.sell.type === ERC721$2 ? '1' : request.sell.amount;
1020
- const amountBuy = request.buy.type === ERC721$2 ? '1' : request.buy.amount;
1010
+ const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
1011
+ const amountBuy = request.buy.type === ERC721 ? '1' : request.buy.amount;
1021
1012
  const getSignableOrderRequestV3 = {
1022
1013
  user: ethAddress,
1023
1014
  amount_buy: amountBuy,
@@ -1485,2508 +1476,682 @@ class Passport {
1485
1476
  }
1486
1477
  }
1487
1478
 
1488
- class BaseHttpRequest {
1489
- config;
1490
- constructor(config) {
1491
- this.config = config;
1492
- }
1479
+ function isChainValid(chainID, config) {
1480
+ return chainID === config.ethConfiguration.chainID;
1493
1481
  }
1494
-
1495
- class ApiError extends Error {
1496
- url;
1497
- status;
1498
- statusText;
1499
- body;
1500
- request;
1501
- constructor(request, response, message) {
1502
- super(message);
1503
- this.name = 'ApiError';
1504
- this.url = response.url;
1505
- this.status = response.status;
1506
- this.statusText = response.statusText;
1507
- this.body = response.body;
1508
- this.request = request;
1482
+ async function validateChain(signer, config) {
1483
+ const chainID = await signer.getChainId();
1484
+ if (!isChainValid(chainID, config)) {
1485
+ throw new Error('The wallet used for this operation is not connected to the correct network.');
1509
1486
  }
1510
1487
  }
1511
1488
 
1512
- /* istanbul ignore file */
1513
- /* tslint:disable */
1514
- /* eslint-disable */
1515
- class CancelError extends Error {
1516
- constructor(message) {
1517
- super(message);
1518
- this.name = 'CancelError';
1519
- }
1520
- get isCancelled() {
1521
- return true;
1522
- }
1489
+ async function transfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1490
+ await validateChain(ethSigner, config.immutableXConfig);
1491
+ const ethAddress = await ethSigner.getAddress();
1492
+ const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
1493
+ const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
1494
+ const signableResult = await transfersApi.getSignableTransferV1({
1495
+ getSignableTransferRequest: {
1496
+ sender: ethAddress,
1497
+ token: convertToSignableToken(request),
1498
+ amount: transferAmount,
1499
+ receiver: request.receiver,
1500
+ },
1501
+ });
1502
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1503
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1504
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1505
+ const transferSigningParams = {
1506
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1507
+ sender_stark_key: signableResult.data.sender_stark_key,
1508
+ sender_vault_id: signableResult.data.sender_vault_id,
1509
+ receiver_stark_key: signableResult.data.receiver_stark_key,
1510
+ receiver_vault_id: signableResult.data.receiver_vault_id,
1511
+ asset_id: signableResult.data.asset_id,
1512
+ amount: signableResult.data.amount,
1513
+ nonce: signableResult.data.nonce,
1514
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1515
+ stark_signature: starkSignature,
1516
+ };
1517
+ const response = await transfersApi.createTransferV1({
1518
+ createTransferRequest: transferSigningParams,
1519
+ xImxEthAddress: ethAddress,
1520
+ xImxEthSignature: ethSignature,
1521
+ });
1522
+ return {
1523
+ sent_signature: response?.data.sent_signature,
1524
+ status: response?.data.status?.toString(),
1525
+ time: response?.data.time,
1526
+ transfer_id: response?.data.transfer_id,
1527
+ };
1523
1528
  }
1524
- class CancelablePromise {
1525
- [Symbol.toStringTag];
1526
- _isResolved;
1527
- _isRejected;
1528
- _isCancelled;
1529
- _cancelHandlers;
1530
- _promise;
1531
- _resolve;
1532
- _reject;
1533
- constructor(executor) {
1534
- this._isResolved = false;
1535
- this._isRejected = false;
1536
- this._isCancelled = false;
1537
- this._cancelHandlers = [];
1538
- this._promise = new Promise((resolve, reject) => {
1539
- this._resolve = resolve;
1540
- this._reject = reject;
1541
- const onResolve = (value) => {
1542
- if (this._isResolved || this._isRejected || this._isCancelled) {
1543
- return;
1544
- }
1545
- this._isResolved = true;
1546
- this._resolve?.(value);
1547
- };
1548
- const onReject = (reason) => {
1549
- if (this._isResolved || this._isRejected || this._isCancelled) {
1550
- return;
1551
- }
1552
- this._isRejected = true;
1553
- this._reject?.(reason);
1554
- };
1555
- const onCancel = (cancelHandler) => {
1556
- if (this._isResolved || this._isRejected || this._isCancelled) {
1557
- return;
1558
- }
1559
- this._cancelHandlers.push(cancelHandler);
1560
- };
1561
- Object.defineProperty(onCancel, 'isResolved', {
1562
- get: () => this._isResolved,
1563
- });
1564
- Object.defineProperty(onCancel, 'isRejected', {
1565
- get: () => this._isRejected,
1566
- });
1567
- Object.defineProperty(onCancel, 'isCancelled', {
1568
- get: () => this._isCancelled,
1569
- });
1570
- return executor(onResolve, onReject, onCancel);
1571
- });
1572
- }
1573
- then(onFulfilled, onRejected) {
1574
- return this._promise.then(onFulfilled, onRejected);
1575
- }
1576
- catch(onRejected) {
1577
- return this._promise.catch(onRejected);
1578
- }
1579
- finally(onFinally) {
1580
- return this._promise.finally(onFinally);
1581
- }
1582
- cancel() {
1583
- if (this._isResolved || this._isRejected || this._isCancelled) {
1584
- return;
1585
- }
1586
- this._isCancelled = true;
1587
- if (this._cancelHandlers.length) {
1588
- try {
1589
- for (const cancelHandler of this._cancelHandlers) {
1590
- cancelHandler();
1591
- }
1592
- }
1593
- catch (error) {
1594
- console.warn('Cancellation threw an error', error);
1595
- return;
1596
- }
1597
- }
1598
- this._cancelHandlers.length = 0;
1599
- this._reject?.(new CancelError('Request aborted'));
1529
+ async function batchTransfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1530
+ await validateChain(ethSigner, config.immutableXConfig);
1531
+ const ethAddress = await ethSigner.getAddress();
1532
+ const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
1533
+ const signableRequests = request.map((nftTransfer) => ({
1534
+ amount: '1',
1535
+ token: convertToSignableToken({
1536
+ type: 'ERC721',
1537
+ tokenId: nftTransfer.tokenId,
1538
+ tokenAddress: nftTransfer.tokenAddress,
1539
+ }),
1540
+ receiver: nftTransfer.receiver,
1541
+ }));
1542
+ const signableResult = await transfersApi.getSignableTransfer({
1543
+ getSignableTransferRequestV2: {
1544
+ sender_ether_key: ethAddress,
1545
+ signable_requests: signableRequests,
1546
+ },
1547
+ });
1548
+ const signableMessage = signableResult.data.signable_message;
1549
+ if (signableMessage === undefined) {
1550
+ throw new Error('Invalid response from Signable registration offchain');
1600
1551
  }
1601
- get isCancelled() {
1602
- return this._isCancelled;
1552
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1553
+ const requests = [];
1554
+ for (const resp of signableResult.data.signable_responses) {
1555
+ // TODO: remove once fixed
1556
+ // eslint-disable-next-line no-await-in-loop
1557
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
1558
+ const req = {
1559
+ sender_vault_id: resp.sender_vault_id,
1560
+ receiver_stark_key: resp.receiver_stark_key,
1561
+ receiver_vault_id: resp.receiver_vault_id,
1562
+ asset_id: resp.asset_id,
1563
+ amount: resp.amount,
1564
+ nonce: resp.nonce,
1565
+ expiration_timestamp: resp.expiration_timestamp,
1566
+ stark_signature: starkSignature,
1567
+ };
1568
+ requests.push(req);
1603
1569
  }
1570
+ // TODO: throw error on missing payload hash?
1571
+ const transferSigningParams = {
1572
+ sender_stark_key: signableResult.data.sender_stark_key,
1573
+ requests,
1574
+ };
1575
+ const response = await transfersApi.createTransfer({
1576
+ createTransferRequestV2: transferSigningParams,
1577
+ xImxEthAddress: ethAddress,
1578
+ xImxEthSignature: ethSignature,
1579
+ });
1580
+ return {
1581
+ transfer_ids: response?.data.transfer_ids,
1582
+ };
1604
1583
  }
1605
1584
 
1606
- /* istanbul ignore file */
1607
- /* tslint:disable */
1608
- /* eslint-disable */
1609
- const isDefined = (value) => {
1610
- return value !== undefined && value !== null;
1611
- };
1612
- const isString = (value) => {
1613
- return typeof value === 'string';
1614
- };
1615
- const isStringWithValue = (value) => {
1616
- return isString(value) && value !== '';
1617
- };
1618
- const isBlob = (value) => {
1619
- return (typeof value === 'object' &&
1620
- typeof value.type === 'string' &&
1621
- typeof value.stream === 'function' &&
1622
- typeof value.arrayBuffer === 'function' &&
1623
- typeof value.constructor === 'function' &&
1624
- typeof value.constructor.name === 'string' &&
1625
- /^(Blob|File)$/.test(value.constructor.name) &&
1626
- /^(Blob|File)$/.test(value[Symbol.toStringTag]));
1627
- };
1628
- const isFormData = (value) => {
1629
- return value instanceof FormData;
1630
- };
1631
- const base64 = (str) => {
1632
- try {
1633
- return btoa(str);
1634
- }
1635
- catch (err) {
1636
- // @ts-ignore
1637
- return Buffer.from(str).toString('base64');
1638
- }
1639
- };
1640
- const getQueryString = (params) => {
1641
- const qs = [];
1642
- const append = (key, value) => {
1643
- qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1585
+ async function createOrder({ signers, request, config, }) {
1586
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1587
+ const ethAddress = await signers.ethSigner.getAddress();
1588
+ const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
1589
+ const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
1590
+ const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
1591
+ const getSignableOrderRequest = {
1592
+ user: ethAddress,
1593
+ amount_buy: amountBuy,
1594
+ token_buy: convertToSignableToken(request.buy),
1595
+ amount_sell: amountSell,
1596
+ token_sell: convertToSignableToken(request.sell),
1597
+ fees: request.fees,
1598
+ expiration_timestamp: request.expiration_timestamp,
1644
1599
  };
1645
- const process = (key, value) => {
1646
- if (isDefined(value)) {
1647
- if (Array.isArray(value)) {
1648
- value.forEach(v => {
1649
- process(key, v);
1650
- });
1651
- }
1652
- else if (typeof value === 'object') {
1653
- Object.entries(value).forEach(([k, v]) => {
1654
- process(`${key}[${k}]`, v);
1655
- });
1656
- }
1657
- else {
1658
- append(key, value);
1659
- }
1660
- }
1600
+ const getSignableOrderResponse = await ordersApi.getSignableOrder({
1601
+ getSignableOrderRequestV3: getSignableOrderRequest,
1602
+ });
1603
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
1604
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1605
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1606
+ const resp = getSignableOrderResponse.data;
1607
+ const orderParams = {
1608
+ createOrderRequest: {
1609
+ amount_buy: resp.amount_buy,
1610
+ amount_sell: resp.amount_sell,
1611
+ asset_id_buy: resp.asset_id_buy,
1612
+ asset_id_sell: resp.asset_id_sell,
1613
+ expiration_timestamp: resp.expiration_timestamp,
1614
+ include_fees: true,
1615
+ fees: request.fees,
1616
+ nonce: resp.nonce,
1617
+ stark_key: resp.stark_key,
1618
+ stark_signature: starkSignature,
1619
+ vault_id_buy: resp.vault_id_buy,
1620
+ vault_id_sell: resp.vault_id_sell,
1621
+ },
1622
+ xImxEthAddress: ethAddress,
1623
+ xImxEthSignature: ethSignature,
1624
+ };
1625
+ const createOrderResponse = await ordersApi.createOrder(orderParams);
1626
+ return {
1627
+ ...createOrderResponse.data,
1628
+ };
1629
+ }
1630
+ async function cancelOrder({ signers, request, config, }) {
1631
+ const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
1632
+ const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
1633
+ getSignableCancelOrderRequest: {
1634
+ order_id: request.order_id,
1635
+ },
1636
+ });
1637
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
1638
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1639
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1640
+ const ethAddress = await signers.ethSigner.getAddress();
1641
+ const cancelOrderResponse = await ordersApi.cancelOrder({
1642
+ id: request.order_id.toString(),
1643
+ cancelOrderRequest: {
1644
+ order_id: request.order_id,
1645
+ stark_signature: starkSignature,
1646
+ },
1647
+ xImxEthAddress: ethAddress,
1648
+ xImxEthSignature: ethSignature,
1649
+ });
1650
+ return {
1651
+ order_id: cancelOrderResponse.data.order_id,
1652
+ status: cancelOrderResponse.data.status,
1661
1653
  };
1662
- Object.entries(params).forEach(([key, value]) => {
1663
- process(key, value);
1654
+ }
1655
+
1656
+ async function registerOffchain(signers, config) {
1657
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1658
+ const usersApi = new UsersApi(config.immutableXConfig.apiConfiguration);
1659
+ const userAddress = await signers.ethSigner.getAddress();
1660
+ const starkPublicKey = await signers.starkSigner.getAddress();
1661
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
1662
+ getSignableRegistrationRequest: {
1663
+ ether_key: userAddress,
1664
+ stark_key: starkPublicKey,
1665
+ },
1664
1666
  });
1665
- if (qs.length > 0) {
1666
- return `?${qs.join('&')}`;
1667
- }
1668
- return '';
1669
- };
1670
- const getUrl = (config, options) => {
1671
- const encoder = config.ENCODE_PATH || encodeURI;
1672
- const path = options.url
1673
- .replace('{api-version}', config.VERSION)
1674
- .replace(/{(.*?)}/g, (substring, group) => {
1675
- if (options.path?.hasOwnProperty(group)) {
1676
- return encoder(String(options.path[group]));
1677
- }
1678
- return substring;
1667
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1668
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1669
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1670
+ const registeredUser = await usersApi.registerUser({
1671
+ registerUserRequest: {
1672
+ eth_signature: ethSignature,
1673
+ ether_key: userAddress,
1674
+ stark_signature: starkSignature,
1675
+ stark_key: starkPublicKey,
1676
+ },
1679
1677
  });
1680
- const url = `${config.BASE}${path}`;
1681
- if (options.query) {
1682
- return `${url}${getQueryString(options.query)}`;
1678
+ return registeredUser.data;
1679
+ }
1680
+ async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
1681
+ await validateChain(ethSigner, config.immutableXConfig);
1682
+ const registrationContract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1683
+ try {
1684
+ return await registrationContract.isRegistered(starkPublicKey);
1683
1685
  }
1684
- return url;
1685
- };
1686
- const getFormData = (options) => {
1687
- if (options.formData) {
1688
- const formData = new FormData();
1689
- const process = (key, value) => {
1690
- if (isString(value) || isBlob(value)) {
1691
- formData.append(key, value);
1692
- }
1693
- else {
1694
- formData.append(key, JSON.stringify(value));
1695
- }
1696
- };
1697
- Object.entries(options.formData)
1698
- .filter(([_, value]) => isDefined(value))
1699
- .forEach(([key, value]) => {
1700
- if (Array.isArray(value)) {
1701
- value.forEach(v => process(key, v));
1702
- }
1703
- else {
1704
- process(key, value);
1705
- }
1706
- });
1707
- return formData;
1686
+ catch (ex) {
1687
+ if (ex.reason === 'USER_UNREGISTERED') {
1688
+ return false;
1689
+ }
1690
+ throw ex;
1708
1691
  }
1709
- return undefined;
1710
- };
1711
- const resolve = async (options, resolver) => {
1712
- if (typeof resolver === 'function') {
1713
- return resolver(options);
1714
- }
1715
- return resolver;
1716
- };
1717
- const getHeaders = async (config, options) => {
1718
- const token = await resolve(options, config.TOKEN);
1719
- const username = await resolve(options, config.USERNAME);
1720
- const password = await resolve(options, config.PASSWORD);
1721
- const additionalHeaders = await resolve(options, config.HEADERS);
1722
- const headers = Object.entries({
1723
- Accept: 'application/json',
1724
- ...additionalHeaders,
1725
- ...options.headers,
1726
- })
1727
- .filter(([_, value]) => isDefined(value))
1728
- .reduce((headers, [key, value]) => ({
1729
- ...headers,
1730
- [key]: String(value),
1731
- }), {});
1732
- if (isStringWithValue(token)) {
1733
- headers['Authorization'] = `Bearer ${token}`;
1734
- }
1735
- if (isStringWithValue(username) && isStringWithValue(password)) {
1736
- const credentials = base64(`${username}:${password}`);
1737
- headers['Authorization'] = `Basic ${credentials}`;
1738
- }
1739
- if (options.body) {
1740
- if (options.mediaType) {
1741
- headers['Content-Type'] = options.mediaType;
1742
- }
1743
- else if (isBlob(options.body)) {
1744
- headers['Content-Type'] = 'application/octet-stream';
1745
- }
1746
- else if (isString(options.body)) {
1747
- headers['Content-Type'] = 'text/plain';
1748
- }
1749
- else if (!isFormData(options.body)) {
1750
- headers['Content-Type'] = 'application/json';
1751
- }
1752
- }
1753
- return new Headers(headers);
1754
- };
1755
- const getRequestBody = (options) => {
1756
- if (options.body) {
1757
- if (options.mediaType?.includes('/json')) {
1758
- return JSON.stringify(options.body);
1759
- }
1760
- else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
1761
- return options.body;
1762
- }
1763
- else {
1764
- return JSON.stringify(options.body);
1765
- }
1766
- }
1767
- return undefined;
1768
- };
1769
- const sendRequest = async (options, url, body, formData, headers, onCancel) => {
1770
- const controller = new AbortController();
1771
- const request = {
1772
- headers,
1773
- method: options.method,
1774
- body: body ?? formData,
1775
- signal: controller.signal,
1776
- };
1777
- onCancel(() => controller.abort());
1778
- return await fetch(url, request);
1779
- };
1780
- const getResponseHeader = (response, responseHeader) => {
1781
- if (responseHeader) {
1782
- const content = response.headers.get(responseHeader);
1783
- if (isString(content)) {
1784
- return content;
1785
- }
1786
- }
1787
- return undefined;
1788
- };
1789
- const getResponseBody = async (response) => {
1790
- if (response.status !== 204) {
1791
- try {
1792
- const contentType = response.headers.get('Content-Type');
1793
- if (contentType) {
1794
- const isJSON = contentType.toLowerCase().startsWith('application/json');
1795
- if (isJSON) {
1796
- return await response.json();
1797
- }
1798
- else {
1799
- return await response.text();
1800
- }
1801
- }
1802
- }
1803
- catch (error) {
1804
- console.error(error);
1805
- }
1806
- }
1807
- return undefined;
1808
- };
1809
- const catchErrorCodes = (options, result) => {
1810
- const errors = {
1811
- 400: 'Bad Request',
1812
- 401: 'Unauthorized',
1813
- 403: 'Forbidden',
1814
- 404: 'Not Found',
1815
- 500: 'Internal Server Error',
1816
- 502: 'Bad Gateway',
1817
- 503: 'Service Unavailable',
1818
- ...options.errors,
1692
+ }
1693
+ async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
1694
+ const response = await usersApi.getSignableRegistration({
1695
+ getSignableRegistrationRequest: {
1696
+ ether_key: etherKey,
1697
+ stark_key: starkPublicKey,
1698
+ },
1699
+ });
1700
+ return {
1701
+ operator_signature: response.data.operator_signature,
1702
+ payload_hash: response.data.payload_hash,
1819
1703
  };
1820
- const error = errors[result.status];
1821
- if (error) {
1822
- throw new ApiError(options, result, error);
1823
- }
1824
- if (!result.ok) {
1825
- throw new ApiError(options, result, 'Generic Error');
1826
- }
1704
+ }
1705
+
1706
+ const assertIsDefined = (value) => {
1707
+ if (value !== undefined)
1708
+ return value;
1709
+ throw new Error('undefined field exception');
1827
1710
  };
1828
- /**
1829
- * Request method
1830
- * @param config The OpenAPI configuration object
1831
- * @param options The request options from the service
1832
- * @returns CancelablePromise<T>
1833
- * @throws ApiError
1834
- */
1835
- const request = (config, options) => {
1836
- return new CancelablePromise(async (resolve, reject, onCancel) => {
1837
- try {
1838
- const url = getUrl(config, options);
1839
- const formData = getFormData(options);
1840
- const body = getRequestBody(options);
1841
- const headers = await getHeaders(config, options);
1842
- if (!onCancel.isCancelled) {
1843
- const response = await sendRequest(options, url, body, formData, headers, onCancel);
1844
- const responseBody = await getResponseBody(response);
1845
- const responseHeader = getResponseHeader(response, options.responseHeader);
1846
- const result = {
1847
- url,
1848
- ok: response.ok,
1849
- status: response.status,
1850
- statusText: response.statusText,
1851
- body: responseHeader ?? responseBody,
1852
- };
1853
- catchErrorCodes(options, result);
1854
- resolve(result.body);
1855
- }
1856
- }
1857
- catch (error) {
1858
- reject(error);
1859
- }
1711
+ async function prepareWithdrawalAction(params) {
1712
+ const { signers: { ethSigner, starkSigner }, type, config, } = params;
1713
+ await validateChain(ethSigner, params.config);
1714
+ const withdrawalsApi = new WithdrawalsApi(config.apiConfiguration);
1715
+ const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
1716
+ const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
1717
+ getSignableWithdrawalRequest: {
1718
+ user: await ethSigner.getAddress(),
1719
+ token: convertToSignableToken(params),
1720
+ amount: withdrawalAmount,
1721
+ },
1860
1722
  });
1861
- };
1862
-
1863
- class NodeHttpRequest extends BaseHttpRequest {
1864
- constructor(config) {
1865
- super(config);
1866
- }
1867
- /**
1868
- * Request method
1869
- * @param options The request options from the service
1870
- * @returns CancelablePromise<T>
1871
- * @throws ApiError
1872
- */
1873
- request(options) {
1874
- return request(this.config, options);
1875
- }
1723
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
1724
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1725
+ const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
1726
+ const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
1727
+ createWithdrawalRequest: {
1728
+ stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
1729
+ amount: withdrawalAmount,
1730
+ asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
1731
+ vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
1732
+ nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
1733
+ stark_signature: starkSignature,
1734
+ },
1735
+ xImxEthAddress: ethAddress,
1736
+ xImxEthSignature: ethSignature,
1737
+ });
1738
+ return prepareWithdrawalResponse.data;
1876
1739
  }
1877
1740
 
1878
- class OrdersService {
1879
- httpRequest;
1880
- constructor(httpRequest) {
1881
- this.httpRequest = httpRequest;
1882
- }
1883
- /**
1884
- * List all orders
1885
- * List all orders
1886
- * @returns Orders OK response.
1887
- * @throws ApiError
1888
- */
1889
- listOrders({ chainId, pageSize = 100, sortBy, sortDirection, pageCursor, }) {
1890
- return this.httpRequest.request({
1891
- method: 'GET',
1892
- url: '/v1/chains/{chain_id}/orders',
1893
- path: {
1894
- 'chain_id': chainId,
1895
- },
1896
- query: {
1897
- 'page_size': pageSize,
1898
- 'sort_by': sortBy,
1899
- 'sort_direction': sortDirection,
1900
- 'page_cursor': pageCursor,
1901
- },
1902
- errors: {
1903
- 404: `not_found: Resource not found`,
1904
- 500: `internal_error: Internal server error`,
1905
- },
1906
- });
1907
- }
1908
- /**
1909
- * Create an order
1910
- * Create an order
1911
- * @returns Order Created response.
1912
- * @throws ApiError
1913
- */
1914
- createOrder({ chainId, requestBody, }) {
1915
- return this.httpRequest.request({
1916
- method: 'POST',
1917
- url: '/v1/chains/{chain_id}/orders',
1918
- path: {
1919
- 'chain_id': chainId,
1920
- },
1921
- body: requestBody,
1922
- mediaType: 'application/json',
1923
- errors: {
1924
- 400: `bad_request: Bad Request`,
1925
- 404: `not_found: Resource not found`,
1926
- 500: `internal_error: Internal server error`,
1927
- },
1928
- });
1929
- }
1930
- /**
1931
- * Get a single order by ID
1932
- * Get a single order by ID
1933
- * @returns Order OK response.
1934
- * @throws ApiError
1935
- */
1936
- getOrder({ chainId, orderId, }) {
1937
- return this.httpRequest.request({
1938
- method: 'GET',
1939
- url: '/v1/chains/{chain_id}/orders/{order_id}',
1940
- path: {
1941
- 'chain_id': chainId,
1942
- 'order_id': orderId,
1943
- },
1944
- errors: {
1945
- 404: `not_found: Resource not found`,
1946
- 500: `internal_error: Internal server error`,
1741
+ async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
1742
+ const encodingApi = new EncodingApi(config.apiConfiguration);
1743
+ const result = await encodingApi.encodeAsset({
1744
+ assetType,
1745
+ encodeAssetRequest: {
1746
+ token: {
1747
+ type: tokenType,
1748
+ ...(tokenData && { data: tokenData }),
1947
1749
  },
1948
- });
1949
- }
1750
+ },
1751
+ });
1752
+ return result.data;
1950
1753
  }
1951
1754
 
1952
- class OrderBookClient {
1953
- orders;
1954
- request;
1955
- constructor(config, HttpRequest = NodeHttpRequest) {
1956
- this.request = new HttpRequest({
1957
- BASE: config?.BASE ?? 'https://order-book-mr.dev.imtbl.com',
1958
- VERSION: config?.VERSION ?? '1.0.0',
1959
- WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
1960
- CREDENTIALS: config?.CREDENTIALS ?? 'include',
1961
- TOKEN: config?.TOKEN,
1962
- USERNAME: config?.USERNAME,
1963
- PASSWORD: config?.PASSWORD,
1964
- HEADERS: config?.HEADERS,
1965
- ENCODE_PATH: config?.ENCODE_PATH,
1966
- });
1967
- this.orders = new OrdersService(this.request);
1968
- }
1755
+ async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
1756
+ const etherKey = await ethSigner.getAddress();
1757
+ const imxConfig = config.immutableXConfig;
1758
+ const usersApi = new UsersApi(imxConfig.apiConfiguration);
1759
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1760
+ const contract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1761
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1762
+ return ethSigner.sendTransaction(populatedTransaction);
1969
1763
  }
1970
-
1971
- /* istanbul ignore file */
1972
- /* tslint:disable */
1973
- /* eslint-disable */
1974
- var BuyItem;
1975
- (function (BuyItem) {
1976
- (function (item_type) {
1977
- item_type["ERC20"] = "ERC20";
1978
- item_type["IMX"] = "IMX";
1979
- })(BuyItem.item_type || (BuyItem.item_type = {}));
1980
- })(BuyItem || (BuyItem = {}));
1981
-
1982
- /* istanbul ignore file */
1983
- /* tslint:disable */
1984
- /* eslint-disable */
1985
- var CreateOrderProtocolData;
1986
- (function (CreateOrderProtocolData) {
1987
- (function (order_type) {
1988
- order_type["FULL_OPEN"] = "FULL_OPEN";
1989
- })(CreateOrderProtocolData.order_type || (CreateOrderProtocolData.order_type = {}));
1990
- })(CreateOrderProtocolData || (CreateOrderProtocolData = {}));
1991
-
1992
- /* istanbul ignore file */
1993
- /* tslint:disable */
1994
- /* eslint-disable */
1995
- var Fee;
1996
- (function (Fee) {
1997
- (function (fee_type) {
1998
- fee_type["ROYALTY"] = "ROYALTY";
1999
- })(Fee.fee_type || (Fee.fee_type = {}));
2000
- })(Fee || (Fee = {}));
2001
-
2002
- /* istanbul ignore file */
2003
- /* tslint:disable */
2004
- /* eslint-disable */
2005
- var Order;
2006
- (function (Order) {
2007
- (function (status) {
2008
- status["PENDING"] = "PENDING";
2009
- status["ACTIVE"] = "ACTIVE";
2010
- status["CANCELLED"] = "CANCELLED";
2011
- status["INACTIVE"] = "INACTIVE";
2012
- status["REJECTED"] = "REJECTED";
2013
- status["FILLED"] = "FILLED";
2014
- status["EXPIRED"] = "EXPIRED";
2015
- })(Order.status || (Order.status = {}));
2016
- })(Order || (Order = {}));
2017
-
2018
- /* istanbul ignore file */
2019
- /* tslint:disable */
2020
- /* eslint-disable */
2021
- var SellItem;
2022
- (function (SellItem) {
2023
- (function (item_type) {
2024
- item_type["ERC721"] = "ERC721";
2025
- })(SellItem.item_type || (SellItem.item_type = {}));
2026
- })(SellItem || (SellItem = {}));
2027
-
2028
- class ImmutableApiClient {
2029
- orderbookService;
2030
- chainId;
2031
- constructor(orderbookService, chainId) {
2032
- this.orderbookService = orderbookService;
2033
- this.chainId = chainId;
2034
- }
2035
- async getOrder(orderId) {
2036
- return this.orderbookService.getOrder({ chainId: this.chainId, orderId });
2037
- }
2038
- async createOrder({ orderHash, orderComponents, offerer, orderSignature, }) {
2039
- if (orderComponents.offer.length !== 1) {
2040
- throw new Error('Only one item can be listed at a time');
2041
- }
2042
- if (Number(orderComponents.offer[0].itemType) !== ItemType.ERC721) {
2043
- throw new Error('Only ERC721 tokens can be listed');
2044
- }
2045
- const considerationItemTypeTheSame = new Set([...orderComponents.consideration.map((c) => c.itemType)]).size === 1;
2046
- if (!considerationItemTypeTheSame) {
2047
- throw new Error('All consideration items must be of the same type');
2048
- }
2049
- return this.orderbookService.createOrder({
2050
- chainId: this.chainId,
2051
- requestBody: {
2052
- order_hash: orderHash,
2053
- account_address: offerer,
2054
- buy: [
2055
- {
2056
- item_type: Number(orderComponents.consideration[0].itemType) === ItemType.NATIVE
2057
- ? BuyItem.item_type.IMX
2058
- : BuyItem.item_type.ERC20,
2059
- start_amount: orderComponents.consideration[0].startAmount,
2060
- }
2061
- ],
2062
- buy_fees: orderComponents.consideration.length > 1
2063
- ? [
2064
- {
2065
- amount: orderComponents.consideration[1].startAmount,
2066
- recipient: orderComponents.consideration[1].recipient,
2067
- fee_type: Fee.fee_type.ROYALTY,
2068
- },
2069
- ]
2070
- : [],
2071
- end_time: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
2072
- protocol_data: {
2073
- order_type: CreateOrderProtocolData.order_type.FULL_OPEN,
2074
- zone_address: orderComponents.zone,
2075
- },
2076
- salt: orderComponents.salt,
2077
- sell: [{
2078
- contract_address: orderComponents.offer[0].token,
2079
- token_id: orderComponents.offer[0].identifierOrCriteria,
2080
- item_type: SellItem.item_type.ERC721,
2081
- }],
2082
- signature: orderSignature,
2083
- start_time: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
2084
- },
2085
- });
2086
- }
1764
+ async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
1765
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1766
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1767
+ return ethSigner.sendTransaction(populatedTransaction);
2087
1768
  }
2088
-
2089
- class ImmutableApiClientFactory {
2090
- chainId;
2091
- orderbookClient;
2092
- constructor(apiEndpoint, chainId) {
2093
- this.chainId = chainId;
2094
- this.orderbookClient = new OrderBookClient({
2095
- // eslint-disable-next-line @typescript-eslint/naming-convention
2096
- BASE: apiEndpoint,
1769
+ async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1770
+ await validateChain(ethSigner, config.immutableXConfig);
1771
+ const imxConfig = config.immutableXConfig;
1772
+ const assetType = await getEncodeAssetInfo('asset', 'ERC20', imxConfig, {
1773
+ token_address: token.tokenAddress,
1774
+ });
1775
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1776
+ if (!isRegistered) {
1777
+ return executeRegisterAndWithdrawERC20({
1778
+ ethSigner,
1779
+ assetType: assetType.asset_type,
1780
+ starkPublicKey,
1781
+ config,
2097
1782
  });
2098
1783
  }
2099
- create() {
2100
- return new ImmutableApiClient(this.orderbookClient.orders, this.chainId);
2101
- }
1784
+ return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
2102
1785
  }
2103
1786
 
2104
- class ERC721 {
2105
- erc721;
2106
- constructor(erc721) {
2107
- this.erc721 = erc721;
1787
+ async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1788
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1789
+ const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
1790
+ return ethSigner.sendTransaction(populatedTransaction);
1791
+ }
1792
+ async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1793
+ const etherKey = await ethSigner.getAddress();
1794
+ const usersApi = new UsersApi(config.apiConfiguration);
1795
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1796
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1797
+ const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
1798
+ return ethSigner.sendTransaction(populatedTransaction);
1799
+ }
1800
+ function getMintingBlob(token) {
1801
+ const { id } = token.data;
1802
+ const blueprint = token.data.blueprint || '';
1803
+ return encUtils.sanitizeHex(encUtils.utf8ToHex(`{${id}}:{${blueprint}}`));
1804
+ }
1805
+ async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1806
+ const imxConfig = config.immutableXConfig;
1807
+ const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', imxConfig, {
1808
+ id: token.data.id,
1809
+ token_address: token.data.tokenAddress,
1810
+ ...(token.data.blueprint && { blueprint: token.data.blueprint }),
1811
+ });
1812
+ const mintingBlob = getMintingBlob(token);
1813
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1814
+ if (!isRegistered) {
1815
+ return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
2108
1816
  }
2109
- async royaltyInfo(tokenId, salePrice) {
2110
- const [recipient, royaltyRequired] = await this.erc721.royaltyInfo(tokenId, salePrice);
2111
- return { recipient, amountRequired: royaltyRequired.toString() };
1817
+ return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
1818
+ }
1819
+ async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1820
+ const etherKey = await ethSigner.getAddress();
1821
+ const usersApi = new UsersApi(config.apiConfiguration);
1822
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1823
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1824
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
1825
+ return ethSigner.sendTransaction(populatedTransaction);
1826
+ }
1827
+ async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1828
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1829
+ const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
1830
+ return ethSigner.sendTransaction(populatedTransaction);
1831
+ }
1832
+ async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1833
+ const imxConfig = config.immutableXConfig;
1834
+ const assetType = await getEncodeAssetInfo('asset', 'ERC721', imxConfig, {
1835
+ token_id: token.tokenId,
1836
+ token_address: token.tokenAddress,
1837
+ });
1838
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1839
+ if (!isRegistered) {
1840
+ return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
2112
1841
  }
1842
+ return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
1843
+ }
1844
+ async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1845
+ await validateChain(ethSigner, config.immutableXConfig);
1846
+ const { tokenAddress } = token;
1847
+ const { tokenId } = token;
1848
+ const imxConfig = config.immutableXConfig;
1849
+ const mintsApi = new MintsApi(imxConfig.apiConfiguration);
1850
+ return await mintsApi
1851
+ .getMintableTokenDetailsByClientTokenId({
1852
+ tokenAddress,
1853
+ tokenId,
1854
+ })
1855
+ .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
1856
+ type: 'ERC721',
1857
+ data: {
1858
+ id: tokenId,
1859
+ tokenAddress,
1860
+ blueprint: mintableToken.data.blueprint,
1861
+ },
1862
+ }, config))
1863
+ .catch((error) => {
1864
+ if (error.response?.status === 404) {
1865
+ // token is already minted on L1
1866
+ return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
1867
+ }
1868
+ throw error; // unable to recover from any other kind of error
1869
+ });
2113
1870
  }
2114
1871
 
2115
- /* Autogenerated file. Do not edit manually. */
2116
- /* tslint:disable */
2117
- /* eslint-disable */
2118
- const _abi = [
2119
- {
2120
- inputs: [
2121
- {
2122
- internalType: "address",
2123
- name: "owner_",
2124
- type: "address",
2125
- },
2126
- {
2127
- internalType: "string",
2128
- name: "name_",
2129
- type: "string",
2130
- },
2131
- {
2132
- internalType: "string",
2133
- name: "symbol_",
2134
- type: "string",
2135
- },
2136
- {
2137
- internalType: "string",
2138
- name: "baseURI_",
2139
- type: "string",
2140
- },
2141
- {
2142
- internalType: "string",
2143
- name: "contractURI_",
2144
- type: "string",
2145
- },
2146
- {
2147
- internalType: "address",
2148
- name: "_receiver",
2149
- type: "address",
2150
- },
2151
- {
2152
- internalType: "uint96",
2153
- name: "_feeNumerator",
2154
- type: "uint96",
2155
- },
2156
- ],
2157
- stateMutability: "nonpayable",
2158
- type: "constructor",
2159
- },
2160
- {
2161
- inputs: [
2162
- {
2163
- internalType: "address",
2164
- name: "target",
2165
- type: "address",
2166
- },
2167
- ],
2168
- name: "ApproveTargetNotInAllowlist",
2169
- type: "error",
2170
- },
2171
- {
2172
- inputs: [
2173
- {
2174
- internalType: "address",
2175
- name: "caller",
2176
- type: "address",
2177
- },
2178
- ],
2179
- name: "CallerNotInAllowlist",
2180
- type: "error",
2181
- },
2182
- {
2183
- anonymous: false,
2184
- inputs: [
2185
- {
2186
- indexed: true,
2187
- internalType: "address",
2188
- name: "owner",
2189
- type: "address",
2190
- },
2191
- {
2192
- indexed: true,
2193
- internalType: "address",
2194
- name: "approved",
2195
- type: "address",
2196
- },
2197
- {
2198
- indexed: true,
2199
- internalType: "uint256",
2200
- name: "tokenId",
2201
- type: "uint256",
2202
- },
2203
- ],
2204
- name: "Approval",
2205
- type: "event",
2206
- },
2207
- {
2208
- anonymous: false,
2209
- inputs: [
2210
- {
2211
- indexed: true,
2212
- internalType: "address",
2213
- name: "owner",
2214
- type: "address",
2215
- },
2216
- {
2217
- indexed: true,
2218
- internalType: "address",
2219
- name: "operator",
2220
- type: "address",
2221
- },
2222
- {
2223
- indexed: false,
2224
- internalType: "bool",
2225
- name: "approved",
2226
- type: "bool",
2227
- },
2228
- ],
2229
- name: "ApprovalForAll",
2230
- type: "event",
2231
- },
2232
- {
2233
- anonymous: false,
2234
- inputs: [
2235
- {
2236
- indexed: true,
2237
- internalType: "bytes32",
2238
- name: "role",
2239
- type: "bytes32",
2240
- },
2241
- {
2242
- indexed: true,
2243
- internalType: "bytes32",
2244
- name: "previousAdminRole",
2245
- type: "bytes32",
2246
- },
2247
- {
2248
- indexed: true,
2249
- internalType: "bytes32",
2250
- name: "newAdminRole",
2251
- type: "bytes32",
2252
- },
2253
- ],
2254
- name: "RoleAdminChanged",
2255
- type: "event",
2256
- },
2257
- {
2258
- anonymous: false,
2259
- inputs: [
2260
- {
2261
- indexed: true,
2262
- internalType: "bytes32",
2263
- name: "role",
2264
- type: "bytes32",
2265
- },
2266
- {
2267
- indexed: true,
2268
- internalType: "address",
2269
- name: "account",
2270
- type: "address",
2271
- },
2272
- {
2273
- indexed: true,
2274
- internalType: "address",
2275
- name: "sender",
2276
- type: "address",
2277
- },
2278
- ],
2279
- name: "RoleGranted",
2280
- type: "event",
2281
- },
2282
- {
2283
- anonymous: false,
2284
- inputs: [
2285
- {
2286
- indexed: true,
2287
- internalType: "bytes32",
2288
- name: "role",
2289
- type: "bytes32",
2290
- },
2291
- {
2292
- indexed: true,
2293
- internalType: "address",
2294
- name: "account",
2295
- type: "address",
2296
- },
2297
- {
2298
- indexed: true,
2299
- internalType: "address",
2300
- name: "sender",
2301
- type: "address",
2302
- },
2303
- ],
2304
- name: "RoleRevoked",
2305
- type: "event",
2306
- },
2307
- {
2308
- anonymous: false,
2309
- inputs: [
2310
- {
2311
- indexed: false,
2312
- internalType: "address",
2313
- name: "oldRegistry",
2314
- type: "address",
2315
- },
2316
- {
2317
- indexed: false,
2318
- internalType: "address",
2319
- name: "newRegistry",
2320
- type: "address",
2321
- },
2322
- ],
2323
- name: "RoyaltytAllowlistRegistryUpdated",
2324
- type: "event",
2325
- },
2326
- {
2327
- anonymous: false,
2328
- inputs: [
2329
- {
2330
- indexed: true,
2331
- internalType: "address",
2332
- name: "from",
2333
- type: "address",
2334
- },
2335
- {
2336
- indexed: true,
2337
- internalType: "address",
2338
- name: "to",
2339
- type: "address",
2340
- },
2341
- {
2342
- indexed: true,
2343
- internalType: "uint256",
2344
- name: "tokenId",
2345
- type: "uint256",
2346
- },
2347
- ],
2348
- name: "Transfer",
2349
- type: "event",
2350
- },
2351
- {
2352
- inputs: [],
2353
- name: "DEFAULT_ADMIN_ROLE",
2354
- outputs: [
2355
- {
2356
- internalType: "bytes32",
2357
- name: "",
2358
- type: "bytes32",
2359
- },
2360
- ],
2361
- stateMutability: "view",
2362
- type: "function",
2363
- },
2364
- {
2365
- inputs: [],
2366
- name: "MINTER_ROLE",
2367
- outputs: [
2368
- {
2369
- internalType: "bytes32",
2370
- name: "",
2371
- type: "bytes32",
2372
- },
2373
- ],
2374
- stateMutability: "view",
2375
- type: "function",
2376
- },
2377
- {
2378
- inputs: [
2379
- {
2380
- internalType: "address",
2381
- name: "to",
2382
- type: "address",
2383
- },
2384
- {
2385
- internalType: "uint256",
2386
- name: "tokenId",
2387
- type: "uint256",
2388
- },
2389
- ],
2390
- name: "approve",
2391
- outputs: [],
2392
- stateMutability: "nonpayable",
2393
- type: "function",
2394
- },
2395
- {
2396
- inputs: [
2397
- {
2398
- internalType: "address",
2399
- name: "owner",
2400
- type: "address",
2401
- },
2402
- ],
2403
- name: "balanceOf",
2404
- outputs: [
2405
- {
2406
- internalType: "uint256",
2407
- name: "",
2408
- type: "uint256",
2409
- },
2410
- ],
2411
- stateMutability: "view",
2412
- type: "function",
2413
- },
2414
- {
2415
- inputs: [],
2416
- name: "baseURI",
2417
- outputs: [
2418
- {
2419
- internalType: "string",
2420
- name: "",
2421
- type: "string",
2422
- },
2423
- ],
2424
- stateMutability: "view",
2425
- type: "function",
2426
- },
2427
- {
2428
- inputs: [
2429
- {
2430
- internalType: "uint256",
2431
- name: "tokenId",
2432
- type: "uint256",
2433
- },
2434
- ],
2435
- name: "burn",
2436
- outputs: [],
2437
- stateMutability: "nonpayable",
2438
- type: "function",
2439
- },
2440
- {
2441
- inputs: [],
2442
- name: "contractURI",
2443
- outputs: [
2444
- {
2445
- internalType: "string",
2446
- name: "",
2447
- type: "string",
2448
- },
2449
- ],
2450
- stateMutability: "view",
2451
- type: "function",
2452
- },
2453
- {
2454
- inputs: [],
2455
- name: "getAdmins",
2456
- outputs: [
2457
- {
2458
- internalType: "address[]",
2459
- name: "",
2460
- type: "address[]",
2461
- },
2462
- ],
2463
- stateMutability: "view",
2464
- type: "function",
2465
- },
2466
- {
2467
- inputs: [
2468
- {
2469
- internalType: "uint256",
2470
- name: "tokenId",
2471
- type: "uint256",
2472
- },
2473
- ],
2474
- name: "getApproved",
2475
- outputs: [
2476
- {
2477
- internalType: "address",
2478
- name: "",
2479
- type: "address",
2480
- },
2481
- ],
2482
- stateMutability: "view",
2483
- type: "function",
2484
- },
2485
- {
2486
- inputs: [
2487
- {
2488
- internalType: "bytes32",
2489
- name: "role",
2490
- type: "bytes32",
2491
- },
2492
- ],
2493
- name: "getRoleAdmin",
2494
- outputs: [
2495
- {
2496
- internalType: "bytes32",
2497
- name: "",
2498
- type: "bytes32",
2499
- },
2500
- ],
2501
- stateMutability: "view",
2502
- type: "function",
2503
- },
2504
- {
2505
- inputs: [
2506
- {
2507
- internalType: "bytes32",
2508
- name: "role",
2509
- type: "bytes32",
2510
- },
2511
- {
2512
- internalType: "uint256",
2513
- name: "index",
2514
- type: "uint256",
2515
- },
2516
- ],
2517
- name: "getRoleMember",
2518
- outputs: [
2519
- {
2520
- internalType: "address",
2521
- name: "",
2522
- type: "address",
2523
- },
2524
- ],
2525
- stateMutability: "view",
2526
- type: "function",
2527
- },
2528
- {
2529
- inputs: [
2530
- {
2531
- internalType: "bytes32",
2532
- name: "role",
2533
- type: "bytes32",
2534
- },
2535
- ],
2536
- name: "getRoleMemberCount",
2537
- outputs: [
2538
- {
2539
- internalType: "uint256",
2540
- name: "",
2541
- type: "uint256",
2542
- },
2543
- ],
2544
- stateMutability: "view",
2545
- type: "function",
2546
- },
2547
- {
2548
- inputs: [
2549
- {
2550
- internalType: "address",
2551
- name: "user",
2552
- type: "address",
2553
- },
2554
- ],
2555
- name: "grantMinterRole",
2556
- outputs: [],
2557
- stateMutability: "nonpayable",
2558
- type: "function",
2559
- },
2560
- {
2561
- inputs: [
2562
- {
2563
- internalType: "bytes32",
2564
- name: "role",
2565
- type: "bytes32",
2566
- },
2567
- {
2568
- internalType: "address",
2569
- name: "account",
2570
- type: "address",
2571
- },
2572
- ],
2573
- name: "grantRole",
2574
- outputs: [],
2575
- stateMutability: "nonpayable",
2576
- type: "function",
2577
- },
2578
- {
2579
- inputs: [
2580
- {
2581
- internalType: "bytes32",
2582
- name: "role",
2583
- type: "bytes32",
2584
- },
2585
- {
2586
- internalType: "address",
2587
- name: "account",
2588
- type: "address",
2589
- },
2590
- ],
2591
- name: "hasRole",
2592
- outputs: [
2593
- {
2594
- internalType: "bool",
2595
- name: "",
2596
- type: "bool",
2597
- },
2598
- ],
2599
- stateMutability: "view",
2600
- type: "function",
2601
- },
2602
- {
2603
- inputs: [
2604
- {
2605
- internalType: "address",
2606
- name: "owner",
2607
- type: "address",
2608
- },
2609
- {
2610
- internalType: "address",
2611
- name: "operator",
2612
- type: "address",
2613
- },
2614
- ],
2615
- name: "isApprovedForAll",
2616
- outputs: [
2617
- {
2618
- internalType: "bool",
2619
- name: "",
2620
- type: "bool",
2621
- },
2622
- ],
2623
- stateMutability: "view",
2624
- type: "function",
2625
- },
2626
- {
2627
- inputs: [
2628
- {
2629
- internalType: "address",
2630
- name: "to",
2631
- type: "address",
2632
- },
2633
- {
2634
- internalType: "uint256",
2635
- name: "amount",
2636
- type: "uint256",
2637
- },
2638
- ],
2639
- name: "mint",
2640
- outputs: [],
2641
- stateMutability: "nonpayable",
2642
- type: "function",
2643
- },
2644
- {
2645
- inputs: [],
2646
- name: "name",
2647
- outputs: [
2648
- {
2649
- internalType: "string",
2650
- name: "",
2651
- type: "string",
2652
- },
2653
- ],
2654
- stateMutability: "view",
2655
- type: "function",
2656
- },
2657
- {
2658
- inputs: [
2659
- {
2660
- internalType: "uint256",
2661
- name: "tokenId",
2662
- type: "uint256",
2663
- },
2664
- ],
2665
- name: "ownerOf",
2666
- outputs: [
2667
- {
2668
- internalType: "address",
2669
- name: "",
2670
- type: "address",
2671
- },
2672
- ],
2673
- stateMutability: "view",
2674
- type: "function",
2675
- },
2676
- {
2677
- inputs: [
2678
- {
2679
- internalType: "bytes32",
2680
- name: "role",
2681
- type: "bytes32",
2682
- },
2683
- {
2684
- internalType: "address",
2685
- name: "account",
2686
- type: "address",
2687
- },
2688
- ],
2689
- name: "renounceRole",
2690
- outputs: [],
2691
- stateMutability: "nonpayable",
2692
- type: "function",
2693
- },
2694
- {
2695
- inputs: [
2696
- {
2697
- internalType: "address",
2698
- name: "user",
2699
- type: "address",
2700
- },
2701
- ],
2702
- name: "revokeMinterRole",
2703
- outputs: [],
2704
- stateMutability: "nonpayable",
2705
- type: "function",
2706
- },
2707
- {
2708
- inputs: [
2709
- {
2710
- internalType: "bytes32",
2711
- name: "role",
2712
- type: "bytes32",
2713
- },
2714
- {
2715
- internalType: "address",
2716
- name: "account",
2717
- type: "address",
2718
- },
2719
- ],
2720
- name: "revokeRole",
2721
- outputs: [],
2722
- stateMutability: "nonpayable",
2723
- type: "function",
2724
- },
2725
- {
2726
- inputs: [],
2727
- name: "royaltyAllowlist",
2728
- outputs: [
2729
- {
2730
- internalType: "contract IRoyaltyAllowlist",
2731
- name: "",
2732
- type: "address",
2733
- },
2734
- ],
2735
- stateMutability: "view",
2736
- type: "function",
2737
- },
2738
- {
2739
- inputs: [
2740
- {
2741
- internalType: "uint256",
2742
- name: "_tokenId",
2743
- type: "uint256",
2744
- },
2745
- {
2746
- internalType: "uint256",
2747
- name: "_salePrice",
2748
- type: "uint256",
2749
- },
2750
- ],
2751
- name: "royaltyInfo",
2752
- outputs: [
2753
- {
2754
- internalType: "address",
2755
- name: "",
2756
- type: "address",
2757
- },
2758
- {
2759
- internalType: "uint256",
2760
- name: "",
2761
- type: "uint256",
2762
- },
2763
- ],
2764
- stateMutability: "view",
2765
- type: "function",
2766
- },
2767
- {
2768
- inputs: [
2769
- {
2770
- internalType: "address",
2771
- name: "from",
2772
- type: "address",
2773
- },
2774
- {
2775
- internalType: "address",
2776
- name: "to",
2777
- type: "address",
2778
- },
2779
- {
2780
- internalType: "uint256",
2781
- name: "tokenId",
2782
- type: "uint256",
2783
- },
2784
- ],
2785
- name: "safeTransferFrom",
2786
- outputs: [],
2787
- stateMutability: "nonpayable",
2788
- type: "function",
2789
- },
2790
- {
2791
- inputs: [
2792
- {
2793
- internalType: "address",
2794
- name: "from",
2795
- type: "address",
2796
- },
2797
- {
2798
- internalType: "address",
2799
- name: "to",
2800
- type: "address",
2801
- },
2802
- {
2803
- internalType: "uint256",
2804
- name: "tokenId",
2805
- type: "uint256",
2806
- },
2807
- {
2808
- internalType: "bytes",
2809
- name: "data",
2810
- type: "bytes",
2811
- },
2812
- ],
2813
- name: "safeTransferFrom",
2814
- outputs: [],
2815
- stateMutability: "nonpayable",
2816
- type: "function",
2817
- },
2818
- {
2819
- inputs: [
2820
- {
2821
- internalType: "address",
2822
- name: "operator",
2823
- type: "address",
2824
- },
2825
- {
2826
- internalType: "bool",
2827
- name: "approved",
2828
- type: "bool",
2829
- },
2830
- ],
2831
- name: "setApprovalForAll",
2832
- outputs: [],
2833
- stateMutability: "nonpayable",
2834
- type: "function",
2835
- },
2836
- {
2837
- inputs: [
2838
- {
2839
- internalType: "string",
2840
- name: "baseURI_",
2841
- type: "string",
2842
- },
2843
- ],
2844
- name: "setBaseURI",
2845
- outputs: [],
2846
- stateMutability: "nonpayable",
2847
- type: "function",
2848
- },
2849
- {
2850
- inputs: [
2851
- {
2852
- internalType: "string",
2853
- name: "_contractURI",
2854
- type: "string",
2855
- },
2856
- ],
2857
- name: "setContractURI",
2858
- outputs: [],
2859
- stateMutability: "nonpayable",
2860
- type: "function",
2861
- },
2862
- {
2863
- inputs: [
2864
- {
2865
- internalType: "address",
2866
- name: "_royaltyAllowlist",
2867
- type: "address",
2868
- },
2869
- ],
2870
- name: "setRoyaltyAllowlistRegistry",
2871
- outputs: [],
2872
- stateMutability: "nonpayable",
2873
- type: "function",
2874
- },
2875
- {
2876
- inputs: [
2877
- {
2878
- internalType: "bytes4",
2879
- name: "interfaceId",
2880
- type: "bytes4",
2881
- },
2882
- ],
2883
- name: "supportsInterface",
2884
- outputs: [
2885
- {
2886
- internalType: "bool",
2887
- name: "",
2888
- type: "bool",
2889
- },
2890
- ],
2891
- stateMutability: "view",
2892
- type: "function",
2893
- },
2894
- {
2895
- inputs: [],
2896
- name: "symbol",
2897
- outputs: [
2898
- {
2899
- internalType: "string",
2900
- name: "",
2901
- type: "string",
2902
- },
2903
- ],
2904
- stateMutability: "view",
2905
- type: "function",
2906
- },
2907
- {
2908
- inputs: [
2909
- {
2910
- internalType: "uint256",
2911
- name: "index",
2912
- type: "uint256",
2913
- },
2914
- ],
2915
- name: "tokenByIndex",
2916
- outputs: [
2917
- {
2918
- internalType: "uint256",
2919
- name: "",
2920
- type: "uint256",
2921
- },
2922
- ],
2923
- stateMutability: "view",
2924
- type: "function",
2925
- },
2926
- {
2927
- inputs: [
2928
- {
2929
- internalType: "address",
2930
- name: "owner",
2931
- type: "address",
2932
- },
2933
- {
2934
- internalType: "uint256",
2935
- name: "index",
2936
- type: "uint256",
2937
- },
2938
- ],
2939
- name: "tokenOfOwnerByIndex",
2940
- outputs: [
2941
- {
2942
- internalType: "uint256",
2943
- name: "",
2944
- type: "uint256",
2945
- },
2946
- ],
2947
- stateMutability: "view",
2948
- type: "function",
2949
- },
2950
- {
2951
- inputs: [
2952
- {
2953
- internalType: "uint256",
2954
- name: "tokenId",
2955
- type: "uint256",
2956
- },
2957
- ],
2958
- name: "tokenURI",
2959
- outputs: [
2960
- {
2961
- internalType: "string",
2962
- name: "",
2963
- type: "string",
2964
- },
2965
- ],
2966
- stateMutability: "view",
2967
- type: "function",
2968
- },
2969
- {
2970
- inputs: [],
2971
- name: "totalSupply",
2972
- outputs: [
2973
- {
2974
- internalType: "uint256",
2975
- name: "",
2976
- type: "uint256",
2977
- },
2978
- ],
2979
- stateMutability: "view",
2980
- type: "function",
2981
- },
2982
- {
2983
- inputs: [
2984
- {
2985
- internalType: "address",
2986
- name: "from",
2987
- type: "address",
2988
- },
2989
- {
2990
- internalType: "address",
2991
- name: "to",
2992
- type: "address",
2993
- },
2994
- {
2995
- internalType: "uint256",
2996
- name: "tokenId",
2997
- type: "uint256",
2998
- },
2999
- ],
3000
- name: "transferFrom",
3001
- outputs: [],
3002
- stateMutability: "nonpayable",
3003
- type: "function",
3004
- },
3005
- ];
3006
- class ImmutableERC721Base__factory {
3007
- static abi = _abi;
3008
- static createInterface() {
3009
- return new utils.Interface(_abi);
3010
- }
3011
- static connect(address, signerOrProvider) {
3012
- return new Contract(address, _abi, signerOrProvider);
3013
- }
3014
- }
3015
-
3016
- class ERC721Factory {
3017
- erc721;
3018
- constructor(contractAddress, provider) {
3019
- this.erc721 = ImmutableERC721Base__factory.connect(contractAddress, provider);
3020
- }
3021
- create() {
3022
- return new ERC721(this.erc721);
3023
- }
3024
- }
3025
-
3026
- function getOrderComponentsFromMessage(orderMessage) {
3027
- const data = JSON.parse(orderMessage);
3028
- const orderComponents = data.message;
3029
- orderComponents.salt = BigNumber.from(orderComponents.salt).toHexString();
3030
- return orderComponents;
3031
- }
3032
-
3033
- // Add 20% more gas than estimate to prevent out of gas errors
3034
- // This can always be overwritten by the user signing the transaction
3035
- async function prepareTransaction(transactionMethods) {
3036
- const transaction = await transactionMethods.buildTransaction();
3037
- transaction.gasLimit = await transactionMethods.estimateGas();
3038
- transaction.gasLimit = transaction.gasLimit
3039
- .add(transaction.gasLimit.div(5));
3040
- return transaction;
3041
- }
3042
-
3043
- function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
3044
- const considerationItems = order.buy.map((buyItem) => ({
3045
- startAmount: buyItem.start_amount,
3046
- endAmount: buyItem.start_amount,
3047
- itemType: buyItem.item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
3048
- recipient: order.account_address,
3049
- token: buyItem.contract_address || constants.AddressZero,
3050
- identifierOrCriteria: '0',
3051
- }));
3052
- const fees = order.buy_fees.map((fee) => ({
3053
- startAmount: fee.amount,
3054
- endAmount: fee.amount,
3055
- itemType: order.buy[0].item_type === 'ERC20' ? ItemType.ERC20 : ItemType.NATIVE,
3056
- recipient: fee.recipient,
3057
- token: order.buy[0].contract_address || constants.AddressZero,
3058
- identifierOrCriteria: '0',
3059
- }));
3060
- return {
3061
- conduitKey: constants.HashZero,
3062
- consideration: [...considerationItems, ...fees],
3063
- offer: order.sell.map((sellItem) => ({
3064
- startAmount: '1',
3065
- endAmount: '1',
3066
- itemType: ItemType.ERC721,
3067
- token: sellItem.contract_address,
3068
- identifierOrCriteria: sellItem.token_id,
3069
- })),
3070
- counter,
3071
- endTime: Math.round(new Date(order.end_time).getTime() / 1000).toString(),
3072
- startTime: Math.round(new Date(order.start_time).getTime() / 1000).toString(),
3073
- salt: order.salt,
3074
- offerer: order.account_address,
3075
- zone: zoneAddress,
3076
- totalOriginalConsiderationItems: 2,
3077
- orderType: OrderType.FULL_RESTRICTED,
3078
- zoneHash: constants.HashZero,
3079
- };
3080
- }
3081
-
3082
- class Seaport {
3083
- seaport;
3084
- provider;
3085
- seaportContractAddress;
3086
- zoneContractAddress;
3087
- constructor(seaport, provider, seaportContractAddress, zoneContractAddress) {
3088
- this.seaport = seaport;
3089
- this.provider = provider;
3090
- this.seaportContractAddress = seaportContractAddress;
3091
- this.zoneContractAddress = zoneContractAddress;
3092
- }
3093
- async prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
3094
- const { actions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry);
3095
- let approvalTransaction;
3096
- const approvalAction = actions
3097
- .find((action) => action.type === 'approval');
3098
- if (approvalAction) {
3099
- approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
3100
- }
3101
- const createAction = actions
3102
- .find((action) => action.type === 'create');
3103
- if (!createAction) {
3104
- throw new Error('No create order action found');
3105
- }
3106
- const orderMessageToSign = await createAction.getMessageToSign();
3107
- const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
3108
- return {
3109
- unsignedApprovalTransaction: approvalTransaction,
3110
- typedOrderMessageForSigning: await this.getTypedDataFromOrderComponents(orderComponents),
3111
- orderComponents,
3112
- orderHash: await this.seaport.getOrderHash(orderComponents),
3113
- };
3114
- }
3115
- async fulfilOrder(order, account) {
3116
- const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
3117
- const { actions } = await this.seaport.fulfillOrders({
3118
- accountAddress: account,
3119
- fulfillOrderDetails: [{
3120
- order: {
3121
- parameters: orderComponents,
3122
- signature: order.signature,
3123
- },
3124
- }],
3125
- });
3126
- let approvalTransaction;
3127
- const approvalAction = actions
3128
- .find((action) => action.type === 'approval');
3129
- if (approvalAction) {
3130
- approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
3131
- }
3132
- const fulfillmentAction = actions
3133
- .find((action) => action.type === 'exchange');
3134
- if (!fulfillmentAction) {
3135
- throw new Error('No exchange action found');
3136
- }
3137
- const fulfillmentTransaction = await prepareTransaction(fulfillmentAction.transactionMethods);
3138
- return {
3139
- unsignedApprovalTransaction: approvalTransaction,
3140
- unsignedFulfillmentTransaction: fulfillmentTransaction,
3141
- };
3142
- }
3143
- async cancelOrder(order, account) {
3144
- const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
3145
- const cancellationTransaction = await this.seaport.cancelOrders([orderComponents], account);
3146
- return prepareTransaction(cancellationTransaction);
3147
- }
3148
- async mapImmutableOrderToSeaportOrderComponents(order) {
3149
- const counterForOfferer = await this.seaport.getCounter(order.account_address);
3150
- return mapImmutableOrderToSeaportOrderComponents(order, counterForOfferer.toString(), this.zoneContractAddress);
3151
- }
3152
- createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
3153
- return this.seaport.createOrder({
3154
- allowPartialFills: false,
3155
- offer: [
3156
- {
3157
- itemType: ItemType.ERC721,
3158
- token: listingItem.contractAddress,
3159
- identifier: listingItem.tokenId,
3160
- },
3161
- ],
3162
- consideration: [
3163
- {
3164
- token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
3165
- amount: considerationItem.amount,
3166
- recipient: offerer,
3167
- },
3168
- {
3169
- token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
3170
- amount: royaltyInfo.amountRequired,
3171
- recipient: royaltyInfo.recipient,
3172
- },
3173
- ],
3174
- startTime: (orderStart.getTime() / 1000).toFixed(0),
3175
- endTime: (orderExpiry.getTime() / 1000).toFixed(0),
3176
- zone: this.zoneContractAddress,
3177
- restrictedByZone: true,
3178
- }, offerer);
3179
- }
3180
- async getTypedDataFromOrderComponents(orderComponents) {
3181
- const { chainId } = await this.provider.getNetwork();
3182
- const domainData = {
3183
- name: SEAPORT_CONTRACT_NAME,
3184
- version: SEAPORT_CONTRACT_VERSION_V1_4,
3185
- chainId,
3186
- verifyingContract: this.seaportContractAddress,
3187
- };
3188
- return {
3189
- domain: domainData,
3190
- types: EIP_712_ORDER_TYPE,
3191
- value: orderComponents,
3192
- };
3193
- }
1872
+ async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1873
+ const etherKey = await ethSigner.getAddress();
1874
+ const usersApi = new UsersApi(config.apiConfiguration);
1875
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1876
+ const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1877
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1878
+ return ethSigner.sendTransaction(populatedTransaction);
3194
1879
  }
3195
-
3196
- class SeaportFactory {
3197
- seaportContractAddress;
3198
- zoneContractAddress;
3199
- provider;
3200
- seaport;
3201
- constructor(seaportContractAddress, zoneContractAddress, provider) {
3202
- this.seaportContractAddress = seaportContractAddress;
3203
- this.zoneContractAddress = zoneContractAddress;
3204
- this.provider = provider;
3205
- this.seaport = new Seaport$1(provider, {
3206
- seaportVersion: '1.4',
3207
- balanceAndApprovalChecksOnOrderCreation: true,
3208
- overrides: {
3209
- contractAddress: seaportContractAddress,
3210
- },
3211
- });
3212
- }
3213
- create() {
3214
- return new Seaport(this.seaport, this.provider, this.seaportContractAddress, this.zoneContractAddress);
3215
- }
1880
+ async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1881
+ const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1882
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1883
+ return ethSigner.sendTransaction(populatedTransaction);
3216
1884
  }
3217
-
3218
- /**
3219
- * zkEVM orderbook SDK
3220
- * @constructor
3221
- * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
3222
- */
3223
- class Orderbook {
3224
- config;
3225
- apiClient;
3226
- seaport;
3227
- constructor(config) {
3228
- this.config = config;
3229
- // TODO: Move endpoint lookup to a map based on env. Just using override to get dev started
3230
- const apiEndpoint = config.overrides?.apiEndpoint;
3231
- if (!apiEndpoint) {
3232
- throw new Error('API endpoint must be provided as an override');
3233
- }
3234
- // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
3235
- const chainId = config.overrides?.chainId;
3236
- if (!chainId) {
3237
- throw new Error('ChainID must be provided as an override');
3238
- }
3239
- this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainId).create();
3240
- this.seaport = new SeaportFactory(this.config.seaportContractAddress, this.config.zoneContractAddress, this.config.provider).create();
3241
- }
3242
- /**
3243
- * Get an order by ID
3244
- * @param {string} orderId - The orderId to find.
3245
- * @return {Order} The returned order.
3246
- */
3247
- getOrder(orderId) {
3248
- return this.apiClient.getOrder(orderId);
3249
- }
3250
- /**
3251
- * Get required transactions and messages for signing prior to creating a listing
3252
- * through the createOrder method
3253
- * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
3254
- * @return {PrepareListingResponse} PrepareListingResponse includes
3255
- * the unsigned approval transaction, the typed order message for signing and
3256
- * the order components that can be submitted to `createOrder` with a signature.
3257
- */
3258
- async prepareListing({ offerer, listingItem, considerationItem, orderExpiry, }) {
3259
- const erc721 = new ERC721Factory(listingItem.contractAddress, this.config.provider).create();
3260
- const royaltyInfo = await erc721.royaltyInfo(listingItem.tokenId, considerationItem.amount);
3261
- return this.seaport.prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo,
3262
- // Default order start to now
3263
- new Date(),
3264
- // Default order expiry to 2 years from now
3265
- orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
3266
- }
3267
- /**
3268
- * Create an order
3269
- * @param {CreateOrderParams} createOrderParams - create an order with the given params.
3270
- * @return {Order} The order created in the Immutable services.
3271
- */
3272
- createOrder(createOrderParams) {
3273
- return this.apiClient.createOrder(createOrderParams);
3274
- }
3275
- /**
3276
- * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
3277
- * transaction exists it must be signed and submitted to the chain before the fulfilment
3278
- * transaction can be submitted or it will be reverted.
3279
- * @param {string} orderId - The orderId to fulfil.
3280
- * @param {string} fulfillerAddress - The address of the account fulfilling the order.
3281
- * @return {FulfilOrderResponse} Approval and fulfilment transactions.
3282
- */
3283
- async fulfillOrder(orderId, fulfillerAddress) {
3284
- const order = await this.apiClient.getOrder(orderId);
3285
- if (order.status !== Order.status.ACTIVE) {
3286
- throw new Error(`Cannot fulfil order that is not active. Current status: ${order.status}`);
3287
- }
3288
- return this.seaport.fulfilOrder(order, fulfillerAddress);
3289
- }
3290
- /**
3291
- * Get an unsigned cancel order transaction. Orders can only be cancelled by
3292
- * the account that created them.
3293
- * @param {string} orderId - The orderId to cancel.
3294
- * @param {string} accountAddress - The address of the account cancelling the order.
3295
- * @return {CancelOrderResponse} The unsigned cancel order transaction
3296
- */
3297
- async cancelOrder(orderId, accountAddress) {
3298
- const order = await this.apiClient.getOrder(orderId);
3299
- if (order.status !== Order.status.ACTIVE
3300
- && order.status !== Order.status.INACTIVE
3301
- && order.status !== Order.status.PENDING) {
3302
- throw new Error(`Cannot cancel order with status ${order.status}`);
3303
- }
3304
- if (order.account_address !== accountAddress.toLowerCase()) {
3305
- throw new Error(`Only account ${order.account_address} can cancel order ${orderId}`);
3306
- }
3307
- const cancelOrderTransaction = await this.seaport.cancelOrder(order, accountAddress);
3308
- return { unsignedCancelOrderTransaction: cancelOrderTransaction };
1885
+ async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
1886
+ await validateChain(ethSigner, config.immutableXConfig);
1887
+ const imxConfig = config.immutableXConfig;
1888
+ const assetType = await getEncodeAssetInfo('asset', 'ETH', imxConfig);
1889
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1890
+ if (!isRegistered) {
1891
+ return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3309
1892
  }
1893
+ return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3310
1894
  }
3311
1895
 
3312
- const module = 'orderbook';
3313
-
3314
- function isChainValid(chainID, config) {
3315
- return chainID === config.ethConfiguration.chainID;
1896
+ async function prepareWithdrawal({ signers, withdrawal, config, }) {
1897
+ return prepareWithdrawalAction({
1898
+ signers,
1899
+ config: config.immutableXConfig,
1900
+ ...withdrawal,
1901
+ });
3316
1902
  }
3317
- async function validateChain(signer, config) {
3318
- const chainID = await signer.getChainId();
3319
- if (!isChainValid(chainID, config)) {
3320
- throw new Error('The wallet used for this operation is not connected to the correct network.');
1903
+ // TODO: remove once fixed
1904
+ // eslint-disable-next-line consistent-return
1905
+ async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
1906
+ // TODO: please add a reasonable default here
1907
+ // eslint-disable-next-line default-case
1908
+ switch (token.type) {
1909
+ case 'ETH':
1910
+ return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
1911
+ case 'ERC20':
1912
+ return completeERC20WithdrawalAction({
1913
+ ethSigner,
1914
+ starkPublicKey,
1915
+ token,
1916
+ config,
1917
+ });
1918
+ case 'ERC721':
1919
+ return completeERC721WithdrawalAction({
1920
+ ethSigner,
1921
+ starkPublicKey,
1922
+ token,
1923
+ config,
1924
+ });
3321
1925
  }
3322
1926
  }
3323
1927
 
3324
- async function transfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1928
+ async function createTrade({ signers: { ethSigner, starkSigner }, request, config, }) {
3325
1929
  await validateChain(ethSigner, config.immutableXConfig);
3326
1930
  const ethAddress = await ethSigner.getAddress();
3327
- const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
3328
- const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
3329
- const signableResult = await transfersApi.getSignableTransferV1({
3330
- getSignableTransferRequest: {
3331
- sender: ethAddress,
3332
- token: convertToSignableToken(request),
3333
- amount: transferAmount,
3334
- receiver: request.receiver,
1931
+ const tradesApi = new TradesApi(config.immutableXConfig.apiConfiguration);
1932
+ const signableResult = await tradesApi.getSignableTrade({
1933
+ getSignableTradeRequest: {
1934
+ user: ethAddress,
1935
+ order_id: request.order_id,
1936
+ fees: request.fees,
3335
1937
  },
3336
1938
  });
3337
1939
  const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3338
1940
  const ethSignature = await signRaw(signableMessage, ethSigner);
3339
1941
  const starkSignature = await starkSigner.signMessage(payloadHash);
3340
- const transferSigningParams = {
3341
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3342
- sender_stark_key: signableResult.data.sender_stark_key,
3343
- sender_vault_id: signableResult.data.sender_vault_id,
3344
- receiver_stark_key: signableResult.data.receiver_stark_key,
3345
- receiver_vault_id: signableResult.data.receiver_vault_id,
3346
- asset_id: signableResult.data.asset_id,
3347
- amount: signableResult.data.amount,
3348
- nonce: signableResult.data.nonce,
3349
- expiration_timestamp: signableResult.data.expiration_timestamp,
3350
- stark_signature: starkSignature,
3351
- };
3352
- const response = await transfersApi.createTransferV1({
3353
- createTransferRequest: transferSigningParams,
1942
+ const createTradeResponse = await tradesApi.createTrade({
1943
+ createTradeRequest: {
1944
+ amount_buy: signableResult.data.amount_buy,
1945
+ amount_sell: signableResult.data.amount_sell,
1946
+ asset_id_buy: signableResult.data.asset_id_buy,
1947
+ asset_id_sell: signableResult.data.asset_id_sell,
1948
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1949
+ fee_info: signableResult.data.fee_info,
1950
+ fees: request.fees,
1951
+ include_fees: true,
1952
+ nonce: signableResult.data.nonce,
1953
+ order_id: request.order_id,
1954
+ stark_key: signableResult.data.stark_key,
1955
+ vault_id_buy: signableResult.data.vault_id_buy,
1956
+ vault_id_sell: signableResult.data.vault_id_sell,
1957
+ stark_signature: starkSignature,
1958
+ },
3354
1959
  xImxEthAddress: ethAddress,
3355
1960
  xImxEthSignature: ethSignature,
3356
1961
  });
3357
- return {
3358
- sent_signature: response?.data.sent_signature,
3359
- status: response?.data.status?.toString(),
3360
- time: response?.data.time,
3361
- transfer_id: response?.data.transfer_id,
3362
- };
1962
+ return createTradeResponse.data;
3363
1963
  }
3364
- async function batchTransfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1964
+
1965
+ async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
1966
+ const etherKey = await ethSigner.getAddress();
1967
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1968
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1969
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
1970
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1971
+ }
1972
+ async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
1973
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1974
+ const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
1975
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
1976
+ }
1977
+ async function depositEth({ signers: { ethSigner }, deposit, config, }) {
3365
1978
  await validateChain(ethSigner, config.immutableXConfig);
3366
- const ethAddress = await ethSigner.getAddress();
3367
- const transfersApi = new TransfersApi(config.immutableXConfig.apiConfiguration);
3368
- const signableRequests = request.map((nftTransfer) => ({
3369
- amount: '1',
3370
- token: convertToSignableToken({
3371
- type: 'ERC721',
3372
- tokenId: nftTransfer.tokenId,
3373
- tokenAddress: nftTransfer.tokenAddress,
3374
- }),
3375
- receiver: nftTransfer.receiver,
3376
- }));
3377
- const signableResult = await transfersApi.getSignableTransfer({
3378
- getSignableTransferRequestV2: {
3379
- sender_ether_key: ethAddress,
3380
- signable_requests: signableRequests,
1979
+ const user = await ethSigner.getAddress();
1980
+ const data = {
1981
+ decimals: 18,
1982
+ };
1983
+ const amount = parseUnits(deposit.amount, 'wei');
1984
+ const imxConfig = config.immutableXConfig;
1985
+ const depositsApi = new DepositsApi(imxConfig.apiConfiguration);
1986
+ const encodingApi = new EncodingApi(imxConfig.apiConfiguration);
1987
+ const usersApi = new UsersApi(imxConfig.apiConfiguration);
1988
+ const getSignableDepositRequest = {
1989
+ user,
1990
+ token: {
1991
+ type: deposit.type,
1992
+ data,
3381
1993
  },
3382
- });
3383
- const signableMessage = signableResult.data.signable_message;
3384
- if (signableMessage === undefined) {
3385
- throw new Error('Invalid response from Signable registration offchain');
3386
- }
3387
- const ethSignature = await signRaw(signableMessage, ethSigner);
3388
- const requests = [];
3389
- for (const resp of signableResult.data.signable_responses) {
3390
- // TODO: remove once fixed
3391
- // eslint-disable-next-line no-await-in-loop
3392
- const starkSignature = await starkSigner.signMessage(resp.payload_hash);
3393
- const req = {
3394
- sender_vault_id: resp.sender_vault_id,
3395
- receiver_stark_key: resp.receiver_stark_key,
3396
- receiver_vault_id: resp.receiver_vault_id,
3397
- asset_id: resp.asset_id,
3398
- amount: resp.amount,
3399
- nonce: resp.nonce,
3400
- expiration_timestamp: resp.expiration_timestamp,
3401
- stark_signature: starkSignature,
3402
- };
3403
- requests.push(req);
3404
- }
3405
- // TODO: throw error on missing payload hash?
3406
- const transferSigningParams = {
3407
- sender_stark_key: signableResult.data.sender_stark_key,
3408
- requests,
1994
+ amount: amount.toString(),
3409
1995
  };
3410
- const response = await transfersApi.createTransfer({
3411
- createTransferRequestV2: transferSigningParams,
3412
- xImxEthAddress: ethAddress,
3413
- xImxEthSignature: ethSignature,
1996
+ const signableDepositResult = await depositsApi.getSignableDeposit({
1997
+ getSignableDepositRequest,
3414
1998
  });
3415
- return {
3416
- transfer_ids: response?.data.transfer_ids,
3417
- };
1999
+ const encodingResult = await encodingApi.encodeAsset({
2000
+ assetType: 'asset',
2001
+ encodeAssetRequest: {
2002
+ token: {
2003
+ type: deposit.type,
2004
+ },
2005
+ },
2006
+ });
2007
+ const assetType = encodingResult.data.asset_type;
2008
+ const starkPublicKey = signableDepositResult.data.stark_key;
2009
+ const vaultId = signableDepositResult.data.vault_id;
2010
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2011
+ if (!isRegistered) {
2012
+ return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig, usersApi);
2013
+ }
2014
+ return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig);
3418
2015
  }
3419
2016
 
3420
- async function createOrder({ signers, request, config, }) {
3421
- await validateChain(signers.ethSigner, config.immutableXConfig);
3422
- const ethAddress = await signers.ethSigner.getAddress();
3423
- const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
3424
- const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
3425
- const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
3426
- const getSignableOrderRequest = {
3427
- user: ethAddress,
3428
- amount_buy: amountBuy,
3429
- token_buy: convertToSignableToken(request.buy),
3430
- amount_sell: amountSell,
3431
- token_sell: convertToSignableToken(request.sell),
3432
- fees: request.fees,
3433
- expiration_timestamp: request.expiration_timestamp,
2017
+ async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
2018
+ const etherKey = await ethSigner.getAddress();
2019
+ const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
2020
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
2021
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
2022
+ return ethSigner.sendTransaction(populatedTransaction);
2023
+ }
2024
+ async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
2025
+ const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
2026
+ const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
2027
+ return ethSigner.sendTransaction(populatedTransaction);
2028
+ }
2029
+ async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
2030
+ await validateChain(ethSigner, config.immutableXConfig);
2031
+ const { apiConfiguration, ethConfiguration } = config.immutableXConfig;
2032
+ const user = await ethSigner.getAddress();
2033
+ const tokensApi = new TokensApi(apiConfiguration);
2034
+ const depositsApi = new DepositsApi(apiConfiguration);
2035
+ const encodingApi = new EncodingApi(apiConfiguration);
2036
+ const usersApi = new UsersApi(apiConfiguration);
2037
+ // Get decimals for this specific ERC20
2038
+ const token = await tokensApi.getToken({ address: deposit.tokenAddress });
2039
+ // TODO: remove once fixed
2040
+ // eslint-disable-next-line radix
2041
+ const decimals = parseInt(token.data.decimals);
2042
+ const data = {
2043
+ decimals,
2044
+ token_address: deposit.tokenAddress,
3434
2045
  };
3435
- const getSignableOrderResponse = await ordersApi.getSignableOrder({
3436
- getSignableOrderRequestV3: getSignableOrderRequest,
3437
- });
3438
- const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
3439
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3440
- const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3441
- const resp = getSignableOrderResponse.data;
3442
- const orderParams = {
3443
- createOrderRequest: {
3444
- amount_buy: resp.amount_buy,
3445
- amount_sell: resp.amount_sell,
3446
- asset_id_buy: resp.asset_id_buy,
3447
- asset_id_sell: resp.asset_id_sell,
3448
- expiration_timestamp: resp.expiration_timestamp,
3449
- include_fees: true,
3450
- fees: request.fees,
3451
- nonce: resp.nonce,
3452
- stark_key: resp.stark_key,
3453
- stark_signature: starkSignature,
3454
- vault_id_buy: resp.vault_id_buy,
3455
- vault_id_sell: resp.vault_id_sell,
2046
+ const amount = parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
2047
+ // Approve whether an amount of token from an account can be spent by a third-party account
2048
+ const tokenContract = Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
2049
+ const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
2050
+ await ethSigner.sendTransaction(approveTransaction);
2051
+ const getSignableDepositRequest = {
2052
+ user,
2053
+ token: {
2054
+ type: deposit.type,
2055
+ data,
3456
2056
  },
3457
- xImxEthAddress: ethAddress,
3458
- xImxEthSignature: ethSignature,
3459
- };
3460
- const createOrderResponse = await ordersApi.createOrder(orderParams);
3461
- return {
3462
- ...createOrderResponse.data,
2057
+ amount: amount.toString(),
3463
2058
  };
3464
- }
3465
- async function cancelOrder({ signers, request, config, }) {
3466
- const ordersApi = new OrdersApi(config.immutableXConfig.apiConfiguration);
3467
- const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
3468
- getSignableCancelOrderRequest: {
3469
- order_id: request.order_id,
3470
- },
2059
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2060
+ getSignableDepositRequest,
3471
2061
  });
3472
- const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
3473
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3474
- const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3475
- const ethAddress = await signers.ethSigner.getAddress();
3476
- const cancelOrderResponse = await ordersApi.cancelOrder({
3477
- id: request.order_id.toString(),
3478
- cancelOrderRequest: {
3479
- order_id: request.order_id,
3480
- stark_signature: starkSignature,
2062
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2063
+ const encodingResult = await encodingApi.encodeAsset({
2064
+ assetType: 'asset',
2065
+ encodeAssetRequest: {
2066
+ token: {
2067
+ type: deposit.type,
2068
+ data: {
2069
+ token_address: deposit.tokenAddress,
2070
+ },
2071
+ },
3481
2072
  },
3482
- xImxEthAddress: ethAddress,
3483
- xImxEthSignature: ethSignature,
3484
2073
  });
3485
- return {
3486
- order_id: cancelOrderResponse.data.order_id,
3487
- status: cancelOrderResponse.data.status,
3488
- };
2074
+ const assetType = encodingResult.data.asset_type;
2075
+ const starkPublicKey = signableDepositResult.data.stark_key;
2076
+ const vaultId = signableDepositResult.data.vault_id;
2077
+ const quantizedAmount = BigNumber.from(signableDepositResult.data.amount);
2078
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2079
+ if (!isRegistered) {
2080
+ return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
2081
+ }
2082
+ return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
3489
2083
  }
3490
2084
 
3491
- async function registerOffchain(signers, config) {
3492
- await validateChain(signers.ethSigner, config.immutableXConfig);
3493
- const usersApi = new UsersApi(config.immutableXConfig.apiConfiguration);
3494
- const userAddress = await signers.ethSigner.getAddress();
3495
- const starkPublicKey = await signers.starkSigner.getAddress();
3496
- const signableResult = await usersApi.getSignableRegistrationOffchain({
3497
- getSignableRegistrationRequest: {
3498
- ether_key: userAddress,
3499
- stark_key: starkPublicKey,
3500
- },
3501
- });
3502
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3503
- const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3504
- const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3505
- const registeredUser = await usersApi.registerUser({
3506
- registerUserRequest: {
3507
- eth_signature: ethSignature,
3508
- ether_key: userAddress,
3509
- stark_signature: starkSignature,
3510
- stark_key: starkPublicKey,
3511
- },
3512
- });
3513
- return registeredUser.data;
2085
+ async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
2086
+ const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
2087
+ const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
2088
+ return ethSigner.sendTransaction(populatedTransaction);
3514
2089
  }
3515
- async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
2090
+ async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
3516
2091
  await validateChain(ethSigner, config.immutableXConfig);
3517
- const registrationContract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
3518
- try {
3519
- return await registrationContract.isRegistered(starkPublicKey);
3520
- }
3521
- catch (ex) {
3522
- if (ex.reason === 'USER_UNREGISTERED') {
3523
- return false;
3524
- }
3525
- throw ex;
3526
- }
3527
- }
3528
- async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
3529
- const response = await usersApi.getSignableRegistration({
3530
- getSignableRegistrationRequest: {
3531
- ether_key: etherKey,
3532
- stark_key: starkPublicKey,
3533
- },
3534
- });
3535
- return {
3536
- operator_signature: response.data.operator_signature,
3537
- payload_hash: response.data.payload_hash,
2092
+ const user = await ethSigner.getAddress();
2093
+ const { immutableXConfig } = config;
2094
+ const depositsApi = new DepositsApi(immutableXConfig.apiConfiguration);
2095
+ const encodingApi = new EncodingApi(immutableXConfig.apiConfiguration);
2096
+ const usersApi = new UsersApi(immutableXConfig.apiConfiguration);
2097
+ const data = {
2098
+ token_address: deposit.tokenAddress,
2099
+ token_id: deposit.tokenId,
3538
2100
  };
3539
- }
3540
-
3541
- const assertIsDefined = (value) => {
3542
- if (value !== undefined)
3543
- return value;
3544
- throw new Error('undefined field exception');
3545
- };
3546
- async function prepareWithdrawalAction(params) {
3547
- const { signers: { ethSigner, starkSigner }, type, config, } = params;
3548
- await validateChain(ethSigner, params.config);
3549
- const withdrawalsApi = new WithdrawalsApi(config.apiConfiguration);
3550
- const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
3551
- const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
3552
- getSignableWithdrawalRequest: {
3553
- user: await ethSigner.getAddress(),
3554
- token: convertToSignableToken(params),
3555
- amount: withdrawalAmount,
3556
- },
3557
- });
3558
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
3559
- const starkSignature = await starkSigner.signMessage(payloadHash);
3560
- const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
3561
- const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
3562
- createWithdrawalRequest: {
3563
- stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
3564
- amount: withdrawalAmount,
3565
- asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
3566
- vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
3567
- nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
3568
- stark_signature: starkSignature,
2101
+ const amount = '1';
2102
+ const getSignableDepositRequest = {
2103
+ user,
2104
+ token: {
2105
+ type: deposit.type,
2106
+ data,
3569
2107
  },
3570
- xImxEthAddress: ethAddress,
3571
- xImxEthSignature: ethSignature,
2108
+ amount: amount.toString(),
2109
+ };
2110
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2111
+ getSignableDepositRequest,
3572
2112
  });
3573
- return prepareWithdrawalResponse.data;
3574
- }
3575
-
3576
- async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
3577
- const encodingApi = new EncodingApi(config.apiConfiguration);
3578
- const result = await encodingApi.encodeAsset({
3579
- assetType,
2113
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2114
+ const encodingResult = await encodingApi.encodeAsset({
2115
+ assetType: 'asset',
3580
2116
  encodeAssetRequest: {
3581
2117
  token: {
3582
- type: tokenType,
3583
- ...(tokenData && { data: tokenData }),
2118
+ type: deposit.type,
2119
+ data: {
2120
+ token_address: deposit.tokenAddress,
2121
+ token_id: deposit.tokenId,
2122
+ },
3584
2123
  },
3585
2124
  },
3586
2125
  });
3587
- return result.data;
3588
- }
3589
-
3590
- async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
3591
- const etherKey = await ethSigner.getAddress();
3592
- const imxConfig = config.immutableXConfig;
3593
- const usersApi = new UsersApi(imxConfig.apiConfiguration);
3594
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3595
- const contract = Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
3596
- const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
3597
- return ethSigner.sendTransaction(populatedTransaction);
3598
- }
3599
- async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
3600
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3601
- const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
3602
- return ethSigner.sendTransaction(populatedTransaction);
3603
- }
3604
- async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
3605
- await validateChain(ethSigner, config.immutableXConfig);
3606
- const imxConfig = config.immutableXConfig;
3607
- const assetType = await getEncodeAssetInfo('asset', 'ERC20', imxConfig, {
3608
- token_address: token.tokenAddress,
3609
- });
3610
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3611
- if (!isRegistered) {
3612
- return executeRegisterAndWithdrawERC20({
3613
- ethSigner,
3614
- assetType: assetType.asset_type,
3615
- starkPublicKey,
3616
- config,
3617
- });
3618
- }
3619
- return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3620
- }
3621
-
3622
- async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
3623
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3624
- const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
3625
- return ethSigner.sendTransaction(populatedTransaction);
3626
- }
3627
- async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
3628
- const etherKey = await ethSigner.getAddress();
3629
- const usersApi = new UsersApi(config.apiConfiguration);
3630
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3631
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3632
- const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
3633
- return ethSigner.sendTransaction(populatedTransaction);
3634
- }
3635
- function getMintingBlob(token) {
3636
- const { id } = token.data;
3637
- const blueprint = token.data.blueprint || '';
3638
- return encUtils.sanitizeHex(encUtils.utf8ToHex(`{${id}}:{${blueprint}}`));
3639
- }
3640
- async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
3641
- const imxConfig = config.immutableXConfig;
3642
- const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', imxConfig, {
3643
- id: token.data.id,
3644
- token_address: token.data.tokenAddress,
3645
- ...(token.data.blueprint && { blueprint: token.data.blueprint }),
3646
- });
3647
- const mintingBlob = getMintingBlob(token);
3648
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3649
- if (!isRegistered) {
3650
- return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
3651
- }
3652
- return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
3653
- }
3654
- async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
3655
- const etherKey = await ethSigner.getAddress();
3656
- const usersApi = new UsersApi(config.apiConfiguration);
3657
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3658
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3659
- const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
3660
- return ethSigner.sendTransaction(populatedTransaction);
3661
- }
3662
- async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
3663
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3664
- const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
3665
- return ethSigner.sendTransaction(populatedTransaction);
3666
- }
3667
- async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
3668
- const imxConfig = config.immutableXConfig;
3669
- const assetType = await getEncodeAssetInfo('asset', 'ERC721', imxConfig, {
3670
- token_id: token.tokenId,
3671
- token_address: token.tokenAddress,
3672
- });
2126
+ const assetType = encodingResult.data.asset_type;
2127
+ const starkPublicKey = signableDepositResult.data.stark_key;
2128
+ const vaultId = signableDepositResult.data.vault_id;
3673
2129
  const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3674
- if (!isRegistered) {
3675
- return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
2130
+ // Approve whether an amount of token from an account can be spent by a third-party account
2131
+ const tokenContract = Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
2132
+ const operator = immutableXConfig.ethConfiguration.coreContractAddress;
2133
+ const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
2134
+ if (!isApprovedForAll) {
2135
+ await tokenContract.setApprovalForAll(operator, true);
3676
2136
  }
3677
- return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
3678
- }
3679
- async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
3680
- await validateChain(ethSigner, config.immutableXConfig);
3681
- const { tokenAddress } = token;
3682
- const { tokenId } = token;
3683
- const imxConfig = config.immutableXConfig;
3684
- const mintsApi = new MintsApi(imxConfig.apiConfiguration);
3685
- return await mintsApi
3686
- .getMintableTokenDetailsByClientTokenId({
3687
- tokenAddress,
3688
- tokenId,
3689
- })
3690
- .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
3691
- type: 'ERC721',
3692
- data: {
3693
- id: tokenId,
3694
- tokenAddress,
3695
- blueprint: mintableToken.data.blueprint,
3696
- },
3697
- }, config))
3698
- .catch((error) => {
3699
- if (error.response?.status === 404) {
3700
- // token is already minted on L1
3701
- return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
3702
- }
3703
- throw error; // unable to recover from any other kind of error
3704
- });
3705
- }
3706
-
3707
- async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
3708
- const etherKey = await ethSigner.getAddress();
3709
- const usersApi = new UsersApi(config.apiConfiguration);
3710
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3711
- const contract = Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3712
- const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
3713
- return ethSigner.sendTransaction(populatedTransaction);
3714
- }
3715
- async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
3716
- const contract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3717
- const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
3718
- return ethSigner.sendTransaction(populatedTransaction);
3719
- }
3720
- async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
3721
- await validateChain(ethSigner, config.immutableXConfig);
3722
- const imxConfig = config.immutableXConfig;
3723
- const assetType = await getEncodeAssetInfo('asset', 'ETH', imxConfig);
3724
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3725
2137
  if (!isRegistered) {
3726
- return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
2138
+ const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
2139
+ const coreContract = Contracts.Core.connect(immutableXConfig.ethConfiguration.coreContractAddress, ethSigner);
2140
+ // Note: proxy registration contract registerAndDepositNft method is not used as
2141
+ // it currently fails erc721 transfer ownership check
2142
+ await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
3727
2143
  }
3728
- return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
2144
+ return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, immutableXConfig);
3729
2145
  }
3730
2146
 
3731
- async function prepareWithdrawal({ signers, withdrawal, config, }) {
3732
- return prepareWithdrawalAction({
3733
- signers,
3734
- config: config.immutableXConfig,
3735
- ...withdrawal,
3736
- });
3737
- }
3738
- // TODO: remove once fixed
3739
- // eslint-disable-next-line consistent-return
3740
- async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
2147
+ // TODO: remove once fixed deposit variable shadowing
2148
+ // eslint-disable-next-line consistent-return, @typescript-eslint/no-shadow
2149
+ async function deposit({ signers, deposit, config }) {
3741
2150
  // TODO: please add a reasonable default here
3742
2151
  // eslint-disable-next-line default-case
3743
- switch (token.type) {
2152
+ switch (deposit.type) {
3744
2153
  case 'ETH':
3745
- return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
3746
- case 'ERC20':
3747
- return completeERC20WithdrawalAction({
3748
- ethSigner,
3749
- starkPublicKey,
3750
- token,
3751
- config,
3752
- });
3753
- case 'ERC721':
3754
- return completeERC721WithdrawalAction({
3755
- ethSigner,
3756
- starkPublicKey,
3757
- token,
3758
- config,
3759
- });
3760
- }
3761
- }
3762
-
3763
- async function createTrade({ signers: { ethSigner, starkSigner }, request, config, }) {
3764
- await validateChain(ethSigner, config.immutableXConfig);
3765
- const ethAddress = await ethSigner.getAddress();
3766
- const tradesApi = new TradesApi(config.immutableXConfig.apiConfiguration);
3767
- const signableResult = await tradesApi.getSignableTrade({
3768
- getSignableTradeRequest: {
3769
- user: ethAddress,
3770
- order_id: request.order_id,
3771
- fees: request.fees,
3772
- },
3773
- });
3774
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3775
- const ethSignature = await signRaw(signableMessage, ethSigner);
3776
- const starkSignature = await starkSigner.signMessage(payloadHash);
3777
- const createTradeResponse = await tradesApi.createTrade({
3778
- createTradeRequest: {
3779
- amount_buy: signableResult.data.amount_buy,
3780
- amount_sell: signableResult.data.amount_sell,
3781
- asset_id_buy: signableResult.data.asset_id_buy,
3782
- asset_id_sell: signableResult.data.asset_id_sell,
3783
- expiration_timestamp: signableResult.data.expiration_timestamp,
3784
- fee_info: signableResult.data.fee_info,
3785
- fees: request.fees,
3786
- include_fees: true,
3787
- nonce: signableResult.data.nonce,
3788
- order_id: request.order_id,
3789
- stark_key: signableResult.data.stark_key,
3790
- vault_id_buy: signableResult.data.vault_id_buy,
3791
- vault_id_sell: signableResult.data.vault_id_sell,
3792
- stark_signature: starkSignature,
3793
- },
3794
- xImxEthAddress: ethAddress,
3795
- xImxEthSignature: ethSignature,
3796
- });
3797
- return createTradeResponse.data;
3798
- }
3799
-
3800
- async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
3801
- const etherKey = await ethSigner.getAddress();
3802
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3803
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3804
- const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
3805
- return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
3806
- }
3807
- async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
3808
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3809
- const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
3810
- return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
3811
- }
3812
- async function depositEth({ signers: { ethSigner }, deposit, config, }) {
3813
- await validateChain(ethSigner, config.immutableXConfig);
3814
- const user = await ethSigner.getAddress();
3815
- const data = {
3816
- decimals: 18,
3817
- };
3818
- const amount = parseUnits(deposit.amount, 'wei');
3819
- const imxConfig = config.immutableXConfig;
3820
- const depositsApi = new DepositsApi(imxConfig.apiConfiguration);
3821
- const encodingApi = new EncodingApi(imxConfig.apiConfiguration);
3822
- const usersApi = new UsersApi(imxConfig.apiConfiguration);
3823
- const getSignableDepositRequest = {
3824
- user,
3825
- token: {
3826
- type: deposit.type,
3827
- data,
3828
- },
3829
- amount: amount.toString(),
3830
- };
3831
- const signableDepositResult = await depositsApi.getSignableDeposit({
3832
- getSignableDepositRequest,
3833
- });
3834
- const encodingResult = await encodingApi.encodeAsset({
3835
- assetType: 'asset',
3836
- encodeAssetRequest: {
3837
- token: {
3838
- type: deposit.type,
3839
- },
3840
- },
3841
- });
3842
- const assetType = encodingResult.data.asset_type;
3843
- const starkPublicKey = signableDepositResult.data.stark_key;
3844
- const vaultId = signableDepositResult.data.vault_id;
3845
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3846
- if (!isRegistered) {
3847
- return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig, usersApi);
3848
- }
3849
- return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig);
3850
- }
3851
-
3852
- async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
3853
- const etherKey = await ethSigner.getAddress();
3854
- const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
3855
- const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3856
- const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
3857
- return ethSigner.sendTransaction(populatedTransaction);
3858
- }
3859
- async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
3860
- const coreContract = Contracts.Core.connect(config.coreContractAddress, ethSigner);
3861
- const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
3862
- return ethSigner.sendTransaction(populatedTransaction);
3863
- }
3864
- async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
3865
- await validateChain(ethSigner, config.immutableXConfig);
3866
- const { apiConfiguration, ethConfiguration } = config.immutableXConfig;
3867
- const user = await ethSigner.getAddress();
3868
- const tokensApi = new TokensApi(apiConfiguration);
3869
- const depositsApi = new DepositsApi(apiConfiguration);
3870
- const encodingApi = new EncodingApi(apiConfiguration);
3871
- const usersApi = new UsersApi(apiConfiguration);
3872
- // Get decimals for this specific ERC20
3873
- const token = await tokensApi.getToken({ address: deposit.tokenAddress });
3874
- // TODO: remove once fixed
3875
- // eslint-disable-next-line radix
3876
- const decimals = parseInt(token.data.decimals);
3877
- const data = {
3878
- decimals,
3879
- token_address: deposit.tokenAddress,
3880
- };
3881
- const amount = parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
3882
- // Approve whether an amount of token from an account can be spent by a third-party account
3883
- const tokenContract = Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
3884
- const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
3885
- await ethSigner.sendTransaction(approveTransaction);
3886
- const getSignableDepositRequest = {
3887
- user,
3888
- token: {
3889
- type: deposit.type,
3890
- data,
3891
- },
3892
- amount: amount.toString(),
3893
- };
3894
- const signableDepositResult = await depositsApi.getSignableDeposit({
3895
- getSignableDepositRequest,
3896
- });
3897
- // Perform encoding on asset details to get an assetType (required for stark contract request)
3898
- const encodingResult = await encodingApi.encodeAsset({
3899
- assetType: 'asset',
3900
- encodeAssetRequest: {
3901
- token: {
3902
- type: deposit.type,
3903
- data: {
3904
- token_address: deposit.tokenAddress,
3905
- },
3906
- },
3907
- },
3908
- });
3909
- const assetType = encodingResult.data.asset_type;
3910
- const starkPublicKey = signableDepositResult.data.stark_key;
3911
- const vaultId = signableDepositResult.data.vault_id;
3912
- const quantizedAmount = BigNumber$1.from(signableDepositResult.data.amount);
3913
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3914
- if (!isRegistered) {
3915
- return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
3916
- }
3917
- return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
3918
- }
3919
-
3920
- async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
3921
- const coreContract = Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3922
- const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
3923
- return ethSigner.sendTransaction(populatedTransaction);
3924
- }
3925
- async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
3926
- await validateChain(ethSigner, config.immutableXConfig);
3927
- const user = await ethSigner.getAddress();
3928
- const { immutableXConfig } = config;
3929
- const depositsApi = new DepositsApi(immutableXConfig.apiConfiguration);
3930
- const encodingApi = new EncodingApi(immutableXConfig.apiConfiguration);
3931
- const usersApi = new UsersApi(immutableXConfig.apiConfiguration);
3932
- const data = {
3933
- token_address: deposit.tokenAddress,
3934
- token_id: deposit.tokenId,
3935
- };
3936
- const amount = '1';
3937
- const getSignableDepositRequest = {
3938
- user,
3939
- token: {
3940
- type: deposit.type,
3941
- data,
3942
- },
3943
- amount: amount.toString(),
3944
- };
3945
- const signableDepositResult = await depositsApi.getSignableDeposit({
3946
- getSignableDepositRequest,
3947
- });
3948
- // Perform encoding on asset details to get an assetType (required for stark contract request)
3949
- const encodingResult = await encodingApi.encodeAsset({
3950
- assetType: 'asset',
3951
- encodeAssetRequest: {
3952
- token: {
3953
- type: deposit.type,
3954
- data: {
3955
- token_address: deposit.tokenAddress,
3956
- token_id: deposit.tokenId,
3957
- },
3958
- },
3959
- },
3960
- });
3961
- const assetType = encodingResult.data.asset_type;
3962
- const starkPublicKey = signableDepositResult.data.stark_key;
3963
- const vaultId = signableDepositResult.data.vault_id;
3964
- const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3965
- // Approve whether an amount of token from an account can be spent by a third-party account
3966
- const tokenContract = Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
3967
- const operator = immutableXConfig.ethConfiguration.coreContractAddress;
3968
- const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
3969
- if (!isApprovedForAll) {
3970
- await tokenContract.setApprovalForAll(operator, true);
3971
- }
3972
- if (!isRegistered) {
3973
- const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
3974
- const coreContract = Contracts.Core.connect(immutableXConfig.ethConfiguration.coreContractAddress, ethSigner);
3975
- // Note: proxy registration contract registerAndDepositNft method is not used as
3976
- // it currently fails erc721 transfer ownership check
3977
- await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
3978
- }
3979
- return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, immutableXConfig);
3980
- }
3981
-
3982
- // TODO: remove once fixed deposit variable shadowing
3983
- // eslint-disable-next-line consistent-return, @typescript-eslint/no-shadow
3984
- async function deposit({ signers, deposit, config }) {
3985
- // TODO: please add a reasonable default here
3986
- // eslint-disable-next-line default-case
3987
- switch (deposit.type) {
3988
- case 'ETH':
3989
- return depositEth({ signers, deposit, config });
2154
+ return depositEth({ signers, deposit, config });
3990
2155
  case 'ERC20':
3991
2156
  return depositERC20({ signers, deposit, config });
3992
2157
  case 'ERC721':
@@ -4032,1336 +2197,339 @@ async function exchangeTransfer({ signers, request, config, }) {
4032
2197
  return {
4033
2198
  sent_signature: response?.data.sent_signature,
4034
2199
  status: response?.data.status?.toString(),
4035
- time: response?.data.time,
4036
- transfer_id: response?.data.transfer_id,
4037
- };
4038
- }
4039
-
4040
- class GenericIMXProvider {
4041
- config;
4042
- signers;
4043
- constructor(config, ethSigner, starkSigner) {
4044
- this.config = config;
4045
- this.signers = { ethSigner, starkSigner };
4046
- }
4047
- async getAddress() {
4048
- return await this.signers.ethSigner.getAddress();
4049
- }
4050
- registerOffchain() {
4051
- return registerOffchain(this.signers, this.config);
4052
- }
4053
- batchNftTransfer(request) {
4054
- return batchTransfer({
4055
- signers: this.signers,
4056
- request,
4057
- config: this.config,
4058
- });
4059
- }
4060
- cancelOrder(request) {
4061
- return cancelOrder({
4062
- signers: this.signers,
4063
- request,
4064
- config: this.config,
4065
- });
4066
- }
4067
- completeWithdrawal(starkPublicKey, token) {
4068
- return completeWithdrawal({
4069
- config: this.config,
4070
- signers: this.signers,
4071
- token,
4072
- starkPublicKey,
4073
- });
4074
- }
4075
- createOrder(request) {
4076
- return createOrder({
4077
- signers: this.signers,
4078
- request,
4079
- config: this.config,
4080
- });
4081
- }
4082
- createTrade(request) {
4083
- return createTrade({
4084
- signers: this.signers,
4085
- request,
4086
- config: this.config,
4087
- });
4088
- }
4089
- deposit(tokenAmount) {
4090
- return deposit({
4091
- signers: this.signers,
4092
- deposit: tokenAmount,
4093
- config: this.config,
4094
- });
4095
- }
4096
- exchangeTransfer(request) {
4097
- return exchangeTransfer({
4098
- signers: this.signers,
4099
- request,
4100
- config: this.config,
4101
- });
4102
- }
4103
- async isRegisteredOnchain() {
4104
- const starkPublicKey = await this.signers.starkSigner.getAddress();
4105
- return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
4106
- }
4107
- prepareWithdrawal(request) {
4108
- return prepareWithdrawal({
4109
- signers: this.signers,
4110
- withdrawal: request,
4111
- config: this.config,
4112
- });
4113
- }
4114
- transfer(request) {
4115
- return transfer({
4116
- signers: this.signers,
4117
- request,
4118
- config: this.config,
4119
- });
4120
- }
4121
- }
4122
-
4123
- const WALLET_ACTION = {
4124
- // TODO: remove once fixed - consider using an enum
4125
- // eslint-disable-next-line @typescript-eslint/naming-convention
4126
- SWITCH_CHAIN: 'wallet_switchEthereumChain',
4127
- // eslint-disable-next-line @typescript-eslint/naming-convention
4128
- CONNECT: 'eth_requestAccounts',
4129
- };
4130
- function isRequestableProvider(provider) {
4131
- return !!provider?.request;
4132
- }
4133
- async function connectProvider(provider, chainID) {
4134
- await provider.request({ method: WALLET_ACTION.CONNECT });
4135
- if (chainID) {
4136
- await provider.request({
4137
- method: WALLET_ACTION.SWITCH_CHAIN,
4138
- params: [{ chainId: `0x${chainID.toString(16)}` }],
4139
- });
4140
- }
4141
- }
4142
-
4143
- const ERRORS = {
4144
- // TODO: remove once fixed - consider using something in line with the naming convention
4145
- // eslint-disable-next-line @typescript-eslint/naming-convention
4146
- PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
4147
- };
4148
- async function connect$1({ chainID, }) {
4149
- const provider = (await detectEthereumProvider());
4150
- if (!isRequestableProvider(provider)) {
4151
- throw new Error(ERRORS.PROVIDER_NOT_FOUND);
4152
- }
4153
- await connectProvider(provider, chainID);
4154
- // NOTE: if we want to listen to Metamask events in the future, we can add a
4155
- // listener here.
4156
- return new ethers.providers.Web3Provider(provider);
4157
- }
4158
-
4159
- const COMMUNICATION_TYPE = 'message';
4160
- var RequestEventType;
4161
- (function (RequestEventType) {
4162
- RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
4163
- RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
4164
- RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
4165
- RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
4166
- })(RequestEventType || (RequestEventType = {}));
4167
- var ResponseEventType;
4168
- (function (ResponseEventType) {
4169
- ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
4170
- ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
4171
- ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
4172
- ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
4173
- })(ResponseEventType || (ResponseEventType = {}));
4174
-
4175
- function postRequestMessage(iframe, payload) {
4176
- if (iframe && iframe.contentWindow) {
4177
- iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
4178
- }
4179
- }
4180
-
4181
- function messageResponseListener(iframe, event, eventType, callback) {
4182
- if (iframe && event.source !== iframe.contentWindow) {
4183
- return;
4184
- }
4185
- const l2WalletMessage = event.data;
4186
- if (l2WalletMessage.type !== eventType) {
4187
- return;
4188
- }
4189
- callback(l2WalletMessage.details);
4190
- }
4191
-
4192
- class ImxSigner {
4193
- publicAddress;
4194
- iframe;
4195
- constructor(publicAddress, iframe) {
4196
- this.publicAddress = publicAddress;
4197
- this.iframe = iframe;
4198
- }
4199
- getAddress() {
4200
- return this.publicAddress;
4201
- }
4202
- signMessage(rawMessage) {
4203
- return new Promise((resolve, reject) => {
4204
- const listener = (event) => {
4205
- messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
4206
- window.removeEventListener(COMMUNICATION_TYPE, listener);
4207
- if (!messageDetails.success) {
4208
- reject(new Error(messageDetails.error?.message));
4209
- }
4210
- resolve(messageDetails.data.signedMessage);
4211
- });
4212
- };
4213
- window.addEventListener(COMMUNICATION_TYPE, listener);
4214
- postRequestMessage(this.iframe, {
4215
- type: RequestEventType.SIGN_MESSAGE_REQUEST,
4216
- details: { starkPublicKey: this.publicAddress, message: rawMessage },
4217
- });
4218
- });
4219
- }
4220
- getIFrame() {
4221
- return this.iframe;
4222
- }
4223
- }
4224
-
4225
- const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
4226
- const IMX_WALLET_IFRAME_HOSTS = {
4227
- [Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
4228
- [Environment.PRODUCTION]: 'https://wallets.immutable.com',
4229
- };
4230
- const IMX_WALLET_IFRAME_STYLE = 'display: none;';
4231
- function getIFrame() {
4232
- return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
4233
- }
4234
- async function setupIFrame(env) {
4235
- return new Promise((resolve) => {
4236
- const iframe = document.createElement('iframe');
4237
- iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
4238
- iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
4239
- iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
4240
- document.body.appendChild(iframe);
4241
- iframe.onload = () => resolve(iframe);
4242
- });
4243
- }
4244
- async function getOrSetupIFrame(env) {
4245
- const iframe = getIFrame();
4246
- if (iframe)
4247
- return iframe;
4248
- return await setupIFrame(env);
4249
- }
4250
-
4251
- const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
4252
- const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
4253
- async function connect(l1Provider, env) {
4254
- const l1Signer = l1Provider.getSigner();
4255
- const address = await l1Signer.getAddress();
4256
- const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
4257
- const iframe = await getOrSetupIFrame(env);
4258
- return new Promise((resolve, reject) => {
4259
- const listener = (event) => {
4260
- messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
4261
- window.removeEventListener(COMMUNICATION_TYPE, listener);
4262
- if (!messageDetails.success) {
4263
- reject(new Error(CONNECTION_FAILED_ERROR));
4264
- }
4265
- resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
4266
- });
4267
- };
4268
- window.addEventListener(COMMUNICATION_TYPE, listener);
4269
- postRequestMessage(iframe, {
4270
- type: RequestEventType.CONNECT_WALLET_REQUEST,
4271
- details: { ethAddress: address, signature },
4272
- });
4273
- });
4274
- }
4275
- async function disconnect(imxSigner) {
4276
- const iframe = imxSigner.getIFrame();
4277
- return new Promise((resolve, reject) => {
4278
- const listener = (event) => {
4279
- messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
4280
- window.removeEventListener(COMMUNICATION_TYPE, listener);
4281
- if (!messageDetails.success && messageDetails.error) {
4282
- reject(messageDetails.error);
4283
- }
4284
- iframe.remove();
4285
- resolve();
4286
- });
4287
- };
4288
- window.addEventListener(COMMUNICATION_TYPE, listener);
4289
- postRequestMessage(iframe, {
4290
- type: RequestEventType.DISCONNECT_WALLET_REQUEST,
4291
- details: { starkPublicKey: imxSigner.getAddress() },
4292
- });
4293
- });
4294
- }
4295
-
4296
- var ProviderErrorType;
4297
- (function (ProviderErrorType) {
4298
- ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
4299
- ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
4300
- })(ProviderErrorType || (ProviderErrorType = {}));
4301
- class ProviderError extends Error {
4302
- type;
4303
- constructor(message, type) {
4304
- super(message);
4305
- this.type = type;
4306
- }
4307
- }
4308
- const withProviderError = async (fn, customError) => {
4309
- try {
4310
- return await fn();
4311
- }
4312
- catch (error) {
4313
- const errorMessage = customError.message || `${error.message}` || 'UnknownError';
4314
- throw new ProviderError(errorMessage, customError.type);
4315
- }
4316
- };
4317
-
4318
- class MetaMaskIMXProvider extends GenericIMXProvider {
4319
- static imxSigner;
4320
- static async connect(config) {
4321
- return await withProviderError(async () => {
4322
- const metaMaskProvider = await connect$1({
4323
- chainID: config.immutableXConfig.ethConfiguration.chainID,
4324
- });
4325
- this.imxSigner = await connect(metaMaskProvider, config.baseConfig.environment);
4326
- return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
4327
- }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
4328
- }
4329
- static async disconnect() {
4330
- if (!this.imxSigner) {
4331
- throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
4332
- }
4333
- return withProviderError(async () => {
4334
- await disconnect(this.imxSigner);
4335
- }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
4336
- }
4337
- static async signMessage(message) {
4338
- if (!this.imxSigner) {
4339
- throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
4340
- }
4341
- return withProviderError(async () => await this.imxSigner.signMessage(message), { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
4342
- }
4343
- }
4344
-
4345
- class ProviderConfiguration {
4346
- immutableXConfig;
4347
- baseConfig;
4348
- constructor({ baseConfig, overrides }) {
4349
- this.baseConfig = baseConfig;
4350
- if (overrides) {
4351
- this.immutableXConfig = overrides.immutableXConfig;
4352
- }
4353
- else {
4354
- // TODO: remove once a sensible default is chosen
4355
- // eslint-disable-next-line default-case
4356
- switch (baseConfig.environment) {
4357
- case Environment.SANDBOX: {
4358
- this.immutableXConfig = Config.SANDBOX;
4359
- break;
4360
- }
4361
- case Environment.PRODUCTION: {
4362
- this.immutableXConfig = Config.PRODUCTION;
4363
- break;
4364
- }
4365
- }
4366
- }
4367
- }
4368
- }
4369
-
4370
- function $parcel$interopDefault(a) {
4371
- return a && a.__esModule ? a.default : a;
2200
+ time: response?.data.time,
2201
+ transfer_id: response?.data.transfer_id,
2202
+ };
4372
2203
  }
4373
2204
 
4374
- const $762782b6c862d954$export$db5daa1b5156ccfe = [
4375
- {
4376
- constant: true,
4377
- inputs: [],
4378
- name: "name",
4379
- outputs: [
4380
- {
4381
- name: "",
4382
- type: "string"
4383
- }
4384
- ],
4385
- payable: false,
4386
- type: "function"
4387
- },
4388
- {
4389
- constant: true,
4390
- inputs: [],
4391
- name: "decimals",
4392
- outputs: [
4393
- {
4394
- name: "",
4395
- type: "uint8"
4396
- }
4397
- ],
4398
- payable: false,
4399
- type: "function"
4400
- },
4401
- {
4402
- constant: true,
4403
- inputs: [
4404
- {
4405
- name: "_owner",
4406
- type: "address"
4407
- }
4408
- ],
4409
- name: "balanceOf",
4410
- outputs: [
4411
- {
4412
- name: "balance",
4413
- type: "uint256"
4414
- }
4415
- ],
4416
- payable: false,
4417
- type: "function"
4418
- },
4419
- {
4420
- constant: true,
4421
- inputs: [],
4422
- name: "symbol",
4423
- outputs: [
4424
- {
4425
- name: "",
4426
- type: "string"
4427
- }
4428
- ],
4429
- payable: false,
4430
- type: "function"
2205
+ class GenericIMXProvider {
2206
+ config;
2207
+ signers;
2208
+ constructor(config, ethSigner, starkSigner) {
2209
+ this.config = config;
2210
+ this.signers = { ethSigner, starkSigner };
4431
2211
  }
4432
- ];
4433
-
4434
-
4435
-
4436
- const $bc2bfebf768286d3$export$6a2ba3c3bd042990 = {
4437
- baseConfig: {
4438
- environment: (Environment).SANDBOX
2212
+ async getAddress() {
2213
+ return await this.signers.ethSigner.getAddress();
4439
2214
  }
4440
- };
4441
-
4442
-
4443
- let $d176a05e966364ba$export$3bfad4d03ada24c4;
4444
- (function(ConnectionProviders) {
4445
- ConnectionProviders["METAMASK"] = "metamask";
4446
- })($d176a05e966364ba$export$3bfad4d03ada24c4 || ($d176a05e966364ba$export$3bfad4d03ada24c4 = {}));
4447
-
4448
-
4449
- let $a47e48dd2c04791b$export$c06e1e7429de6283;
4450
- (function(ChainId) {
4451
- ChainId[ChainId["ETHEREUM"] = 1] = "ETHEREUM";
4452
- ChainId[ChainId["SEPOLIA"] = 11155111] = "SEPOLIA";
4453
- ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13373] = "IMTBL_ZKEVM_DEVNET";
4454
- ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13372] = "IMTBL_ZKEVM_TESTNET";
4455
- ChainId[ChainId["POLYGON_ZKEVM_TESTNET"] = 1442] = "POLYGON_ZKEVM_TESTNET";
4456
- ChainId[ChainId["POLYGON_ZKEVM"] = 137] = "POLYGON_ZKEVM";
4457
- })($a47e48dd2c04791b$export$c06e1e7429de6283 || ($a47e48dd2c04791b$export$c06e1e7429de6283 = {}));
4458
- const $a47e48dd2c04791b$export$6f24f3cef7d501c4 = new Map([
4459
- [
4460
- $a47e48dd2c04791b$export$c06e1e7429de6283.ETHEREUM,
4461
- {
4462
- chainIdHex: "0x1",
4463
- chainName: "Ethereum",
4464
- rpcUrls: [
4465
- "https://mainnet.infura.io/v3/"
4466
- ],
4467
- nativeCurrency: {
4468
- name: "Ethereum",
4469
- symbol: "ETH",
4470
- decimals: 18
4471
- },
4472
- blockExplorerUrls: [
4473
- "https://etherscan.io/"
4474
- ]
4475
- }
4476
- ],
4477
- [
4478
- $a47e48dd2c04791b$export$c06e1e7429de6283.IMTBL_ZKEVM_TESTNET,
4479
- {
4480
- chainIdHex: "0x343C",
4481
- chainName: "Immutable zkEVM Testnet",
4482
- rpcUrls: [
4483
- "https://zkevm-rpc.sandbox.x.immutable.com"
4484
- ],
4485
- nativeCurrency: {
4486
- name: "IMX",
4487
- symbol: "IMX",
4488
- decimals: 18
4489
- }
4490
- }
4491
- ],
4492
- [
4493
- $a47e48dd2c04791b$export$c06e1e7429de6283.POLYGON_ZKEVM,
4494
- {
4495
- chainIdHex: "0x89",
4496
- chainName: "Polygon zkEVM",
4497
- rpcUrls: [
4498
- "https://polygon-rpc.com"
4499
- ],
4500
- nativeCurrency: {
4501
- name: "MATIC",
4502
- symbol: "MATIC",
4503
- decimals: 18
4504
- },
4505
- blockExplorerUrls: [
4506
- "https://polygonscan.com/"
4507
- ]
4508
- }
4509
- ]
4510
- ]);
4511
- const $a47e48dd2c04791b$export$3e81fc0987227f10 = new Map([
4512
- [
4513
- $a47e48dd2c04791b$export$c06e1e7429de6283.SEPOLIA,
4514
- {
4515
- chainIdHex: "0xaa36a7",
4516
- chainName: "Sepolia",
4517
- rpcUrls: [
4518
- "https://sepolia.infura.io/v3/"
4519
- ],
4520
- nativeCurrency: {
4521
- name: "Sep Eth",
4522
- symbol: "ETH",
4523
- decimals: 18
4524
- },
4525
- blockExplorerUrls: [
4526
- "https://sepolia.etherscan.io/"
4527
- ]
4528
- }
4529
- ],
4530
- [
4531
- $a47e48dd2c04791b$export$c06e1e7429de6283.IMTBL_ZKEVM_DEVNET,
4532
- {
4533
- chainIdHex: "0x343D",
4534
- chainName: "Immutable zkEVM Devnet",
4535
- rpcUrls: [
4536
- "https://zkevm-rpc.dev.x.immutable.com/"
4537
- ],
4538
- nativeCurrency: {
4539
- name: "IMX",
4540
- symbol: "IMX",
4541
- decimals: 18
4542
- }
4543
- }
4544
- ],
4545
- [
4546
- $a47e48dd2c04791b$export$c06e1e7429de6283.POLYGON_ZKEVM_TESTNET,
4547
- {
4548
- chainIdHex: "0x5A2",
4549
- chainName: "Polygon zkEVM Testnet",
4550
- rpcUrls: [
4551
- "https://rpc.public.zkevm-test.net"
4552
- ],
4553
- nativeCurrency: {
4554
- name: "MATIC",
4555
- symbol: "MATIC",
4556
- decimals: 18
4557
- },
4558
- blockExplorerUrls: [
4559
- "https://testnet-zkevm.polygonscan.com"
4560
- ]
4561
- }
4562
- ]
4563
- ]);
4564
- let $a47e48dd2c04791b$export$1f05a55fe0680cc7;
4565
- (function(NetworkFilterTypes) {
4566
- NetworkFilterTypes["ALL"] = "all";
4567
- })($a47e48dd2c04791b$export$1f05a55fe0680cc7 || ($a47e48dd2c04791b$export$1f05a55fe0680cc7 = {}));
4568
-
4569
-
4570
- // TODO: fix circular dependency
4571
- // eslint-disable-next-line import/no-cycle
4572
- let $08d5ddc39acd6833$export$fd9b17d87f4121d2;
4573
- (function(TokenFilterTypes) {
4574
- TokenFilterTypes["SWAP"] = "swap";
4575
- TokenFilterTypes["BRIDGE"] = "bridge";
4576
- TokenFilterTypes["ALL"] = "all";
4577
- })($08d5ddc39acd6833$export$fd9b17d87f4121d2 || ($08d5ddc39acd6833$export$fd9b17d87f4121d2 = {}));
4578
-
4579
-
4580
-
4581
-
4582
- // TODO: fix circular dependency
4583
- // eslint-disable-next-line import/no-cycle
4584
- let $4f91c5f280efe242$export$35b06f0d33f57e26;
4585
- (function(WalletAction) {
4586
- WalletAction["CHECK_CONNECTION"] = "eth_accounts";
4587
- WalletAction["CONNECT"] = "eth_requestAccounts";
4588
- WalletAction["ADD_NETWORK"] = "wallet_addEthereumChain";
4589
- WalletAction["SWITCH_NETWORK"] = "wallet_switchEthereumChain";
4590
- })($4f91c5f280efe242$export$35b06f0d33f57e26 || ($4f91c5f280efe242$export$35b06f0d33f57e26 = {}));
4591
- let $4f91c5f280efe242$export$a75605c67ea83a5a;
4592
- (function(WalletFilterTypes) {
4593
- WalletFilterTypes["ALL"] = "all";
4594
- WalletFilterTypes["DESKTOP"] = "desktop";
4595
- WalletFilterTypes["MOBILE"] = "mobile";
4596
- })($4f91c5f280efe242$export$a75605c67ea83a5a || ($4f91c5f280efe242$export$a75605c67ea83a5a = {}));
4597
-
4598
-
4599
-
4600
-
4601
- /**
4602
- * The different types of errors that can be returned by the checkout process.
4603
- */ let $a8bc256d81a5e2c1$export$e3dc0620abde7f5a;
4604
- (function(CheckoutErrorType) {
4605
- CheckoutErrorType["PROVIDER_PREFERENCE_ERROR"] = "PROVIDER_PREFERENCE_ERROR";
4606
- CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
4607
- CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
4608
- CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
4609
- CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
4610
- CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
4611
- CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
4612
- CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
4613
- CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
4614
- CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
4615
- CheckoutErrorType["TRANSACTION_ERROR"] = "TRANSACTION_ERROR";
4616
- })($a8bc256d81a5e2c1$export$e3dc0620abde7f5a || ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a = {}));
4617
- class $a8bc256d81a5e2c1$export$b722478a3cbfa3bc extends Error {
4618
- constructor(message, type, data){
4619
- super(message);
4620
- this.message = message;
4621
- this.type = type;
4622
- this.data = data;
2215
+ registerOffchain() {
2216
+ return registerOffchain(this.signers, this.config);
4623
2217
  }
4624
- }
4625
- let $a8bc256d81a5e2c1$export$a22d4e0719ee6def;
4626
- (function(CheckoutInternalErrorType) {
4627
- CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
4628
- })($a8bc256d81a5e2c1$export$a22d4e0719ee6def || ($a8bc256d81a5e2c1$export$a22d4e0719ee6def = {}));
4629
- const $a8bc256d81a5e2c1$export$bacc563de539c6c3 = async (fn, customError)=>{
4630
- try {
4631
- return await fn();
4632
- } catch (error) {
4633
- const cause = `${error.message}` || "UnknownError";
4634
- const errorMessage = customError.message ? `[${customError.type}]:${customError.message}. Cause:${cause}` : `[${customError.type}] Cause:${cause}`;
4635
- if (error instanceof $a8bc256d81a5e2c1$export$b722478a3cbfa3bc) throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
4636
- ...customError.data,
4637
- innerErrorType: error.type,
4638
- ...error.data
4639
- });
4640
- throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
4641
- ...customError.data
2218
+ batchNftTransfer(request) {
2219
+ return batchTransfer({
2220
+ signers: this.signers,
2221
+ request,
2222
+ config: this.config,
4642
2223
  });
4643
2224
  }
4644
- };
4645
-
4646
-
4647
-
4648
-
4649
- /* eslint-disable @typescript-eslint/no-explicit-any */
4650
-
4651
- /* eslint-disable @typescript-eslint/no-explicit-any */
4652
-
4653
-
4654
-
4655
- async function $c99672cf2294e839$var$getMetaMaskProvider() {
4656
- const provider = await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>await (detectEthereumProvider)(), {
4657
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR
4658
- });
4659
- if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR);
4660
- return new (Web3Provider)(provider);
4661
- }
4662
- async function $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference) {
4663
- let web3Provider = null;
4664
- switch(providerPreference){
4665
- case ($d176a05e966364ba$export$3bfad4d03ada24c4).METAMASK:
4666
- web3Provider = await $c99672cf2294e839$var$getMetaMaskProvider();
4667
- break;
4668
- default:
4669
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider preference is not supported", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_PREFERENCE_ERROR);
2225
+ cancelOrder(request) {
2226
+ return cancelOrder({
2227
+ signers: this.signers,
2228
+ request,
2229
+ config: this.config,
2230
+ });
4670
2231
  }
4671
- return web3Provider;
4672
- }
4673
- async function $c99672cf2294e839$export$2d040992269b4717(providerPreference) {
4674
- const provider = await $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference);
4675
- if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
4676
- details: `Unsupported provider for ${providerPreference}`
4677
- });
4678
- let accounts = [];
4679
- try {
4680
- accounts = await provider.provider.request({
4681
- method: (0, $4f91c5f280efe242$export$35b06f0d33f57e26).CHECK_CONNECTION,
4682
- params: []
2232
+ completeWithdrawal(starkPublicKey, token) {
2233
+ return completeWithdrawal({
2234
+ config: this.config,
2235
+ signers: this.signers,
2236
+ token,
2237
+ starkPublicKey,
4683
2238
  });
4684
- } catch (err) {
4685
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Check wallet connection request failed", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_FAILED_ERROR, {
4686
- rpcMethod: ($4f91c5f280efe242$export$35b06f0d33f57e26).CHECK_CONNECTION
2239
+ }
2240
+ createOrder(request) {
2241
+ return createOrder({
2242
+ signers: this.signers,
2243
+ request,
2244
+ config: this.config,
4687
2245
  });
4688
2246
  }
4689
- // accounts[0] will have the active account if connected.
4690
- return {
4691
- isConnected: accounts && accounts.length > 0,
4692
- walletAddress: accounts[0] ?? ""
4693
- };
4694
- }
4695
- async function $c99672cf2294e839$export$fba2f6c3656e07c1(params) {
4696
- const web3Provider = await $c99672cf2294e839$var$getWalletProviderForPreference(params.providerPreference);
4697
- await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4698
- if (!web3Provider || !web3Provider?.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
4699
- details: `Unsupported provider for ${params.providerPreference}`
2247
+ createTrade(request) {
2248
+ return createTrade({
2249
+ signers: this.signers,
2250
+ request,
2251
+ config: this.config,
4700
2252
  });
4701
- // this makes the request to the wallet to connect i.e request eth accounts ('eth_requestAccounts')
4702
- await web3Provider.provider.request({
4703
- method: ($4f91c5f280efe242$export$35b06f0d33f57e26).CONNECT,
4704
- params: []
2253
+ }
2254
+ deposit(tokenAmount) {
2255
+ return deposit({
2256
+ signers: this.signers,
2257
+ deposit: tokenAmount,
2258
+ config: this.config,
4705
2259
  });
4706
- }, {
4707
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR
4708
- });
4709
- return web3Provider;
4710
- }
4711
-
4712
-
4713
- var $497c134ecbc8a50f$exports = {};
4714
- $497c134ecbc8a50f$exports = JSON.parse('[{"chainId":1},{"chainId":11155111},{"chainId":13372},{"chainId":13373},{"chainId":1442},{"chainId":137}]');
4715
-
4716
-
4717
- const $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
4718
- // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
4719
- // make sure to check if(provider.provider?.request) in the exported function and throw an error
4720
- // eslint-disable-next-line consistent-return
4721
- async function $de192de6ef100f9f$var$switchNetworkInWallet(networkMap, provider, chainId) {
4722
- if (provider.provider?.request) return await provider.provider.request({
4723
- method: ($4f91c5f280efe242$export$35b06f0d33f57e26).SWITCH_NETWORK,
4724
- params: [
4725
- {
4726
- chainId: networkMap.get(chainId)?.chainIdHex
4727
- }
4728
- ]
4729
- });
4730
- }
4731
- // TODO: Should these functions always return something?
4732
- // eslint-disable-next-line consistent-return
4733
- async function $de192de6ef100f9f$var$addNetworkToWallet(networkMap, provider, chainId) {
4734
- if (provider.provider?.request) {
4735
- const networkDetails = networkMap.get(chainId);
4736
- const addNetwork = {
4737
- chainId: networkDetails?.chainIdHex,
4738
- chainName: networkDetails?.chainName,
4739
- rpcUrls: networkDetails?.rpcUrls,
4740
- nativeCurrency: networkDetails?.nativeCurrency,
4741
- blockExplorerUrls: networkDetails?.blockExplorerUrls
4742
- };
4743
- return await provider.provider.request({
4744
- method: ($4f91c5f280efe242$export$35b06f0d33f57e26).ADD_NETWORK,
4745
- params: [
4746
- addNetwork
4747
- ]
2260
+ }
2261
+ exchangeTransfer(request) {
2262
+ return exchangeTransfer({
2263
+ signers: this.signers,
2264
+ request,
2265
+ config: this.config,
4748
2266
  });
4749
2267
  }
4750
- }
4751
- async function $de192de6ef100f9f$export$79f13b4cfaaf0d09(config, provider) {
4752
- const { networkMap: networkMap } = config;
4753
- return ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4754
- const network = await provider.getNetwork();
4755
- if (!Array.from(networkMap.keys()).includes(network.chainId)) // return empty details
4756
- return {
4757
- chainId: network.chainId,
4758
- name: network.name,
4759
- isSupported: false
4760
- };
4761
- const chainIdNetworkInfo = networkMap.get(network.chainId);
4762
- return {
4763
- name: chainIdNetworkInfo.chainName,
4764
- chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
4765
- nativeCurrency: chainIdNetworkInfo.nativeCurrency,
4766
- isSupported: true
4767
- };
4768
- }, {
4769
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).GET_NETWORK_INFO_ERROR
4770
- });
4771
- }
4772
- async function $de192de6ef100f9f$export$b827d9418aeb5dbd(config, providerPreference, provider, chainId) {
4773
- let currentProvider = provider;
4774
- const { networkMap: networkMap } = config;
4775
- if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${chainId} is not a supported chain`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR);
4776
- if (!currentProvider || !currentProvider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR, {
4777
- details: "Unsupported provider"
4778
- });
4779
- // WT-1146 - Refer to the README in this folder for explantion on the switch network flow
4780
- try {
4781
- await $de192de6ef100f9f$var$switchNetworkInWallet(networkMap, currentProvider, chainId);
4782
- } catch (err) {
4783
- if (err.code === $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE) try {
4784
- await $de192de6ef100f9f$var$addNetworkToWallet(networkMap, currentProvider, chainId);
4785
- // eslint-disable-next-line @typescript-eslint/no-shadow
4786
- } catch (err) {
4787
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled add network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
4788
- }
4789
- else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
2268
+ async isRegisteredOnchain() {
2269
+ const starkPublicKey = await this.signers.starkSigner.getAddress();
2270
+ return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
4790
2271
  }
4791
- currentProvider = await ($c99672cf2294e839$export$fba2f6c3656e07c1)({
4792
- providerPreference: providerPreference
4793
- });
4794
- if ((await currentProvider.getNetwork()).chainId !== chainId) // user didn't actually switch
4795
- throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).USER_REJECTED_REQUEST_ERROR);
4796
- // we can assume that if the above succeeds then user has successfully
4797
- // switched to the network specified
4798
- const newNetwork = networkMap.get(chainId);
4799
- return {
4800
- network: {
4801
- name: newNetwork?.chainName,
4802
- chainId: parseInt(newNetwork?.chainIdHex ?? "", 16),
4803
- nativeCurrency: newNetwork?.nativeCurrency
4804
- },
4805
- provider: currentProvider
4806
- };
4807
- }
4808
- async function $de192de6ef100f9f$export$3043f6442a9ef563(config, { type: type = ($a47e48dd2c04791b$export$1f05a55fe0680cc7).ALL , exclude: exclude }) {
4809
- const { networkMap: networkMap } = config;
4810
- const list = ((/*@__PURE__*/$parcel$interopDefault($497c134ecbc8a50f$exports))).filter((network)=>{
4811
- const allowAllTokens = type === ($a47e48dd2c04791b$export$1f05a55fe0680cc7).ALL;
4812
- const networkNotExcluded = !(exclude || []).map((exc)=>exc.chainId).includes(network.chainId);
4813
- return allowAllTokens && networkNotExcluded;
4814
- });
4815
- const allowedNetworks = [];
4816
- list.forEach((element)=>{
4817
- const newNetwork = networkMap.get(element.chainId);
4818
- if (newNetwork) allowedNetworks.push({
4819
- name: newNetwork.chainName,
4820
- chainId: parseInt(newNetwork.chainIdHex, 16),
4821
- nativeCurrency: newNetwork.nativeCurrency,
4822
- isSupported: true
2272
+ prepareWithdrawal(request) {
2273
+ return prepareWithdrawal({
2274
+ signers: this.signers,
2275
+ withdrawal: request,
2276
+ config: this.config,
4823
2277
  });
4824
- });
4825
- return {
4826
- networks: allowedNetworks
4827
- };
2278
+ }
2279
+ transfer(request) {
2280
+ return transfer({
2281
+ signers: this.signers,
2282
+ request,
2283
+ config: this.config,
2284
+ });
2285
+ }
4828
2286
  }
4829
2287
 
4830
-
4831
-
4832
-
4833
-
4834
- var $cda6003506e4182e$exports = {};
4835
- $cda6003506e4182e$exports = JSON.parse("[{\"chainId\":13373,\"name\":\"IMX\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"FUN token\",\"address\":\"0xd8f1D29a1572FbCeF0B0C9541E50637Ad8804F21\",\"symbol\":\"FUN\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"USDC\",\"address\":\"0x5893A5c7bc615Dfd36D7383366d00FFFca5f7178\",\"symbol\":\"USDC\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"WETH\",\"address\":\"0xD6d9321DCC42377C1fa8cFec665182c463b2392C\",\"symbol\":\"WETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":1,\"name\":\"Ethereum\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF\",\"chainId\":1,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":11155111,\"name\":\"Sep Eth\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":11155111,\"name\":\"Immutable Test token\",\"address\":\"0x40cAdc2BC5d25B9c669B8E09c68eCcb9B80873f7\",\"symbol\":\"TEST\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":1442,\"name\":\"WETH\",\"address\":\"0x4F062A3EAeC3730560aB89b5CE5aC0ab2C5517aE\",\"symbol\":\"WETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x72958b06abdF2701AcE6ceb3cE0B8B1CE11E0851\",\"chainId\":1442,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]}]");
4836
-
4837
-
4838
- const $efe60cea83bfc4e8$var$filterTokenList = ({ type: type , chainId: chainId , exclude: exclude })=>((/*@__PURE__*/$parcel$interopDefault($cda6003506e4182e$exports))).filter((token)=>{
4839
- const skipChainIdCheck = !chainId;
4840
- const chainIdMatches = token.chainId === chainId;
4841
- const tokenNotExcluded = !exclude?.map((excludeToken)=>excludeToken.address).includes(token.address || "");
4842
- const allowAllTokens = type === ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL;
4843
- const tokenAllowedForType = token.tokenFeatures.includes(type);
4844
- return (skipChainIdCheck || chainIdMatches) && tokenNotExcluded && (allowAllTokens || tokenAllowedForType);
4845
- });
4846
- const $efe60cea83bfc4e8$export$473cec51305fdae8 = async ({ type: type = ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL , chainId: chainId , exclude: exclude })=>{
4847
- const filteredTokenList = $efe60cea83bfc4e8$var$filterTokenList({
4848
- type: type,
4849
- chainId: chainId,
4850
- exclude: exclude
4851
- }).map((token)=>({
4852
- name: token.name,
4853
- symbol: token.symbol,
4854
- decimals: token.decimals,
4855
- address: token.address,
4856
- icon: token.icon
4857
- }));
4858
- return {
4859
- tokens: filteredTokenList
4860
- };
2288
+ const WALLET_ACTION = {
2289
+ // TODO: remove once fixed - consider using an enum
2290
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2291
+ SWITCH_CHAIN: 'wallet_switchEthereumChain',
2292
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2293
+ CONNECT: 'eth_requestAccounts',
4861
2294
  };
4862
-
4863
-
4864
-
4865
-
4866
- const $1564e43dde50bb61$export$df96cd8d56be0ab1 = async (config, provider, walletAddress)=>await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4867
- const networkInfo = await ($de192de6ef100f9f$export$79f13b4cfaaf0d09)(config, provider);
4868
- if (!networkInfo.isSupported) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${networkInfo.chainId} is not a supported chain`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR, {
4869
- chainName: networkInfo.name
4870
- });
4871
- const balance = await provider.getBalance(walletAddress);
4872
- return {
4873
- balance: balance,
4874
- formattedBalance: (utils).formatUnits(balance, networkInfo.nativeCurrency.decimals),
4875
- token: networkInfo.nativeCurrency
4876
- };
4877
- }, {
4878
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).GET_BALANCE_ERROR
4879
- });
4880
- async function $1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, contractAddress) {
4881
- return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4882
- const contract = new (Contract)(contractAddress, JSON.stringify(($762782b6c862d954$export$db5daa1b5156ccfe)), provider);
4883
- const name = await contract.name();
4884
- const symbol = await contract.symbol();
4885
- const balance = await contract.balanceOf(walletAddress);
4886
- const decimals = await contract.decimals();
4887
- const formattedBalance = (utils).formatUnits(balance, decimals);
4888
- return {
4889
- balance: balance,
4890
- formattedBalance: formattedBalance,
4891
- token: {
4892
- name: name,
4893
- symbol: symbol,
4894
- decimals: decimals,
4895
- address: contractAddress
4896
- }
4897
- };
4898
- }, {
4899
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).GET_ERC20_BALANCE_ERROR
4900
- });
2295
+ function isRequestableProvider(provider) {
2296
+ return !!provider?.request;
4901
2297
  }
4902
- const $1564e43dde50bb61$export$fee49741664a4d7e = async (config, provider, walletAddress, chainId)=>{
4903
- if (!Object.values(($a47e48dd2c04791b$export$c06e1e7429de6283)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`ChainId ${chainId} is not supported`, ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).CHAIN_NOT_SUPPORTED_ERROR);
4904
- if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("provider object is missing request function", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_REQUEST_MISSING_ERROR);
4905
- const tokenList = await ($efe60cea83bfc4e8$export$473cec51305fdae8)({
4906
- type: ($08d5ddc39acd6833$export$fd9b17d87f4121d2).ALL,
4907
- chainId: chainId
4908
- });
4909
- const allBalancePromises = [];
4910
- allBalancePromises.push($1564e43dde50bb61$export$df96cd8d56be0ab1(config, provider, walletAddress));
4911
- tokenList.tokens.filter((token)=>token.address).forEach((token)=>allBalancePromises.push($1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, token.address ?? "")));
4912
- const balanceResults = await Promise.allSettled(allBalancePromises);
4913
- const getBalanceResults = balanceResults.filter((result)=>result.status === "fulfilled").map((fulfilledResult)=>fulfilledResult.value);
4914
- return {
4915
- balances: getBalanceResults
4916
- };
4917
- };
4918
-
4919
-
4920
-
4921
-
4922
-
4923
-
4924
-
4925
-
4926
-
4927
- var $6f3c55a615003cbf$exports = {};
4928
- $6f3c55a615003cbf$exports = JSON.parse('[{"connectionProvider":"metamask","icon":"some-icon-url","name":"MetaMask","description":"complete web3 wallet solution","platform":["desktop"]},{"connectionProvider":"passport","icon":"pp-icon","name":"Passport","description":"Web3 with your email!","platform":["mobile","desktop"]},{"connectionProvider":"gamestop","icon":"gme-icon","name":"GameStop","description":"Never stopping the game!","platform":["mobile"]}]');
4929
-
4930
-
4931
- async function $5cdde2ffe6360fec$export$a822caa90d7eef09({ type: type = ($4f91c5f280efe242$export$a75605c67ea83a5a).ALL , exclude: exclude }) {
4932
- // todo:For async API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
4933
- const filteredWalletsList = ((/*@__PURE__*/$parcel$interopDefault($6f3c55a615003cbf$exports))).filter((wallet)=>{
4934
- const walletNotExcluded = !exclude?.map((excludeWallet)=>excludeWallet.connectionProvider).includes(wallet.connectionProvider);
4935
- const allowAllWallets = type === ($4f91c5f280efe242$export$a75605c67ea83a5a).ALL;
4936
- const walletsAllowedForType = wallet.platform.includes(type);
4937
- return walletNotExcluded && (allowAllWallets || walletsAllowedForType);
4938
- }).map((wallet)=>{
4939
- const { platform: platform , ...walletInfo } = wallet;
4940
- return walletInfo;
4941
- });
4942
- return {
4943
- wallets: filteredWalletsList
4944
- };
2298
+ async function connectProvider(provider, chainID) {
2299
+ await provider.request({ method: WALLET_ACTION.CONNECT });
2300
+ if (chainID) {
2301
+ await provider.request({
2302
+ method: WALLET_ACTION.SWITCH_CHAIN,
2303
+ params: [{ chainId: `0x${chainID.toString(16)}` }],
2304
+ });
2305
+ }
4945
2306
  }
4946
2307
 
4947
-
4948
-
4949
-
4950
-
4951
-
4952
- const $dbe95599a4661140$export$8e0e7ffc78696d30 = async (params)=>{
4953
- const { provider: provider , transaction: transaction } = params;
4954
- return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4955
- const transactionResponse = await provider.getSigner().sendTransaction(transaction);
4956
- return {
4957
- transactionResponse: transactionResponse
4958
- };
4959
- }, {
4960
- type: ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).TRANSACTION_ERROR
4961
- });
2308
+ const ERRORS = {
2309
+ // TODO: remove once fixed - consider using something in line with the naming convention
2310
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2311
+ PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
4962
2312
  };
2313
+ async function connect$1({ chainID, }) {
2314
+ const provider = (await detectEthereumProvider());
2315
+ if (!isRequestableProvider(provider)) {
2316
+ throw new Error(ERRORS.PROVIDER_NOT_FOUND);
2317
+ }
2318
+ await connectProvider(provider, chainID);
2319
+ // NOTE: if we want to listen to Metamask events in the future, we can add a
2320
+ // listener here.
2321
+ return new ethers.providers.Web3Provider(provider);
2322
+ }
4963
2323
 
2324
+ const COMMUNICATION_TYPE = 'message';
2325
+ var RequestEventType;
2326
+ (function (RequestEventType) {
2327
+ RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
2328
+ RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
2329
+ RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
2330
+ RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
2331
+ })(RequestEventType || (RequestEventType = {}));
2332
+ var ResponseEventType;
2333
+ (function (ResponseEventType) {
2334
+ ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
2335
+ ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
2336
+ ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
2337
+ ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
2338
+ })(ResponseEventType || (ResponseEventType = {}));
4964
2339
 
4965
-
4966
-
4967
-
4968
-
4969
-
4970
-
4971
- class $4013c5c91bb535f6$export$47a4ed4a38b9eecf extends Error {
4972
- constructor(message){
4973
- super(message);
4974
- this.message = message;
4975
- }
4976
- }
4977
- class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
4978
- constructor(config){
4979
- // validate input
4980
- if (!Object.values((Environment)).includes(config.baseConfig.environment)) throw new $4013c5c91bb535f6$export$47a4ed4a38b9eecf("Invalid checkout configuration of environment");
4981
- this.environment = config.baseConfig.environment;
4982
- this.networkMap = config.baseConfig.environment === (Environment).PRODUCTION ? ($a47e48dd2c04791b$export$6f24f3cef7d501c4) : ($a47e48dd2c04791b$export$3e81fc0987227f10);
2340
+ function postRequestMessage(iframe, payload) {
2341
+ if (iframe && iframe.contentWindow) {
2342
+ iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
4983
2343
  }
4984
2344
  }
4985
2345
 
4986
-
4987
-
4988
-
4989
- class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
4990
- constructor(config = ($bc2bfebf768286d3$export$6a2ba3c3bd042990)){
4991
- this.config = new ($4013c5c91bb535f6$export$4823433c4a67bbc6)(config);
4992
- }
4993
- /**
4994
- * Check if a wallet is connected to the current application
4995
- * without requesting permission from the wallet and hence triggering a connect popup.
4996
- * @param {CheckConnectionParams} params - The necessary data required to verify a wallet connection status.
4997
- * @returns Wallet connection status details.
4998
- * @throws {@link ErrorType}
4999
- */ // eslint-disable-next-line class-methods-use-this
5000
- async checkIsWalletConnected(params) {
5001
- return $c99672cf2294e839$export$2d040992269b4717(params.providerPreference);
5002
- }
5003
- /**
5004
- * Establish a connection with a wallet provider such as MetaMask and returns the provider object and the current network details.
5005
- * @param {ConnectParams} params - The necessary data required to establish a connection with a wallet provider.
5006
- * @returns Wallet provider and current network information.
5007
- * @throws {@link ErrorType}
5008
- */ async connect(params) {
5009
- this.providerPreference = params.providerPreference;
5010
- const provider = await $c99672cf2294e839$export$fba2f6c3656e07c1(params);
5011
- const networkInfo = await $de192de6ef100f9f$export$79f13b4cfaaf0d09(this.config, provider);
5012
- return {
5013
- provider: provider,
5014
- network: networkInfo
5015
- };
5016
- }
5017
- /**
5018
- * Switch the currently connected wallet to a new network.
5019
- * @param {SwitchNetworkParams} params - The necessary data required to switch network.
5020
- * @returns The new network information.
5021
- * @throws {@link ErrorType}
5022
- */ async switchNetwork(params) {
5023
- if (!this.providerPreference) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("connect should be called before switchNetwork to set the provider preference", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).PROVIDER_PREFERENCE_ERROR);
5024
- return await $de192de6ef100f9f$export$b827d9418aeb5dbd(this.config, this.providerPreference, params.provider, params.chainId);
5025
- }
5026
- /**
5027
- * Fetch the balance of the native token of the current connected network or,
5028
- * if a contract address is provided, it will return the balance of that ERC20 token. For example,
5029
- * if the wallet is connected to the Ethereum Mainnet then the function gets the wallet ETH L1 balance.
5030
- * @param {GetBalanceParams} params - The necessary data required to fetch the wallet balance.
5031
- * @returns Native token balance for the given wallet.
5032
- * @throws {@link ErrorType}
5033
- */ async getBalance(params) {
5034
- if (!params.contractAddress || params.contractAddress === "") return await $1564e43dde50bb61$export$df96cd8d56be0ab1(this.config, params.provider, params.walletAddress);
5035
- return await $1564e43dde50bb61$export$60e0fe116a0e6ed0(params.provider, params.walletAddress, params.contractAddress);
5036
- }
5037
- /**
5038
- * Fetch all available balances (ERC20 & Native) of the current connected network of the given wallet.
5039
- * It will loop through the list of allowed tokens and check for balance on each one.
5040
- * @param {GetAllBalancesParams} params - The necessary data required to fetch all the wallet balances.
5041
- * @returns List of tokens balance for the given wallet.
5042
- * @throws {@link ErrorType}
5043
- */ async getAllBalances(params) {
5044
- return $1564e43dde50bb61$export$fee49741664a4d7e(this.config, params.provider, params.walletAddress, params.chainId);
2346
+ function messageResponseListener(iframe, event, eventType, callback) {
2347
+ if (iframe && event.source !== iframe.contentWindow) {
2348
+ return;
5045
2349
  }
5046
- /**
5047
- * Fetch the list of available networks that a wallet can add or/and switch to.
5048
- * @param {GetNetworkAllowListParams} params - The necessary data required to fetch the list of available networks.
5049
- * @returns List of networks.
5050
- * @throws {@link ErrorType}
5051
- */ async getNetworkAllowList(params) {
5052
- return await $de192de6ef100f9f$export$3043f6442a9ef563(this.config, params);
2350
+ const l2WalletMessage = event.data;
2351
+ if (l2WalletMessage.type !== eventType) {
2352
+ return;
5053
2353
  }
5054
- /**
5055
- * Get the list of tokens which are allowed to be used with the product.
5056
- * @param {GetTokenAllowListParams} params - The necessary data required to fetch the list of allowed tokens.
5057
- * @returns List of allowed tokens.
5058
- * @throws {@link ErrorType}
5059
- */ // eslint-disable-next-line class-methods-use-this
5060
- async getTokenAllowList(params) {
5061
- return await $efe60cea83bfc4e8$export$473cec51305fdae8(params);
2354
+ callback(l2WalletMessage.details);
2355
+ }
2356
+
2357
+ class ImxSigner {
2358
+ publicAddress;
2359
+ iframe;
2360
+ constructor(publicAddress, iframe) {
2361
+ this.publicAddress = publicAddress;
2362
+ this.iframe = iframe;
5062
2363
  }
5063
- /**
5064
- * Fetch the list of wallets which are available to connect with.
5065
- * @param {GetWalletAllowListParams} params - The necessary data required to fetch the list of allowed wallets.
5066
- * @returns List of allowed wallets.
5067
- * @throws {@link ErrorType}
5068
- */ // eslint-disable-next-line class-methods-use-this
5069
- async getWalletAllowList(params) {
5070
- return await $5cdde2ffe6360fec$export$a822caa90d7eef09(params);
2364
+ getAddress() {
2365
+ return this.publicAddress;
5071
2366
  }
5072
- /**
5073
- * Send a generic transaction to the provider.
5074
- * @param {SendTransactionParams} params - The necessary data required to send a transaction.
5075
- * @returns Transaction response.
5076
- * @throws {@link ErrorType}
5077
- * @remarks
5078
- * Further documenation can be found at [MetaMask | Sending Transactions](https://docs.metamask.io/guide/sending-transactions.html).
5079
- */ // eslint-disable-next-line class-methods-use-this
5080
- async sendTransaction(params) {
5081
- return await $dbe95599a4661140$export$8e0e7ffc78696d30(params);
2367
+ signMessage(rawMessage) {
2368
+ return new Promise((resolve, reject) => {
2369
+ const listener = (event) => {
2370
+ messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
2371
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2372
+ if (!messageDetails.success) {
2373
+ reject(new Error(messageDetails.error?.message));
2374
+ }
2375
+ resolve(messageDetails.data.signedMessage);
2376
+ });
2377
+ };
2378
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2379
+ postRequestMessage(this.iframe, {
2380
+ type: RequestEventType.SIGN_MESSAGE_REQUEST,
2381
+ details: { starkPublicKey: this.publicAddress, message: rawMessage },
2382
+ });
2383
+ });
5082
2384
  }
5083
- /**
5084
- * Get network information about the currently selected network.
5085
- * @param {GetNetworkParams} params - The necessary data required to get the current network information.
5086
- * @returns Network details.
5087
- * @throws {@link ErrorType}
5088
- */ async getNetworkInfo(params) {
5089
- return await $de192de6ef100f9f$export$79f13b4cfaaf0d09(this.config, params.provider);
2385
+ getIFrame() {
2386
+ return this.iframe;
5090
2387
  }
5091
2388
  }
5092
2389
 
5093
- function $parcel$export(e, n, v, s) {
5094
- Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
2390
+ const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
2391
+ const IMX_WALLET_IFRAME_HOSTS = {
2392
+ [Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
2393
+ [Environment.PRODUCTION]: 'https://wallets.immutable.com',
2394
+ };
2395
+ const IMX_WALLET_IFRAME_STYLE = 'display: none;';
2396
+ function getIFrame() {
2397
+ return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
5095
2398
  }
5096
- // Definitions | Events
5097
- var $207ed853f11d19d5$exports = {};
5098
-
5099
- $parcel$export($207ed853f11d19d5$exports, "IMTBLWidgetEvents", () => $207ed853f11d19d5$export$5a0ace85cae72d45);
5100
- /**
5101
- * Enum representing the events emitted by the widgets.
5102
- */ let $207ed853f11d19d5$export$5a0ace85cae72d45;
5103
- (function(IMTBLWidgetEvents) {
5104
- IMTBLWidgetEvents["IMTBL_CONNECT_WIDGET_EVENT"] = "imtbl-connect-widget";
5105
- IMTBLWidgetEvents["IMTBL_WALLET_WIDGET_EVENT"] = "imtbl-wallet-widget";
5106
- IMTBLWidgetEvents["IMTBL_SWAP_WIDGET_EVENT"] = "imtbl-swap-widget";
5107
- IMTBLWidgetEvents["IMTBL_BRIDGE_WIDGET_EVENT"] = "imtbl-bridge-widget";
5108
- IMTBLWidgetEvents["IMTBL_BUY_WIDGET_EVENT"] = "imtbl-buy-widget";
5109
- IMTBLWidgetEvents["IMTBL_ONRAMP_WIDGET_EVENT"] = "imtbl-onramp-widget";
5110
- })($207ed853f11d19d5$export$5a0ace85cae72d45 || ($207ed853f11d19d5$export$5a0ace85cae72d45 = {}));
5111
-
5112
-
5113
- var $a85ecdbd885c58ad$exports = {};
5114
-
5115
- $parcel$export($a85ecdbd885c58ad$exports, "ConnectEventType", () => $a85ecdbd885c58ad$export$e72e7f9969a47dd3);
5116
- let $a85ecdbd885c58ad$export$e72e7f9969a47dd3;
5117
- (function(ConnectEventType) {
5118
- ConnectEventType["SUCCESS"] = "success";
5119
- ConnectEventType["FAILURE"] = "failure";
5120
- ConnectEventType["CLOSE_WIDGET"] = "close-widget";
5121
- })($a85ecdbd885c58ad$export$e72e7f9969a47dd3 || ($a85ecdbd885c58ad$export$e72e7f9969a47dd3 = {}));
5122
-
5123
-
5124
- var $77b6aac5c353d4a9$exports = {};
5125
-
5126
- $parcel$export($77b6aac5c353d4a9$exports, "WalletEventType", () => $77b6aac5c353d4a9$export$d9be06b70b28c742);
5127
- let $77b6aac5c353d4a9$export$d9be06b70b28c742;
5128
- (function(WalletEventType) {
5129
- WalletEventType["CLOSE_WIDGET"] = "close-widget";
5130
- WalletEventType["NETWORK_SWITCH"] = "network-switch";
5131
- WalletEventType["ADD_COINS"] = "add-coins";
5132
- WalletEventType["REQUEST_SWAP"] = "request-swap";
5133
- WalletEventType["REQUEST_BRIDGE"] = "request-bridge";
5134
- WalletEventType["REQUEST_ONRAMP"] = "request-onramp";
5135
- WalletEventType["DISCONNECT_WALLET"] = "disconnect-wallet";
5136
- })($77b6aac5c353d4a9$export$d9be06b70b28c742 || ($77b6aac5c353d4a9$export$d9be06b70b28c742 = {}));
5137
-
5138
-
5139
- var $53d219e7f6bf0cd6$exports = {};
5140
-
5141
- $parcel$export($53d219e7f6bf0cd6$exports, "SwapEventType", () => $53d219e7f6bf0cd6$export$140a49745ab55563);
5142
- /**
5143
- * Represents an event object emitted by the Swap Widget.
5144
- * @property {SwapEventType} type - The type of the event.
5145
- * @property {T} data - The data contained in the event.
5146
- */ let $53d219e7f6bf0cd6$export$140a49745ab55563;
5147
- (function(SwapEventType) {
5148
- SwapEventType["SUCCESS"] = "success";
5149
- SwapEventType["FAILURE"] = "failure";
5150
- SwapEventType["CLOSE_WIDGET"] = "close-widget";
5151
- })($53d219e7f6bf0cd6$export$140a49745ab55563 || ($53d219e7f6bf0cd6$export$140a49745ab55563 = {}));
5152
-
5153
-
5154
- var $15cc9e120aa6f3bf$exports = {};
5155
-
5156
- $parcel$export($15cc9e120aa6f3bf$exports, "BridgeEventType", () => $15cc9e120aa6f3bf$export$d1bfa21f7c76447a);
5157
- /**
5158
- * Represents an event object emitted by the Bridge Widget.
5159
- * @property {BridgeEventType} type - The type of the event.
5160
- * @property {T} data - The data associated with the event.
5161
- */ let $15cc9e120aa6f3bf$export$d1bfa21f7c76447a;
5162
- (function(BridgeEventType) {
5163
- BridgeEventType["CLOSE_WIDGET"] = "close-widget";
5164
- BridgeEventType["SUCCESS"] = "success";
5165
- BridgeEventType["FAILURE"] = "failure";
5166
- })($15cc9e120aa6f3bf$export$d1bfa21f7c76447a || ($15cc9e120aa6f3bf$export$d1bfa21f7c76447a = {}));
5167
-
5168
-
5169
- var $98cbcca465beec95$exports = {};
5170
-
5171
- $parcel$export($98cbcca465beec95$exports, "BuyEventType", () => $98cbcca465beec95$export$90db5fe1be5993c1);
5172
- /**
5173
- * Represents an event object emitted by the Buy Widget.
5174
- * @property {BuyEventType} type - The type of the event.
5175
- * @property {T} data - The data contained in the event.
5176
- */ let $98cbcca465beec95$export$90db5fe1be5993c1;
5177
- (function(BuyEventType) {
5178
- BuyEventType["SUCCESS"] = "success";
5179
- BuyEventType["FAILURE"] = "failure";
5180
- BuyEventType["NOT_CONNECTED"] = "not_connected";
5181
- BuyEventType["CLOSE"] = "close";
5182
- })($98cbcca465beec95$export$90db5fe1be5993c1 || ($98cbcca465beec95$export$90db5fe1be5993c1 = {}));
5183
-
5184
-
5185
- var $66ceef112c0ee49e$exports = {};
5186
-
5187
- $parcel$export($66ceef112c0ee49e$exports, "OnRampEventType", () => $66ceef112c0ee49e$export$66ec39c0924078d8);
5188
- let $66ceef112c0ee49e$export$66ec39c0924078d8;
5189
- $66ceef112c0ee49e$export$66ec39c0924078d8 || ($66ceef112c0ee49e$export$66ec39c0924078d8 = {});
5190
- /* eslint-disable @typescript-eslint/naming-convention */
5191
-
5192
- var $14d7a2bbb79e0dae$exports = {};
5193
-
5194
- $parcel$export($14d7a2bbb79e0dae$exports, "Network", () => $14d7a2bbb79e0dae$export$95be4ae94445245a);
5195
- $parcel$export($14d7a2bbb79e0dae$exports, "WidgetTheme", () => $14d7a2bbb79e0dae$export$c88931fdc51854eb);
5196
- $parcel$export($14d7a2bbb79e0dae$exports, "CheckoutWidgetTagNames", () => $14d7a2bbb79e0dae$export$75be0f6af9650f2c);
5197
- /**
5198
- * Enum representing the networks supported by Checkout.
5199
- */ let $14d7a2bbb79e0dae$export$95be4ae94445245a;
5200
- (function(Network) {
5201
- Network["ETHEREUM"] = "Ethereum";
5202
- Network["SEPOLIA"] = "Sepolia";
5203
- Network["IMTBL_ZKEVM_TESTNET"] = "Immutable zkEVM Testnet";
5204
- Network["IMTBL_ZKEVM_DEVNET"] = "Immutable zkEVM Devnet";
5205
- Network["POLYGON_ZKEVM_TESTNET"] = "Polygon zkEVM Testnet";
5206
- Network["POLYGON_ZKEVM"] = "Polygon zkEVM";
5207
- })($14d7a2bbb79e0dae$export$95be4ae94445245a || ($14d7a2bbb79e0dae$export$95be4ae94445245a = {}));
5208
- let $14d7a2bbb79e0dae$export$c88931fdc51854eb;
5209
- (function(WidgetTheme) {
5210
- WidgetTheme["LIGHT"] = "light";
5211
- WidgetTheme["DARK"] = "dark";
5212
- WidgetTheme["CUSTOM"] = "custom";
5213
- })($14d7a2bbb79e0dae$export$c88931fdc51854eb || ($14d7a2bbb79e0dae$export$c88931fdc51854eb = {}));
5214
- let $14d7a2bbb79e0dae$export$75be0f6af9650f2c;
5215
- (function(CheckoutWidgetTagNames) {
5216
- CheckoutWidgetTagNames["CONNECT"] = "imtbl-connect";
5217
- CheckoutWidgetTagNames["WALLET"] = "imtbl-wallet";
5218
- CheckoutWidgetTagNames["SWAP"] = "imtbl-swap";
5219
- CheckoutWidgetTagNames["BUY"] = "imtbl-buy";
5220
- CheckoutWidgetTagNames["BRIDGE"] = "imtbl-bridge";
5221
- CheckoutWidgetTagNames["EXAMPLE"] = "imtbl-example";
5222
- })($14d7a2bbb79e0dae$export$75be0f6af9650f2c || ($14d7a2bbb79e0dae$export$75be0f6af9650f2c = {}));
5223
-
5224
-
5225
- var $1f969328e5988c99$exports = {};
5226
-
5227
- $parcel$export($1f969328e5988c99$exports, "BridgeReact", () => $1f969328e5988c99$export$30f61ebf204c69f6);
5228
-
5229
-
5230
- function $1f969328e5988c99$export$30f61ebf204c69f6(props) {
5231
- const { providerPreference: providerPreference , fromContractAddress: fromContractAddress , amount: amount , fromNetwork: fromNetwork } = props;
5232
- const config = window.ImtblCheckoutWidgetConfig;
5233
- return /*#__PURE__*/ (jsx)("imtbl-bridge", {
5234
- widgetConfig: config,
5235
- providerPreference: providerPreference,
5236
- fromContractAddress: fromContractAddress ?? "",
5237
- fromNetwork: fromNetwork ?? "",
5238
- amount: amount ?? ""
2399
+ async function setupIFrame(env) {
2400
+ return new Promise((resolve) => {
2401
+ const iframe = document.createElement('iframe');
2402
+ iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
2403
+ iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
2404
+ iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
2405
+ document.body.appendChild(iframe);
2406
+ iframe.onload = () => resolve(iframe);
5239
2407
  });
5240
2408
  }
5241
-
5242
-
5243
- var $f22931ca9e2f35b6$exports = {};
5244
-
5245
- $parcel$export($f22931ca9e2f35b6$exports, "BuyReact", () => $f22931ca9e2f35b6$export$d13582032b79b401);
5246
-
5247
-
5248
- function $f22931ca9e2f35b6$export$d13582032b79b401(props) {
5249
- const { providerPreference: providerPreference , orderId: orderId } = props;
5250
- const config = window.ImtblCheckoutWidgetConfig;
5251
- return /*#__PURE__*/ (jsx)("imtbl-buy", {
5252
- widgetConfig: config,
5253
- providerPreference: providerPreference,
5254
- orderId: orderId
5255
- });
2409
+ async function getOrSetupIFrame(env) {
2410
+ const iframe = getIFrame();
2411
+ if (iframe)
2412
+ return iframe;
2413
+ return await setupIFrame(env);
5256
2414
  }
5257
2415
 
5258
-
5259
- var $f2083cd30e2f5c56$exports = {};
5260
-
5261
- $parcel$export($f2083cd30e2f5c56$exports, "ConnectReact", () => $f2083cd30e2f5c56$export$49d62957f420a1e2);
5262
-
5263
-
5264
- function $f2083cd30e2f5c56$export$49d62957f420a1e2(props) {
5265
- const { providerPreference: providerPreference } = props;
5266
- const config = window.ImtblCheckoutWidgetConfig;
5267
- return /*#__PURE__*/ (jsx)("imtbl-connect", {
5268
- widgetConfig: config,
5269
- providerPreference: providerPreference ?? "metamask"
2416
+ const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
2417
+ const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
2418
+ async function connect(l1Provider, env) {
2419
+ const l1Signer = l1Provider.getSigner();
2420
+ const address = await l1Signer.getAddress();
2421
+ const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
2422
+ const iframe = await getOrSetupIFrame(env);
2423
+ return new Promise((resolve, reject) => {
2424
+ const listener = (event) => {
2425
+ messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
2426
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2427
+ if (!messageDetails.success) {
2428
+ reject(new Error(CONNECTION_FAILED_ERROR));
2429
+ }
2430
+ resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
2431
+ });
2432
+ };
2433
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2434
+ postRequestMessage(iframe, {
2435
+ type: RequestEventType.CONNECT_WALLET_REQUEST,
2436
+ details: { ethAddress: address, signature },
2437
+ });
5270
2438
  });
5271
2439
  }
5272
-
5273
-
5274
- var $a4fbb8e3a6aeff58$exports = {};
5275
-
5276
- $parcel$export($a4fbb8e3a6aeff58$exports, "SwapReact", () => $a4fbb8e3a6aeff58$export$971e031379577f4);
5277
- /* eslint-disable max-len */
5278
-
5279
- function $a4fbb8e3a6aeff58$export$971e031379577f4(props) {
5280
- const { providerPreference: providerPreference , fromContractAddress: fromContractAddress , amount: amount , toContractAddress: toContractAddress } = props;
5281
- const config = window.ImtblCheckoutWidgetConfig;
5282
- return /*#__PURE__*/ (jsx)("imtbl-swap", {
5283
- widgetConfig: config,
5284
- providerPreference: providerPreference,
5285
- fromContractAddress: fromContractAddress ?? "",
5286
- toContractAddress: toContractAddress ?? "",
5287
- amount: amount ?? ""
2440
+ async function disconnect(imxSigner) {
2441
+ const iframe = imxSigner.getIFrame();
2442
+ return new Promise((resolve, reject) => {
2443
+ const listener = (event) => {
2444
+ messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
2445
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2446
+ if (!messageDetails.success && messageDetails.error) {
2447
+ reject(messageDetails.error);
2448
+ }
2449
+ iframe.remove();
2450
+ resolve();
2451
+ });
2452
+ };
2453
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2454
+ postRequestMessage(iframe, {
2455
+ type: RequestEventType.DISCONNECT_WALLET_REQUEST,
2456
+ details: { starkPublicKey: imxSigner.getAddress() },
2457
+ });
5288
2458
  });
5289
2459
  }
5290
2460
 
5291
-
5292
- var $89d55ace0f8f1c07$exports = {};
5293
-
5294
- $parcel$export($89d55ace0f8f1c07$exports, "WalletReact", () => $89d55ace0f8f1c07$export$ceaac94f34dba154);
5295
-
5296
-
5297
- function $89d55ace0f8f1c07$export$ceaac94f34dba154(props) {
5298
- const { providerPreference: providerPreference , useConnectWidget: useConnectWidget } = props;
5299
- const config = window.ImtblCheckoutWidgetConfig;
5300
- return /*#__PURE__*/ (jsx)("imtbl-wallet", {
5301
- widgetConfig: config,
5302
- useConnectWidget: useConnectWidget?.toString(),
5303
- providerPreference: providerPreference ?? "metamask"
5304
- });
2461
+ var ProviderErrorType;
2462
+ (function (ProviderErrorType) {
2463
+ ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
2464
+ ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
2465
+ })(ProviderErrorType || (ProviderErrorType = {}));
2466
+ class ProviderError extends Error {
2467
+ type;
2468
+ constructor(message, type) {
2469
+ super(message);
2470
+ this.type = type;
2471
+ }
5305
2472
  }
2473
+ const withProviderError = async (fn, customError) => {
2474
+ try {
2475
+ return await fn();
2476
+ }
2477
+ catch (error) {
2478
+ const errorMessage = customError.message || `${error.message}` || 'UnknownError';
2479
+ throw new ProviderError(errorMessage, customError.type);
2480
+ }
2481
+ };
5306
2482
 
5307
-
5308
- var $d087956fd1002f80$exports = {};
5309
-
5310
- $parcel$export($d087956fd1002f80$exports, "ExampleReact", () => $d087956fd1002f80$export$fa517eee6594d26c);
5311
-
5312
-
5313
-
5314
- function $d087956fd1002f80$export$fa517eee6594d26c(props) {
5315
- const { providerPreference: // eslint-disable-next-line @typescript-eslint/no-unused-vars
5316
- providerPreference , environment: environment , theme: theme } = props;
5317
- return /*#__PURE__*/ (jsx)("imtbl-example", {
5318
- environment: environment ?? (Environment).SANDBOX,
5319
- theme: theme ?? "dark",
5320
- providerPreference: providerPreference
5321
- });
2483
+ class MetaMaskIMXProvider extends GenericIMXProvider {
2484
+ static imxSigner;
2485
+ static async connect(config) {
2486
+ return await withProviderError(async () => {
2487
+ const metaMaskProvider = await connect$1({
2488
+ chainID: config.immutableXConfig.ethConfiguration.chainID,
2489
+ });
2490
+ this.imxSigner = await connect(metaMaskProvider, config.baseConfig.environment);
2491
+ return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
2492
+ }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
2493
+ }
2494
+ static async disconnect() {
2495
+ if (!this.imxSigner) {
2496
+ throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2497
+ }
2498
+ return withProviderError(async () => {
2499
+ await disconnect(this.imxSigner);
2500
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
2501
+ }
2502
+ static async signMessage(message) {
2503
+ if (!this.imxSigner) {
2504
+ throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2505
+ }
2506
+ return withProviderError(async () => await this.imxSigner.signMessage(message), { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
2507
+ }
5322
2508
  }
5323
2509
 
5324
-
5325
- var $430e3eda76fa4d5f$exports = {};
5326
-
5327
- $parcel$export($430e3eda76fa4d5f$exports, "CheckoutWidgets", () => $430e3eda76fa4d5f$export$af210a0808087845);
5328
- $parcel$export($430e3eda76fa4d5f$exports, "UpdateConfig", () => $430e3eda76fa4d5f$export$bf1548ba7e61c17f);
5329
- $parcel$export($430e3eda76fa4d5f$exports, "SetProvider", () => $430e3eda76fa4d5f$export$931068bc678f0d73);
5330
- function $430e3eda76fa4d5f$export$af210a0808087845(config) {
5331
- const checkoutWidgetJS = document.createElement("script");
5332
- checkoutWidgetJS.setAttribute("src", "http://localhost:3000/lib/js/imtbl-checkout.js");
5333
- document.head.appendChild(checkoutWidgetJS);
5334
- window.ImtblCheckoutWidgetConfig = JSON.stringify(config);
5335
- }
5336
- function $430e3eda76fa4d5f$export$bf1548ba7e61c17f(config) {
5337
- window.ImtblCheckoutWidgetConfig = JSON.stringify(config);
5338
- }
5339
- function $430e3eda76fa4d5f$export$931068bc678f0d73(tagName, provider) {
5340
- if (!provider) {
5341
- // eslint-disable-next-line no-console
5342
- console.error("no provider parsed");
5343
- return;
5344
- }
5345
- const elements = document.getElementsByTagName(tagName);
5346
- const widget = elements[0];
5347
- let attempts = 0;
5348
- const maxAttempts = 10;
5349
- let timer;
5350
- const attemptToSetProvider = ()=>{
5351
- try {
5352
- widget.setProvider(provider);
5353
- window.clearInterval(timer);
5354
- } catch (err) {
5355
- attempts++;
5356
- if (attempts >= maxAttempts) {
5357
- window.clearInterval(timer);
5358
- // eslint-disable-next-line no-console
5359
- console.error("failed to set the provider");
2510
+ class ProviderConfiguration {
2511
+ immutableXConfig;
2512
+ baseConfig;
2513
+ constructor({ baseConfig, overrides }) {
2514
+ this.baseConfig = baseConfig;
2515
+ if (overrides) {
2516
+ this.immutableXConfig = overrides.immutableXConfig;
2517
+ }
2518
+ else {
2519
+ // TODO: remove once a sensible default is chosen
2520
+ // eslint-disable-next-line default-case
2521
+ switch (baseConfig.environment) {
2522
+ case Environment.SANDBOX: {
2523
+ this.immutableXConfig = Config.SANDBOX;
2524
+ break;
2525
+ }
2526
+ case Environment.PRODUCTION: {
2527
+ this.immutableXConfig = Config.PRODUCTION;
2528
+ break;
2529
+ }
5360
2530
  }
5361
2531
  }
5362
- };
5363
- timer = window.setInterval(attemptToSetProvider, 10);
5364
- attemptToSetProvider();
2532
+ }
5365
2533
  }
5366
2534
 
5367
- export { $15cc9e120aa6f3bf$export$d1bfa21f7c76447a as BridgeEventType, $1f969328e5988c99$export$30f61ebf204c69f6 as BridgeReact, $98cbcca465beec95$export$90db5fe1be5993c1 as BuyEventType, $f22931ca9e2f35b6$export$d13582032b79b401 as BuyReact, $a47e48dd2c04791b$export$c06e1e7429de6283 as ChainId, $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 as Checkout, $a8bc256d81a5e2c1$export$e3dc0620abde7f5a as CheckoutErrorType, $14d7a2bbb79e0dae$export$75be0f6af9650f2c as CheckoutWidgetTagNames, $430e3eda76fa4d5f$export$af210a0808087845 as CheckoutWidgets, $a85ecdbd885c58ad$export$e72e7f9969a47dd3 as ConnectEventType, $f2083cd30e2f5c56$export$49d62957f420a1e2 as ConnectReact, $d176a05e966364ba$export$3bfad4d03ada24c4 as ConnectionProviders, Environment, $d087956fd1002f80$export$fa517eee6594d26c as ExampleReact, GenericIMXProvider, $207ed853f11d19d5$export$5a0ace85cae72d45 as IMTBLWidgetEvents, ImmutableConfiguration, ImmutableXClient, MetaMaskIMXProvider, $14d7a2bbb79e0dae$export$95be4ae94445245a as Network, $a47e48dd2c04791b$export$1f05a55fe0680cc7 as NetworkFilterTypes, $66ceef112c0ee49e$export$66ec39c0924078d8 as OnRampEventType, Orderbook, Passport, PassportError, ProviderConfiguration, $430e3eda76fa4d5f$export$931068bc678f0d73 as SetProvider, $53d219e7f6bf0cd6$export$140a49745ab55563 as SwapEventType, $a4fbb8e3a6aeff58$export$971e031379577f4 as SwapReact, $08d5ddc39acd6833$export$fd9b17d87f4121d2 as TokenFilterTypes, $430e3eda76fa4d5f$export$bf1548ba7e61c17f as UpdateConfig, $77b6aac5c353d4a9$export$d9be06b70b28c742 as WalletEventType, $4f91c5f280efe242$export$a75605c67ea83a5a as WalletFilterTypes, $89d55ace0f8f1c07$export$ceaac94f34dba154 as WalletReact, $14d7a2bbb79e0dae$export$c88931fdc51854eb as WidgetTheme, module };
2535
+ export { Environment, GenericIMXProvider, ImmutableConfiguration, ImmutableXClient, MetaMaskIMXProvider, Passport, PassportError, ProviderConfiguration };