anchor-sdk 0.1.41-internal.6 → 0.1.42-beta.1
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/AnchorApiClientV2.d.ts +3 -2
- package/dist/AnchorApiClientV2.d.ts.map +1 -0
- package/dist/AnchorERC1155Client.d.ts +1 -0
- package/dist/AnchorERC1155Client.d.ts.map +1 -0
- package/dist/AnchorPayClient.d.ts +1 -0
- package/dist/AnchorPayClient.d.ts.map +1 -0
- package/dist/abi/AnchorERC1155.d.ts +1 -0
- package/dist/abi/AnchorERC1155.d.ts.map +1 -0
- package/dist/constants.d.ts +2 -1
- package/dist/constants.d.ts.map +1 -0
- package/dist/generated/Api.d.ts +1 -0
- package/dist/generated/Api.d.ts.map +1 -0
- package/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -1379
- package/dist/index.js.map +18 -0
- package/dist/typechain/AnchorERC1155.d.ts +3 -2
- package/dist/typechain/AnchorERC1155.d.ts.map +1 -0
- package/dist/typechain/AnchorPay.d.ts +3 -2
- package/dist/typechain/AnchorPay.d.ts.map +1 -0
- package/dist/typechain/common.d.ts +2 -1
- package/dist/typechain/common.d.ts.map +1 -0
- package/dist/typechain/factories/AnchorERC1155__factory.d.ts +1 -0
- package/dist/typechain/factories/AnchorERC1155__factory.d.ts.map +1 -0
- package/dist/typechain/factories/AnchorPay__factory.d.ts +1 -0
- package/dist/typechain/factories/AnchorPay__factory.d.ts.map +1 -0
- package/dist/typechain/factories/index.d.ts +1 -0
- package/dist/typechain/factories/index.d.ts.map +1 -0
- package/dist/typechain/index.d.ts +1 -0
- package/dist/typechain/index.d.ts.map +1 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +83 -85
- package/dist/AnchorApiClient.d.ts +0 -203
- package/dist/AnchorApiClient.js +0 -279
- package/dist/AnchorApiClientV2.js +0 -316
- package/dist/AnchorERC1155Client.js +0 -301
- package/dist/AnchorPayClient.js +0 -908
- package/dist/abi/AnchorERC1155.js +0 -1122
- package/dist/abi/AnchorPay.json +0 -578
- package/dist/api/AnchorApiHttpClient.d.ts +0 -210
- package/dist/api/AnchorApiHttpClient.js +0 -411
- package/dist/api/types.d.ts +0 -764
- package/dist/api/types.js +0 -2
- package/dist/constants.js +0 -367
- package/dist/generated/Api.js +0 -763
- package/dist/react/AnchorReactSDK.d.ts +0 -59
- package/dist/react/AnchorReactSDK.js +0 -192
- package/dist/react/index.d.ts +0 -1
- package/dist/react/index.js +0 -8
- package/dist/typechain/AnchorERC1155.js +0 -2
- package/dist/typechain/AnchorPay.js +0 -2
- package/dist/typechain/common.js +0 -2
- package/dist/typechain/factories/AnchorERC1155__factory.js +0 -1766
- package/dist/typechain/factories/AnchorPay__factory.js +0 -469
- package/dist/typechain/factories/index.js +0 -10
- package/dist/typechain/index.js +0 -41
- package/dist/types.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,1379 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
-
};
|
|
19
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
-
exports.AnchorERC1155Client = exports.AnchorApiClientV2 = exports.AnchorPayClient = exports.AnchorSDK = void 0;
|
|
21
|
-
const viem_1 = require("viem");
|
|
22
|
-
const AnchorPayClient_1 = require("./AnchorPayClient");
|
|
23
|
-
const AnchorERC1155Client_1 = require("./AnchorERC1155Client");
|
|
24
|
-
const AnchorApiClientV2_1 = require("./AnchorApiClientV2");
|
|
25
|
-
const constants_1 = require("./constants");
|
|
26
|
-
const AnchorPay_json_1 = __importDefault(require("./abi/AnchorPay.json"));
|
|
27
|
-
const AnchorERC1155_1 = require("./abi/AnchorERC1155");
|
|
28
|
-
/**
|
|
29
|
-
* Anchor SDK
|
|
30
|
-
* 用于与 AnchorPay 和 AnchorERC1155 合约交互的 SDK
|
|
31
|
-
*/
|
|
32
|
-
class AnchorSDK {
|
|
33
|
-
/**
|
|
34
|
-
* 创建 Anchor SDK 实例
|
|
35
|
-
* @param config SDK 配置
|
|
36
|
-
*/
|
|
37
|
-
constructor(config) {
|
|
38
|
-
this.config = config;
|
|
39
|
-
this.contracts = {};
|
|
40
|
-
// 检查是否使用旧版配置(向后兼容)
|
|
41
|
-
if ("publicClient" in config && config.publicClient) {
|
|
42
|
-
// 使用旧版配置
|
|
43
|
-
this.publicClient = config.publicClient;
|
|
44
|
-
this.walletClient = config.walletClient;
|
|
45
|
-
this.account = this.walletClient?.account;
|
|
46
|
-
this.network = this.createChainFromNetwork(config.network);
|
|
47
|
-
}
|
|
48
|
-
else {
|
|
49
|
-
// 使用新版配置
|
|
50
|
-
// Convert network to viem Chain
|
|
51
|
-
this.network = this.createChainFromNetwork(config.network);
|
|
52
|
-
// Initialize viem clients
|
|
53
|
-
this.publicClient = this.initializePublicClient(config.provider);
|
|
54
|
-
// 如果没有提供 signer,则使用 provider 作为 signer
|
|
55
|
-
const effectiveSigner = config.signer || config.provider;
|
|
56
|
-
this.walletClient = effectiveSigner
|
|
57
|
-
? this.initializeWalletClient(effectiveSigner)
|
|
58
|
-
: undefined;
|
|
59
|
-
this.account =
|
|
60
|
-
this.walletClient?.account ||
|
|
61
|
-
this.getAccountFromSigner(effectiveSigner);
|
|
62
|
-
}
|
|
63
|
-
// 如果用户直接提供了合约地址,优先使用用户提供的地址
|
|
64
|
-
if (config.anchorPayAddress) {
|
|
65
|
-
this.contracts.anchorPay = config.anchorPayAddress;
|
|
66
|
-
}
|
|
67
|
-
if (config.anchorERC1155Address) {
|
|
68
|
-
this.contracts.anchorERC1155 = config.anchorERC1155Address;
|
|
69
|
-
}
|
|
70
|
-
// 创建客户端
|
|
71
|
-
this.anchorPay = new AnchorPayClient_1.AnchorPayClient(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
72
|
-
this.anchorERC1155 = new AnchorERC1155Client_1.AnchorERC1155Client(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
73
|
-
// 处理环境配置
|
|
74
|
-
let apiBaseUrl = config.apiBaseUrl;
|
|
75
|
-
// 如果指定了环境,先尝试从环境配置中获取 API URL 和合约地址
|
|
76
|
-
if (config.env && constants_1.ENVIRONMENTS[config.env]) {
|
|
77
|
-
// 如果没有指定 API URL,使用环境配置中的 URL
|
|
78
|
-
if (!apiBaseUrl) {
|
|
79
|
-
apiBaseUrl = constants_1.ENVIRONMENTS[config.env].apiBaseUrl;
|
|
80
|
-
}
|
|
81
|
-
// 从环境配置中获取当前网络的合约地址(仅当用户没有直接提供时)
|
|
82
|
-
if (this.network.id &&
|
|
83
|
-
constants_1.ENVIRONMENTS[config.env].contracts[this.network.id]) {
|
|
84
|
-
const networkContracts = constants_1.ENVIRONMENTS[config.env].contracts[this.network.id];
|
|
85
|
-
// 只有当用户没有直接提供合约地址时,才使用环境配置中的地址
|
|
86
|
-
if (networkContracts.anchorPay && !this.contracts.anchorPay) {
|
|
87
|
-
this.contracts.anchorPay = networkContracts.anchorPay;
|
|
88
|
-
}
|
|
89
|
-
if (networkContracts.anchorERC1155 && !this.contracts.anchorERC1155) {
|
|
90
|
-
this.contracts.anchorERC1155 = networkContracts.anchorERC1155;
|
|
91
|
-
}
|
|
92
|
-
// 重新初始化客户端
|
|
93
|
-
this.anchorPay = new AnchorPayClient_1.AnchorPayClient(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
94
|
-
this.anchorERC1155 = new AnchorERC1155Client_1.AnchorERC1155Client(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
// 如果有 API URL,创建 Anchor API 客户端
|
|
98
|
-
if (apiBaseUrl) {
|
|
99
|
-
this.anchorApi = new AnchorApiClientV2_1.AnchorApiClientV2({
|
|
100
|
-
apiBaseUrl: apiBaseUrl,
|
|
101
|
-
authToken: config.authToken,
|
|
102
|
-
projectId: config.projectId,
|
|
103
|
-
network: this.network,
|
|
104
|
-
onTokenExpired: config.onTokenExpired,
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* 设置 Token 过期回调
|
|
110
|
-
* @param callback Token 过期回调函数
|
|
111
|
-
*/
|
|
112
|
-
setTokenExpiredCallback(callback) {
|
|
113
|
-
if (this.anchorApi) {
|
|
114
|
-
this.anchorApi.setTokenExpiredCallback(callback);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* 设置钱包客户端
|
|
119
|
-
* 在 SDK 初始化后动态更新钱包客户端和账户
|
|
120
|
-
* @param walletClient 新的钱包客户端
|
|
121
|
-
*/
|
|
122
|
-
setWalletClient(signerOrWalletClient) {
|
|
123
|
-
// 检查是否是 viem WalletClient(向后兼容)
|
|
124
|
-
if (signerOrWalletClient && "account" in signerOrWalletClient) {
|
|
125
|
-
// 使用旧版接口
|
|
126
|
-
this.walletClient = signerOrWalletClient;
|
|
127
|
-
this.account = signerOrWalletClient.account;
|
|
128
|
-
}
|
|
129
|
-
else {
|
|
130
|
-
// 使用新版接口
|
|
131
|
-
// 如果没有提供有效的签名者,则使用当前的 provider
|
|
132
|
-
const effectiveSigner = signerOrWalletClient || this.config.provider;
|
|
133
|
-
this.walletClient = this.initializeWalletClient(effectiveSigner);
|
|
134
|
-
this.account =
|
|
135
|
-
this.walletClient?.account ||
|
|
136
|
-
this.getAccountFromSigner(effectiveSigner);
|
|
137
|
-
}
|
|
138
|
-
// 重新初始化客户端
|
|
139
|
-
this.anchorPay = new AnchorPayClient_1.AnchorPayClient(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
140
|
-
this.anchorERC1155 = new AnchorERC1155Client_1.AnchorERC1155Client(this.publicClient, this.network, this.walletClient, this.account, this.contracts);
|
|
141
|
-
console.log("SDK wallet client updated:", this.account);
|
|
142
|
-
return this;
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* 初始化公共客户端
|
|
146
|
-
* @param provider 提供者(URL或Web3提供者)
|
|
147
|
-
* @returns 公共客户端
|
|
148
|
-
*/
|
|
149
|
-
initializePublicClient(provider) {
|
|
150
|
-
// If provider is a string URL
|
|
151
|
-
if (typeof provider === "string") {
|
|
152
|
-
return (0, viem_1.createPublicClient)({
|
|
153
|
-
chain: this.network,
|
|
154
|
-
transport: (0, viem_1.http)(provider),
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
// If provider is a Web3 Provider (like window.ethereum)
|
|
158
|
-
if (provider && typeof provider === "object") {
|
|
159
|
-
return (0, viem_1.createPublicClient)({
|
|
160
|
-
chain: this.network,
|
|
161
|
-
transport: (0, viem_1.custom)(provider),
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
throw new Error("Invalid provider. Please provide a valid RPC URL or Web3 Provider.");
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* 初始化钱包客户端
|
|
168
|
-
* @param signer 签名者
|
|
169
|
-
* @returns 钱包客户端
|
|
170
|
-
*/
|
|
171
|
-
initializeWalletClient(signer) {
|
|
172
|
-
if (!signer)
|
|
173
|
-
return undefined;
|
|
174
|
-
// If signer is a Web3 Provider with accounts
|
|
175
|
-
if (signer && typeof signer === "object") {
|
|
176
|
-
// For providers like window.ethereum that have accounts
|
|
177
|
-
if (signer.selectedAddress) {
|
|
178
|
-
return (0, viem_1.createWalletClient)({
|
|
179
|
-
chain: this.network,
|
|
180
|
-
transport: (0, viem_1.custom)(signer),
|
|
181
|
-
account: signer.selectedAddress,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
// For signers with an address property
|
|
185
|
-
if (signer.address) {
|
|
186
|
-
return (0, viem_1.createWalletClient)({
|
|
187
|
-
chain: this.network,
|
|
188
|
-
transport: (0, viem_1.custom)(signer.provider || signer),
|
|
189
|
-
account: signer.address,
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
return undefined;
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* 从签名者获取账户
|
|
197
|
-
* @param signer 签名者
|
|
198
|
-
* @returns 账户
|
|
199
|
-
*/
|
|
200
|
-
getAccountFromSigner(signer) {
|
|
201
|
-
if (!signer)
|
|
202
|
-
return undefined;
|
|
203
|
-
// If signer has selectedAddress (like window.ethereum)
|
|
204
|
-
if (signer.selectedAddress) {
|
|
205
|
-
return {
|
|
206
|
-
address: signer.selectedAddress,
|
|
207
|
-
type: "json-rpc",
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
// If signer has address property
|
|
211
|
-
if (signer.address) {
|
|
212
|
-
return {
|
|
213
|
-
address: signer.address,
|
|
214
|
-
type: "json-rpc",
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
return undefined;
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* 从网络信息创建Chain对象
|
|
221
|
-
* @param network 网络信息
|
|
222
|
-
* @returns Chain对象
|
|
223
|
-
*/
|
|
224
|
-
createChainFromNetwork(network) {
|
|
225
|
-
// Create a basic Chain object from the provided network info
|
|
226
|
-
return {
|
|
227
|
-
...network,
|
|
228
|
-
nativeCurrency: network.nativeCurrency || {
|
|
229
|
-
name: "Ether",
|
|
230
|
-
symbol: "ETH",
|
|
231
|
-
decimals: 18,
|
|
232
|
-
},
|
|
233
|
-
rpcUrls: {
|
|
234
|
-
default: {
|
|
235
|
-
http: [
|
|
236
|
-
typeof this.config.provider === "string"
|
|
237
|
-
? this.config.provider
|
|
238
|
-
: "",
|
|
239
|
-
],
|
|
240
|
-
},
|
|
241
|
-
public: {
|
|
242
|
-
http: [
|
|
243
|
-
typeof this.config.provider === "string"
|
|
244
|
-
? this.config.provider
|
|
245
|
-
: "",
|
|
246
|
-
],
|
|
247
|
-
},
|
|
248
|
-
},
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* 购买 Badge(使用 ETH,直接使用签名请求)
|
|
253
|
-
* @param signedRequest 签名铸造请求
|
|
254
|
-
* @param receiptAddress 接收地址,如果提供,将作为 ERC20 转账的接收地址使用
|
|
255
|
-
* @param options 支付选项
|
|
256
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
257
|
-
*/
|
|
258
|
-
async buyBadgeWithETHWithSignedRequest(signedRequest, receiptAddress, options) {
|
|
259
|
-
// 校验 signedRequest
|
|
260
|
-
if (!signedRequest || !signedRequest.request || !signedRequest.signature) {
|
|
261
|
-
throw new Error("signedRequest is required and must contain request and signature");
|
|
262
|
-
}
|
|
263
|
-
// 校验 receiptAddress
|
|
264
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
265
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
266
|
-
}
|
|
267
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
268
|
-
if (options?.sendTransaction !== false &&
|
|
269
|
-
(!this.walletClient || !this.account)) {
|
|
270
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
271
|
-
}
|
|
272
|
-
// 检查请求是否有效
|
|
273
|
-
this.validateMintRequest(signedRequest.request);
|
|
274
|
-
// 检查货币是否为 ETH
|
|
275
|
-
if (signedRequest.request.currency !== constants_1.NATIVE_TOKEN_ADDRESS) {
|
|
276
|
-
throw new Error("Currency must be ETH");
|
|
277
|
-
}
|
|
278
|
-
// 计算总价
|
|
279
|
-
const totalPrice = BigInt(signedRequest.request.price) *
|
|
280
|
-
BigInt(signedRequest.request.quantity);
|
|
281
|
-
// 编码数据
|
|
282
|
-
const data = this.anchorERC1155.encodeTokenReceivedData(signedRequest);
|
|
283
|
-
// 发送交易
|
|
284
|
-
const result = await this.anchorPay.sendETH(receiptAddress, totalPrice, data, options);
|
|
285
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
286
|
-
// 根据 viem 文档,TransactionReceipt 中的交易哈希字段是 transactionHash,而不是 hash
|
|
287
|
-
if (options?.sendTransaction !== false &&
|
|
288
|
-
result &&
|
|
289
|
-
typeof result === "object" &&
|
|
290
|
-
"transactionHash" in result) {
|
|
291
|
-
try {
|
|
292
|
-
await this.processTransactionHash(result.transactionHash);
|
|
293
|
-
}
|
|
294
|
-
catch (error) {
|
|
295
|
-
// 忽略错误,不影响主流程
|
|
296
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
return result;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* 购买 Badge(使用 ERC20 代币,直接使用签名请求)
|
|
303
|
-
* @param signedRequest 签名铸造请求
|
|
304
|
-
* @param receiptAddress 接收地址,如果提供,将作为接收地址使用
|
|
305
|
-
* @param options 支付选项
|
|
306
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
307
|
-
*/
|
|
308
|
-
async buyBadgeWithERC20WithSignedRequest(signedRequest, receiptAddress, options) {
|
|
309
|
-
// 校验 signedRequest
|
|
310
|
-
if (!signedRequest || !signedRequest.request || !signedRequest.signature) {
|
|
311
|
-
throw new Error("signedRequest is required and must contain request and signature");
|
|
312
|
-
}
|
|
313
|
-
// 校验 receiptAddress
|
|
314
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
315
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
316
|
-
}
|
|
317
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
318
|
-
if (options?.sendTransaction !== false &&
|
|
319
|
-
(!this.walletClient || !this.account)) {
|
|
320
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
321
|
-
}
|
|
322
|
-
// 检查请求是否有效
|
|
323
|
-
this.validateMintRequest(signedRequest.request);
|
|
324
|
-
// 检查货币是否为 ERC20
|
|
325
|
-
if (signedRequest.request.currency === constants_1.NATIVE_TOKEN_ADDRESS) {
|
|
326
|
-
throw new Error("Currency cannot be native token");
|
|
327
|
-
}
|
|
328
|
-
// 计算总价
|
|
329
|
-
const totalPrice = BigInt(signedRequest.request.price) *
|
|
330
|
-
BigInt(signedRequest.request.quantity);
|
|
331
|
-
// 编码数据
|
|
332
|
-
const data = this.anchorERC1155.encodeTokenReceivedData(signedRequest);
|
|
333
|
-
// 发送交易
|
|
334
|
-
const result = await this.anchorPay.sendERC20(receiptAddress, signedRequest.request.currency, totalPrice, data, options);
|
|
335
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
336
|
-
// 根据 viem 文档,TransactionReceipt 中的交易哈希字段是 transactionHash,而不是 hash
|
|
337
|
-
if (options?.sendTransaction !== false &&
|
|
338
|
-
result &&
|
|
339
|
-
typeof result === "object" &&
|
|
340
|
-
"transactionHash" in result) {
|
|
341
|
-
try {
|
|
342
|
-
await this.processTransactionHash(result.transactionHash);
|
|
343
|
-
}
|
|
344
|
-
catch (error) {
|
|
345
|
-
// 忽略错误,不影响主流程
|
|
346
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
return result;
|
|
350
|
-
}
|
|
351
|
-
/**
|
|
352
|
-
* 使用 ETH 购买徽章
|
|
353
|
-
* @param customerAddress 客户地址
|
|
354
|
-
* @param contractAddress NFT 地址
|
|
355
|
-
* @param tokenId 代币 ID
|
|
356
|
-
* @param quantity 数量
|
|
357
|
-
* @param receiptAddress 接收地址,如果提供,将作为接收地址使用
|
|
358
|
-
* @param options 支付选项
|
|
359
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
360
|
-
*/
|
|
361
|
-
async buyBadgeWithETH(customerAddress, contractAddress, tokenId, quantity = 1, receiptAddress, options) {
|
|
362
|
-
// 校验地址参数
|
|
363
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
364
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
365
|
-
}
|
|
366
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
367
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
368
|
-
}
|
|
369
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
370
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
371
|
-
}
|
|
372
|
-
// 校验 tokenId 和 quantity
|
|
373
|
-
if (tokenId === undefined || tokenId === "") {
|
|
374
|
-
throw new Error("tokenId is required");
|
|
375
|
-
}
|
|
376
|
-
const quantityBigInt = BigInt(quantity.toString());
|
|
377
|
-
if (quantityBigInt <= 0n) {
|
|
378
|
-
throw new Error("quantity must be greater than 0");
|
|
379
|
-
}
|
|
380
|
-
if (!this.anchorApi) {
|
|
381
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
382
|
-
}
|
|
383
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
384
|
-
if (options?.sendTransaction !== false &&
|
|
385
|
-
(!this.walletClient || !this.account)) {
|
|
386
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
387
|
-
}
|
|
388
|
-
// 使用 claimableIds 来标识要购买的徽章
|
|
389
|
-
const claimableIds = [`${tokenId.toString()}`];
|
|
390
|
-
// 从后端获取铸造请求
|
|
391
|
-
const mintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
392
|
-
customerAddress,
|
|
393
|
-
badgeIds: claimableIds,
|
|
394
|
-
});
|
|
395
|
-
if (mintResponse.code !== "0000" ||
|
|
396
|
-
!mintResponse.obj ||
|
|
397
|
-
!mintResponse.obj.signatures ||
|
|
398
|
-
mintResponse.obj.signatures.length === 0) {
|
|
399
|
-
throw new Error(mintResponse.code || "Failed to get mint request from backend");
|
|
400
|
-
}
|
|
401
|
-
const mintRequest = mintResponse.obj.signatures[0];
|
|
402
|
-
// 检查必要字段
|
|
403
|
-
if (!mintRequest.badgeId ||
|
|
404
|
-
!mintRequest.signature ||
|
|
405
|
-
!mintRequest.validityStartTimestamp ||
|
|
406
|
-
!mintRequest.validityEndTimestamp) {
|
|
407
|
-
throw new Error("Mint request missing required fields");
|
|
408
|
-
}
|
|
409
|
-
// 创建签名铸造请求
|
|
410
|
-
const signedRequest = {
|
|
411
|
-
request: {
|
|
412
|
-
to: customerAddress,
|
|
413
|
-
tokenId: BigInt(mintRequest.badgeId || tokenId),
|
|
414
|
-
quantity: BigInt(mintRequest.quantity || quantity),
|
|
415
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
416
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
417
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp || Math.floor(Date.now() / 1000)), // 立即生效
|
|
418
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp ||
|
|
419
|
-
Math.floor(Date.now() / 1000) + 3600), // 1小时后过期
|
|
420
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
421
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
422
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
423
|
-
},
|
|
424
|
-
signature: mintRequest.signature,
|
|
425
|
-
};
|
|
426
|
-
// 使用签名请求购买徽章(支持 AA 和 EOA 模式)
|
|
427
|
-
return await this.buyBadgeWithETHWithSignedRequest(signedRequest, receiptAddress, options);
|
|
428
|
-
}
|
|
429
|
-
/**
|
|
430
|
-
* 使用自定义签名数据购买徽章(ETH)
|
|
431
|
-
* @param signedRequest 用户自己组装的签名铸造请求
|
|
432
|
-
* @param receiptAddress 接收地址,如果提供,将作为接收地址使用
|
|
433
|
-
* @param options 支付选项
|
|
434
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
435
|
-
*/
|
|
436
|
-
async buyBadgeWithETHWithCustomSignature(signedRequest, receiptAddress, options) {
|
|
437
|
-
// 校验 signedRequest
|
|
438
|
-
if (!signedRequest) {
|
|
439
|
-
throw new Error("signedRequest is required");
|
|
440
|
-
}
|
|
441
|
-
// 校验必要字段
|
|
442
|
-
if (!signedRequest.to || !(0, viem_1.isAddress)(signedRequest.to)) {
|
|
443
|
-
throw new Error("signedRequest.to is required and must be a valid Ethereum address");
|
|
444
|
-
}
|
|
445
|
-
if (signedRequest.tokenId === undefined || signedRequest.tokenId === "") {
|
|
446
|
-
throw new Error("signedRequest.tokenId is required");
|
|
447
|
-
}
|
|
448
|
-
if (signedRequest.quantity === undefined ||
|
|
449
|
-
BigInt(signedRequest.quantity.toString()) <= 0n) {
|
|
450
|
-
throw new Error("signedRequest.quantity is required and must be greater than 0");
|
|
451
|
-
}
|
|
452
|
-
if (signedRequest.price === undefined) {
|
|
453
|
-
throw new Error("signedRequest.price is required");
|
|
454
|
-
}
|
|
455
|
-
if (!signedRequest.uid) {
|
|
456
|
-
throw new Error("signedRequest.uid is required");
|
|
457
|
-
}
|
|
458
|
-
if (!signedRequest.signature) {
|
|
459
|
-
throw new Error("signedRequest.signature is required");
|
|
460
|
-
}
|
|
461
|
-
if (!signedRequest.chainId) {
|
|
462
|
-
throw new Error("signedRequest.chainId is required");
|
|
463
|
-
}
|
|
464
|
-
// 校验 receiptAddress
|
|
465
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
466
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
467
|
-
}
|
|
468
|
-
// 将用户提供的数据转换为标准格式
|
|
469
|
-
const formattedRequest = {
|
|
470
|
-
request: {
|
|
471
|
-
to: signedRequest.to,
|
|
472
|
-
tokenId: BigInt(signedRequest.tokenId),
|
|
473
|
-
quantity: BigInt(signedRequest.quantity),
|
|
474
|
-
price: BigInt(signedRequest.price),
|
|
475
|
-
currency: signedRequest.currency,
|
|
476
|
-
validityStartTimestamp: BigInt(signedRequest.validityStartTimestamp ||
|
|
477
|
-
Math.floor(Date.now() / 1000) + 3600),
|
|
478
|
-
validityEndTimestamp: BigInt(signedRequest.validityEndTimestamp ||
|
|
479
|
-
Math.floor(Date.now() / 1000) + 3600),
|
|
480
|
-
uid: signedRequest.uid,
|
|
481
|
-
chainId: BigInt(signedRequest.chainId || this.network.id),
|
|
482
|
-
projectHandle: signedRequest.projectHandle,
|
|
483
|
-
},
|
|
484
|
-
signature: signedRequest.signature.startsWith("0x")
|
|
485
|
-
? signedRequest.signature
|
|
486
|
-
: `0x${signedRequest.signature}`,
|
|
487
|
-
};
|
|
488
|
-
// 使用标准方法处理
|
|
489
|
-
return await this.buyBadgeWithETHWithSignedRequest(formattedRequest, receiptAddress, options);
|
|
490
|
-
}
|
|
491
|
-
/**
|
|
492
|
-
* 使用 ERC20 代币购买徽章
|
|
493
|
-
* @param customerAddress 客户地址
|
|
494
|
-
* @param contractAddress NFT 地址
|
|
495
|
-
* @param tokenId 代币 ID
|
|
496
|
-
* @param quantity 数量
|
|
497
|
-
* @param currency ERC20 代币地址
|
|
498
|
-
* @param receiptAddress 接收地址,如果提供,将作为接收地址使用
|
|
499
|
-
* @param options 支付选项
|
|
500
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
501
|
-
*/
|
|
502
|
-
async buyBadgeWithERC20(customerAddress, contractAddress, tokenId, quantity = 1, currency, receiptAddress, options) {
|
|
503
|
-
if (!this.anchorApi) {
|
|
504
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
505
|
-
}
|
|
506
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
507
|
-
if (options?.sendTransaction !== false &&
|
|
508
|
-
(!this.walletClient || !this.account)) {
|
|
509
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
510
|
-
}
|
|
511
|
-
// 校验地址参数
|
|
512
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
513
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
514
|
-
}
|
|
515
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
516
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
517
|
-
}
|
|
518
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
519
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
520
|
-
}
|
|
521
|
-
if (!currency || !(0, viem_1.isAddress)(currency)) {
|
|
522
|
-
throw new Error("currency is required and must be a valid ERC20 token address");
|
|
523
|
-
}
|
|
524
|
-
// 校验 tokenId 和 quantity
|
|
525
|
-
if (tokenId === undefined || tokenId === "") {
|
|
526
|
-
throw new Error("tokenId is required");
|
|
527
|
-
}
|
|
528
|
-
const quantityBigInt = BigInt(quantity.toString());
|
|
529
|
-
if (quantityBigInt <= 0n) {
|
|
530
|
-
throw new Error("quantity must be greater than 0");
|
|
531
|
-
}
|
|
532
|
-
// 使用 claimableIds 来标识要购买的徽章
|
|
533
|
-
const claimableIds = [`${tokenId.toString()}`];
|
|
534
|
-
// 从后端获取铸造请求
|
|
535
|
-
const mintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
536
|
-
customerAddress,
|
|
537
|
-
badgeIds: claimableIds,
|
|
538
|
-
});
|
|
539
|
-
if (mintResponse.code !== "0000" ||
|
|
540
|
-
!mintResponse.obj ||
|
|
541
|
-
!mintResponse.obj.signatures ||
|
|
542
|
-
mintResponse.obj.signatures.length === 0) {
|
|
543
|
-
throw new Error(mintResponse.code || "Failed to get mint request from backend");
|
|
544
|
-
}
|
|
545
|
-
const mintRequest = mintResponse.obj.signatures[0];
|
|
546
|
-
// 检查必要字段
|
|
547
|
-
if (!mintRequest.badgeId ||
|
|
548
|
-
!mintRequest.signature ||
|
|
549
|
-
!mintRequest.validityStartTimestamp ||
|
|
550
|
-
!mintRequest.validityEndTimestamp) {
|
|
551
|
-
throw new Error("Mint request missing required fields");
|
|
552
|
-
}
|
|
553
|
-
// 创建签名铸造请求
|
|
554
|
-
const signedRequest = {
|
|
555
|
-
request: {
|
|
556
|
-
to: customerAddress,
|
|
557
|
-
tokenId: BigInt(mintRequest.badgeId || tokenId),
|
|
558
|
-
quantity: BigInt(mintRequest.quantity || quantity),
|
|
559
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
560
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
561
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp || Math.floor(Date.now() / 1000)), // 立即生效
|
|
562
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp ||
|
|
563
|
-
Math.floor(Date.now() / 1000) + 3600), // 1小时后过期
|
|
564
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
565
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
566
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
567
|
-
},
|
|
568
|
-
signature: mintRequest.signature,
|
|
569
|
-
};
|
|
570
|
-
// 使用签名请求购买徽章(支持 AA 和 EOA 模式)
|
|
571
|
-
return await this.buyBadgeWithERC20WithSignedRequest(signedRequest, receiptAddress, options);
|
|
572
|
-
}
|
|
573
|
-
/**
|
|
574
|
-
* 使用自定义签名数据购买徽章(ERC20)
|
|
575
|
-
* @param signedRequest 用户自己组装的签名铸造请求
|
|
576
|
-
* @param receiptAddress 接收地址,如果提供,将作为 ERC20 转账的接收地址使用
|
|
577
|
-
* @param options 支付选项
|
|
578
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
579
|
-
*/
|
|
580
|
-
async buyBadgeWithERC20WithCustomSignature(signedRequest, receiptAddress, options) {
|
|
581
|
-
// 校验 signedRequest
|
|
582
|
-
if (!signedRequest) {
|
|
583
|
-
throw new Error("signedRequest is required");
|
|
584
|
-
}
|
|
585
|
-
// 校验必要字段
|
|
586
|
-
if (!signedRequest.to || !(0, viem_1.isAddress)(signedRequest.to)) {
|
|
587
|
-
throw new Error("signedRequest.to is required and must be a valid Ethereum address");
|
|
588
|
-
}
|
|
589
|
-
if (signedRequest.tokenId === undefined || signedRequest.tokenId === "") {
|
|
590
|
-
throw new Error("signedRequest.tokenId is required");
|
|
591
|
-
}
|
|
592
|
-
if (signedRequest.quantity === undefined ||
|
|
593
|
-
BigInt(signedRequest.quantity.toString()) <= 0n) {
|
|
594
|
-
throw new Error("signedRequest.quantity is required and must be greater than 0");
|
|
595
|
-
}
|
|
596
|
-
if (signedRequest.price === undefined) {
|
|
597
|
-
throw new Error("signedRequest.price is required");
|
|
598
|
-
}
|
|
599
|
-
if (!signedRequest.uid) {
|
|
600
|
-
throw new Error("signedRequest.uid is required");
|
|
601
|
-
}
|
|
602
|
-
if (!signedRequest.signature) {
|
|
603
|
-
throw new Error("signedRequest.signature is required");
|
|
604
|
-
}
|
|
605
|
-
if (!signedRequest.chainId) {
|
|
606
|
-
throw new Error("signedRequest.chainId is required");
|
|
607
|
-
}
|
|
608
|
-
// 校验 receiptAddress
|
|
609
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
610
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
611
|
-
}
|
|
612
|
-
// 将用户提供的数据转换为标准格式
|
|
613
|
-
const formattedRequest = {
|
|
614
|
-
request: {
|
|
615
|
-
to: signedRequest.to,
|
|
616
|
-
tokenId: BigInt(signedRequest.tokenId),
|
|
617
|
-
quantity: BigInt(signedRequest.quantity),
|
|
618
|
-
price: BigInt(signedRequest.price),
|
|
619
|
-
currency: signedRequest.currency,
|
|
620
|
-
validityStartTimestamp: BigInt(signedRequest.validityStartTimestamp ||
|
|
621
|
-
Math.floor(Date.now() / 1000) + 3600),
|
|
622
|
-
validityEndTimestamp: BigInt(signedRequest.validityEndTimestamp ||
|
|
623
|
-
Math.floor(Date.now() / 1000) + 3600),
|
|
624
|
-
uid: signedRequest.uid,
|
|
625
|
-
chainId: BigInt(signedRequest.chainId || this.network.id),
|
|
626
|
-
projectHandle: signedRequest.projectHandle,
|
|
627
|
-
},
|
|
628
|
-
signature: signedRequest.signature.startsWith("0x")
|
|
629
|
-
? signedRequest.signature
|
|
630
|
-
: `0x${signedRequest.signature}`,
|
|
631
|
-
};
|
|
632
|
-
// 使用标准方法处理
|
|
633
|
-
return await this.buyBadgeWithERC20WithSignedRequest(formattedRequest, receiptAddress, options);
|
|
634
|
-
}
|
|
635
|
-
/**
|
|
636
|
-
* 支付方法,使用 ETH 进行支付
|
|
637
|
-
* @deprecated 请使用 sendPayment 方法代替。sendPayment 提供了更灵活的支付选项和更好的类型支持。
|
|
638
|
-
* @param orderId 订单 ID
|
|
639
|
-
* @param amount 支付金额
|
|
640
|
-
* @param receiptAddress 接收地址,如果提供,将作为接收地址使用
|
|
641
|
-
* @param options 支付选项
|
|
642
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
643
|
-
*/
|
|
644
|
-
async pay(orderId, amount, receiptAddress, options) {
|
|
645
|
-
// 校验 orderId
|
|
646
|
-
if (!orderId || orderId.trim() === "") {
|
|
647
|
-
throw new Error("orderId is required and cannot be empty");
|
|
648
|
-
}
|
|
649
|
-
// 校验 receiptAddress
|
|
650
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
651
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
652
|
-
}
|
|
653
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
654
|
-
if (options?.sendTransaction !== false &&
|
|
655
|
-
(!this.walletClient || !this.account)) {
|
|
656
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
657
|
-
}
|
|
658
|
-
// 将 ETH 金额转换为 Wei
|
|
659
|
-
const paymentAmount = typeof amount === "string" || typeof amount === "number"
|
|
660
|
-
? (0, viem_1.parseEther)(amount.toString())
|
|
661
|
-
: amount;
|
|
662
|
-
// 使用 orderId 作为 userData
|
|
663
|
-
const data = this.encodeUserData(orderId);
|
|
664
|
-
const calldata = (0, viem_1.encodeFunctionData)({
|
|
665
|
-
abi: AnchorPay_json_1.default,
|
|
666
|
-
functionName: "send",
|
|
667
|
-
args: [receiptAddress, constants_1.NATIVE_TOKEN_ADDRESS, paymentAmount, data],
|
|
668
|
-
});
|
|
669
|
-
// 如果不需要发送交易,只返回交易数据(AA 模式)
|
|
670
|
-
if (options?.sendTransaction === false) {
|
|
671
|
-
return {
|
|
672
|
-
to: this.contracts?.anchorPay || "",
|
|
673
|
-
data: calldata,
|
|
674
|
-
value: paymentAmount,
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
// 发送交易(EOA 模式)
|
|
678
|
-
const txHash = await this.walletClient.sendTransaction({
|
|
679
|
-
account: this.account,
|
|
680
|
-
to: this.contracts?.anchorPay || "",
|
|
681
|
-
data: calldata,
|
|
682
|
-
value: paymentAmount,
|
|
683
|
-
});
|
|
684
|
-
// 等待交易确认并返回收据
|
|
685
|
-
const result = await this.publicClient.waitForTransactionReceipt({
|
|
686
|
-
hash: txHash,
|
|
687
|
-
});
|
|
688
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
689
|
-
if (result && typeof result === "object" && "transactionHash" in result) {
|
|
690
|
-
try {
|
|
691
|
-
await this.processTransactionHash(result.transactionHash);
|
|
692
|
-
}
|
|
693
|
-
catch (error) {
|
|
694
|
-
// 忽略错误,不影响主流程
|
|
695
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
return result;
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* 支付方法,使用 ETH 进行支付
|
|
702
|
-
* @param params 支付参数
|
|
703
|
-
* @param params.callData 自定义数据
|
|
704
|
-
* @param params.amount 支付金额
|
|
705
|
-
* @param params.receiptAddress 接收地址
|
|
706
|
-
* @param params.contractName 合约名称(可选)
|
|
707
|
-
* @param params.options 支付选项(可选)
|
|
708
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
709
|
-
*/
|
|
710
|
-
async sendPaymentWithNativeToken(params) {
|
|
711
|
-
const { callData, amount, receiptAddress, contractName, options } = params;
|
|
712
|
-
if (!callData || callData.trim() === "") {
|
|
713
|
-
throw new Error("callData is required and cannot be empty");
|
|
714
|
-
}
|
|
715
|
-
// 校验 receiptAddress
|
|
716
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
717
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
718
|
-
}
|
|
719
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
720
|
-
if (options?.sendTransaction !== false &&
|
|
721
|
-
(!this.walletClient || !this.account)) {
|
|
722
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
723
|
-
}
|
|
724
|
-
// 将 ETH 金额转换为 Wei
|
|
725
|
-
const paymentAmount = typeof amount === "string" || typeof amount === "number"
|
|
726
|
-
? (0, viem_1.parseEther)(amount.toString())
|
|
727
|
-
: amount;
|
|
728
|
-
const interfaceHash = (0, viem_1.keccak256)((0, viem_1.stringToHex)(contractName || ""));
|
|
729
|
-
const data = (0, viem_1.concat)([interfaceHash, callData]);
|
|
730
|
-
const calldata = (0, viem_1.encodeFunctionData)({
|
|
731
|
-
abi: AnchorPay_json_1.default,
|
|
732
|
-
functionName: "send",
|
|
733
|
-
args: [receiptAddress, constants_1.NATIVE_TOKEN_ADDRESS, paymentAmount, data],
|
|
734
|
-
});
|
|
735
|
-
// 如果不需要发送交易,只返回交易数据(AA 模式)
|
|
736
|
-
if (options?.sendTransaction === false) {
|
|
737
|
-
return {
|
|
738
|
-
to: this.contracts?.anchorPay || "",
|
|
739
|
-
data: calldata,
|
|
740
|
-
value: paymentAmount,
|
|
741
|
-
};
|
|
742
|
-
}
|
|
743
|
-
// 发送交易(EOA 模式)
|
|
744
|
-
const txHash = await this.walletClient.sendTransaction({
|
|
745
|
-
account: this.account,
|
|
746
|
-
to: this.contracts?.anchorPay || "",
|
|
747
|
-
data: calldata,
|
|
748
|
-
value: paymentAmount,
|
|
749
|
-
});
|
|
750
|
-
// 等待交易确认并返回收据
|
|
751
|
-
const result = await this.publicClient.waitForTransactionReceipt({
|
|
752
|
-
hash: txHash,
|
|
753
|
-
});
|
|
754
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
755
|
-
if (result && typeof result === "object" && "transactionHash" in result) {
|
|
756
|
-
try {
|
|
757
|
-
await this.processTransactionHash(result.transactionHash);
|
|
758
|
-
}
|
|
759
|
-
catch (error) {
|
|
760
|
-
// 忽略错误,不影响主流程
|
|
761
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
return result;
|
|
765
|
-
}
|
|
766
|
-
/**
|
|
767
|
-
* 支付方法,使用 ERC20 代币进行支付
|
|
768
|
-
* @param params 支付参数
|
|
769
|
-
* @param params.callData 自定义数据
|
|
770
|
-
* @param params.amount 支付金额
|
|
771
|
-
* @param params.receiptAddress 接收地址
|
|
772
|
-
* @param params.tokenAddress ERC20 代币地址
|
|
773
|
-
* @param params.contractName 合约名称(可选)
|
|
774
|
-
* @param params.options 支付选项(可选)
|
|
775
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据数组
|
|
776
|
-
*/
|
|
777
|
-
async sendPaymentWithERC20(params) {
|
|
778
|
-
const { callData, amount, receiptAddress, tokenAddress, contractName, options, } = params;
|
|
779
|
-
if (!callData || callData.trim() === "") {
|
|
780
|
-
throw new Error("callData is required and cannot be empty");
|
|
781
|
-
}
|
|
782
|
-
// 校验 receiptAddress
|
|
783
|
-
if (!receiptAddress || !(0, viem_1.isAddress)(receiptAddress)) {
|
|
784
|
-
throw new Error("receiptAddress is required and must be a valid Ethereum address");
|
|
785
|
-
}
|
|
786
|
-
// 校验 tokenAddress
|
|
787
|
-
if (!tokenAddress || !(0, viem_1.isAddress)(tokenAddress)) {
|
|
788
|
-
throw new Error("tokenAddress is required and must be a valid Ethereum address");
|
|
789
|
-
}
|
|
790
|
-
// 获取代币的小数位数
|
|
791
|
-
const decimals = (await this.publicClient.readContract({
|
|
792
|
-
address: tokenAddress,
|
|
793
|
-
abi: constants_1.ERC20_ABI,
|
|
794
|
-
functionName: "decimals",
|
|
795
|
-
}));
|
|
796
|
-
// 根据代币的小数位数进行转换
|
|
797
|
-
const paymentAmount = typeof amount === "bigint"
|
|
798
|
-
? amount
|
|
799
|
-
: BigInt(Math.floor(Number(amount) * 10 ** decimals));
|
|
800
|
-
const interfaceHash = (0, viem_1.keccak256)((0, viem_1.stringToHex)(contractName || ""));
|
|
801
|
-
console.log(`Interface hash: ${interfaceHash}`);
|
|
802
|
-
const data = (0, viem_1.concat)([interfaceHash, callData]);
|
|
803
|
-
console.log(`callData: ${callData}`);
|
|
804
|
-
console.log(`Data: ${data}`);
|
|
805
|
-
// 使用 AnchorPayClient 的 sendERC20 方法
|
|
806
|
-
const result = await this.anchorPay.sendERC20(receiptAddress, tokenAddress, paymentAmount, data, options);
|
|
807
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
808
|
-
if (result && typeof result === "object" && "transactionHash" in result) {
|
|
809
|
-
try {
|
|
810
|
-
await this.processTransactionHash(result.transactionHash);
|
|
811
|
-
}
|
|
812
|
-
catch (error) {
|
|
813
|
-
console.warn(`Failed to process transaction hash ${result.transactionHash} with Anchor API: ${error}`);
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
return result;
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* 编码用户数据
|
|
820
|
-
* @param orderId 订单 ID
|
|
821
|
-
* @returns 编码后的数据
|
|
822
|
-
*/
|
|
823
|
-
encodeUserData(orderId) {
|
|
824
|
-
// 使用 keccak256 哈希函数计算接口哈希
|
|
825
|
-
const interfaceHash = (0, viem_1.keccak256)((0, viem_1.stringToHex)(""));
|
|
826
|
-
console.log(interfaceHash, "interfaceHash");
|
|
827
|
-
// 编码订单 ID
|
|
828
|
-
const encodedOrderId = (0, viem_1.stringToHex)(orderId);
|
|
829
|
-
// 返回完整的编码数据
|
|
830
|
-
console.log((0, viem_1.concat)([interfaceHash, encodedOrderId]), "concat");
|
|
831
|
-
return (0, viem_1.concat)([interfaceHash, encodedOrderId]);
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* 铸造免费 Badge
|
|
835
|
-
* 从后端获取签名铸造请求,然后调用合约铸造
|
|
836
|
-
* @param customerAddress 客户地址
|
|
837
|
-
* @param contractAddress NFT 地址
|
|
838
|
-
* @param tokenIds badge 的 tokenId 数组
|
|
839
|
-
* @param options 选项,可以控制是否直接发送交易
|
|
840
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
841
|
-
*/
|
|
842
|
-
async mintFreeBadge(customerAddress, contractAddress, tokenIds, options) {
|
|
843
|
-
// 校验地址参数
|
|
844
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
845
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
846
|
-
}
|
|
847
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
848
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
849
|
-
}
|
|
850
|
-
// 校验 tokenIds
|
|
851
|
-
if (!tokenIds || !Array.isArray(tokenIds) || tokenIds.length === 0) {
|
|
852
|
-
throw new Error("tokenIds is required and must be a non-empty array");
|
|
853
|
-
}
|
|
854
|
-
for (const id of tokenIds) {
|
|
855
|
-
if (!id || typeof id !== "string") {
|
|
856
|
-
throw new Error("Each tokenId must be a non-empty string");
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
if (!this.anchorApi) {
|
|
860
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
861
|
-
}
|
|
862
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
863
|
-
if (options?.sendTransaction !== false &&
|
|
864
|
-
(!this.walletClient || !this.account)) {
|
|
865
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
866
|
-
}
|
|
867
|
-
// 步骤 1: 从后端获取铸造请求
|
|
868
|
-
const mintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
869
|
-
customerAddress,
|
|
870
|
-
badgeIds: tokenIds,
|
|
871
|
-
});
|
|
872
|
-
console.log(JSON.stringify(mintResponse));
|
|
873
|
-
if (mintResponse.code !== "0000" ||
|
|
874
|
-
!mintResponse.obj ||
|
|
875
|
-
!mintResponse.obj.signatures ||
|
|
876
|
-
mintResponse.obj.signatures.length === 0) {
|
|
877
|
-
throw new Error(mintResponse.code || "Failed to get mint request from backend");
|
|
878
|
-
}
|
|
879
|
-
if (options?.sendTransaction === false) {
|
|
880
|
-
const mintRequests = mintResponse.obj.signatures; // 获取所有签名
|
|
881
|
-
// 创建批量签名铸造请求数组
|
|
882
|
-
const batchUserOp = await Promise.all(mintRequests.map(async (mintRequest) => {
|
|
883
|
-
// 检查必要字段
|
|
884
|
-
if (!mintRequest.badgeId ||
|
|
885
|
-
!mintRequest.signature ||
|
|
886
|
-
!mintRequest.validityStartTimestamp ||
|
|
887
|
-
!mintRequest.validityEndTimestamp) {
|
|
888
|
-
throw new Error("Mint request missing required fields");
|
|
889
|
-
}
|
|
890
|
-
// 创建签名铸造请求
|
|
891
|
-
const signedRequest = {
|
|
892
|
-
request: {
|
|
893
|
-
to: customerAddress,
|
|
894
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
895
|
-
quantity: BigInt(mintRequest.quantity || 1),
|
|
896
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
897
|
-
currency: mintRequest.currency, // ETH
|
|
898
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
899
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
900
|
-
uid: mintRequest.uid,
|
|
901
|
-
chainId: BigInt(mintRequest.chainId || this.network.id),
|
|
902
|
-
projectHandle: mintRequest.projectHandle,
|
|
903
|
-
},
|
|
904
|
-
signature: mintRequest.signature,
|
|
905
|
-
};
|
|
906
|
-
// 检查请求是否有效
|
|
907
|
-
this.validateMintRequest(signedRequest.request);
|
|
908
|
-
// 检查价格是否为 0
|
|
909
|
-
if (BigInt(signedRequest.request.price) !== 0n) {
|
|
910
|
-
throw new Error("Free Badge price must be 0");
|
|
911
|
-
}
|
|
912
|
-
// 返回单个交易数据
|
|
913
|
-
return (await this.anchorERC1155.mintWithSignature(signedRequest, contractAddress, { sendTransaction: false }));
|
|
914
|
-
}));
|
|
915
|
-
// 返回批量操作数组
|
|
916
|
-
return batchUserOp;
|
|
917
|
-
}
|
|
918
|
-
// 处理所有铸造请求
|
|
919
|
-
let lastReceipt = null;
|
|
920
|
-
for (const mintRequest of mintResponse.obj.signatures) {
|
|
921
|
-
// 检查必要字段
|
|
922
|
-
if (!mintRequest.badgeId ||
|
|
923
|
-
!mintRequest.signature ||
|
|
924
|
-
!mintRequest.validityStartTimestamp ||
|
|
925
|
-
!mintRequest.validityEndTimestamp) {
|
|
926
|
-
console.warn("铸造请求缺失必要字段", mintRequest);
|
|
927
|
-
continue;
|
|
928
|
-
}
|
|
929
|
-
// 创建签名铸造请求
|
|
930
|
-
const signedRequest = {
|
|
931
|
-
request: {
|
|
932
|
-
to: customerAddress,
|
|
933
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
934
|
-
quantity: BigInt(mintRequest.quantity || 1),
|
|
935
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
936
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
937
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
938
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
939
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
940
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
941
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
942
|
-
},
|
|
943
|
-
signature: mintRequest.signature,
|
|
944
|
-
};
|
|
945
|
-
// 检查请求是否有效
|
|
946
|
-
this.validateMintRequest(signedRequest.request);
|
|
947
|
-
// 检查价格是否为 0
|
|
948
|
-
if (BigInt(signedRequest.request.price) !== 0n) {
|
|
949
|
-
throw new Error("Free Badge price must be 0");
|
|
950
|
-
}
|
|
951
|
-
console.log(signedRequest, "signedRequest");
|
|
952
|
-
// 调用合约铸造(始终发送交易)
|
|
953
|
-
const result = await this.anchorERC1155.mintWithSignature(signedRequest, contractAddress, { sendTransaction: true });
|
|
954
|
-
// 由于指定了 sendTransaction: true,返回的应该是交易收据
|
|
955
|
-
if ("transactionHash" in result) {
|
|
956
|
-
lastReceipt = result;
|
|
957
|
-
// 尝试加快交易处理
|
|
958
|
-
try {
|
|
959
|
-
await this.processTransactionHash(result.transactionHash);
|
|
960
|
-
}
|
|
961
|
-
catch (error) {
|
|
962
|
-
// 忽略错误,不影响主流程
|
|
963
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
else {
|
|
967
|
-
throw new Error("Expected transaction receipt, but received transaction data");
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
// 返回最后一个交易收据,或者抛出错误
|
|
971
|
-
if (!lastReceipt) {
|
|
972
|
-
throw new Error("No successful mint transaction");
|
|
973
|
-
}
|
|
974
|
-
return lastReceipt;
|
|
975
|
-
}
|
|
976
|
-
/**
|
|
977
|
-
* 铸造免费 Badge(直接使用签名请求)
|
|
978
|
-
* @param signedRequest 签名铸造请求
|
|
979
|
-
* @param options 选项,可以控制是否直接发送交易
|
|
980
|
-
* @returns 如果直接发送交易,返回交易收据;否则返回交易数据
|
|
981
|
-
*/
|
|
982
|
-
async mintFreeBadgeWithSignedRequest(signedRequest, options) {
|
|
983
|
-
// 检查请求是否有效
|
|
984
|
-
this.validateMintRequest(signedRequest.request);
|
|
985
|
-
// 检查价格是否为 0
|
|
986
|
-
if (BigInt(signedRequest.request.price) !== 0n) {
|
|
987
|
-
throw new Error("Free Badge price must be 0");
|
|
988
|
-
}
|
|
989
|
-
// 调用 mintWithSignature,并传递选项
|
|
990
|
-
const result = await this.anchorERC1155.mintWithSignature(signedRequest, signedRequest?.request?.contractAddress, options);
|
|
991
|
-
// 如果是交易收据并且有 transactionHash,尝试加快交易处理
|
|
992
|
-
if (options?.sendTransaction !== false &&
|
|
993
|
-
result &&
|
|
994
|
-
typeof result === "object" &&
|
|
995
|
-
"transactionHash" in result) {
|
|
996
|
-
try {
|
|
997
|
-
await this.processTransactionHash(result.transactionHash);
|
|
998
|
-
}
|
|
999
|
-
catch (error) {
|
|
1000
|
-
// 忽略错误,不影响主流程
|
|
1001
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
return result;
|
|
1005
|
-
}
|
|
1006
|
-
/**
|
|
1007
|
-
* 获取 ERC20 代币批准的交易数据(用于 AA 模式)
|
|
1008
|
-
* @param tokenAddress ERC20 代币地址
|
|
1009
|
-
* @param amount 批准金额
|
|
1010
|
-
* @param spender 花费者地址(默认为 AnchorPay 合约地址)
|
|
1011
|
-
* @returns 交易数据对象,包含 to、data 和 value 字段
|
|
1012
|
-
*/
|
|
1013
|
-
getERC20ApprovalData(tokenAddress, amount, spender) {
|
|
1014
|
-
return this.anchorPay.getERC20ApprovalData(tokenAddress, amount, spender);
|
|
1015
|
-
}
|
|
1016
|
-
/**
|
|
1017
|
-
* 验证铸造请求
|
|
1018
|
-
* @param request 铸造请求
|
|
1019
|
-
*/
|
|
1020
|
-
validateMintRequest(request) {
|
|
1021
|
-
// 检查接收者地址
|
|
1022
|
-
if (!(0, viem_1.isAddress)(request.to)) {
|
|
1023
|
-
throw new Error("Invalid recipient address");
|
|
1024
|
-
}
|
|
1025
|
-
// 检查有效期
|
|
1026
|
-
const now = Math.floor(Date.now() / 1000);
|
|
1027
|
-
const endTimestamp = request.validityEndTimestamp;
|
|
1028
|
-
if (endTimestamp && BigInt(endTimestamp) < BigInt(now)) {
|
|
1029
|
-
throw new Error("Mint request expired");
|
|
1030
|
-
}
|
|
1031
|
-
// 检查数量
|
|
1032
|
-
if (BigInt(request.quantity) <= 0n) {
|
|
1033
|
-
throw new Error("Quantity must be greater than 0");
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
/**
|
|
1037
|
-
* 处理交易哈希
|
|
1038
|
-
* 在交易确认后调用该方法可加快交易处理
|
|
1039
|
-
* @param txHash 交易哈希
|
|
1040
|
-
* @returns 处理结果或 undefined(如果 API 客户端不可用)
|
|
1041
|
-
*/
|
|
1042
|
-
async processTransactionHash(txHash) {
|
|
1043
|
-
try {
|
|
1044
|
-
if (this.anchorApi) {
|
|
1045
|
-
const result = await this.anchorApi.transactionHashProcess(txHash);
|
|
1046
|
-
console.log(`Transaction processing accelerated: ${txHash}`);
|
|
1047
|
-
return result;
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
catch (error) {
|
|
1051
|
-
console.warn(`Failed to accelerate transaction processing: ${error instanceof Error ? error.message : String(error)}`);
|
|
1052
|
-
// 不影响主流程,只记录日志
|
|
1053
|
-
}
|
|
1054
|
-
return undefined;
|
|
1055
|
-
}
|
|
1056
|
-
/**
|
|
1057
|
-
* 批量铸造徽章(V2)
|
|
1058
|
-
* @param customerAddress 客户地址
|
|
1059
|
-
* @param contractAddress NFT 合约地址
|
|
1060
|
-
* @param tokenIds 代币 ID 列表
|
|
1061
|
-
* @param options 选项,可以控制是否直接发送交易
|
|
1062
|
-
* @returns 如果直接发送交易,返回最后一个交易收据;AA 模式返回所有交易数据数组
|
|
1063
|
-
*/
|
|
1064
|
-
async batchMintBadge(customerAddress, contractAddress, tokenIds, options) {
|
|
1065
|
-
if (!this.anchorApi) {
|
|
1066
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
1067
|
-
}
|
|
1068
|
-
// 参数校验
|
|
1069
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
1070
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
1071
|
-
}
|
|
1072
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
1073
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
1074
|
-
}
|
|
1075
|
-
if (!Array.isArray(tokenIds) || tokenIds.length === 0) {
|
|
1076
|
-
throw new Error("tokenIds is required and must be a non-empty array");
|
|
1077
|
-
}
|
|
1078
|
-
for (const id of tokenIds) {
|
|
1079
|
-
if (!id || typeof id !== "string") {
|
|
1080
|
-
throw new Error("Each tokenId must be a non-empty string");
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
1084
|
-
if (options?.sendTransaction !== false &&
|
|
1085
|
-
(!this.walletClient || !this.account)) {
|
|
1086
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
1087
|
-
}
|
|
1088
|
-
// 步骤 1: 从后端获取批量铸造请求
|
|
1089
|
-
// 使用新的 API 设计,一次性获取所有徽章的签名
|
|
1090
|
-
const batchMintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
1091
|
-
customerAddress,
|
|
1092
|
-
badgeIds: tokenIds,
|
|
1093
|
-
});
|
|
1094
|
-
if (batchMintResponse.code !== "0000" ||
|
|
1095
|
-
!batchMintResponse.obj ||
|
|
1096
|
-
!batchMintResponse.obj.signatures ||
|
|
1097
|
-
batchMintResponse.obj.signatures.length === 0) {
|
|
1098
|
-
throw new Error(batchMintResponse.code ||
|
|
1099
|
-
"Failed to get batch mint request from backend");
|
|
1100
|
-
}
|
|
1101
|
-
const mintRequests = batchMintResponse.obj.signatures;
|
|
1102
|
-
// AA 模式:只返回所有交易数据
|
|
1103
|
-
if (options?.sendTransaction === false) {
|
|
1104
|
-
const batchUserOp = await Promise.all(mintRequests.map(async (mintRequest) => {
|
|
1105
|
-
// 检查必要字段
|
|
1106
|
-
if (!mintRequest.badgeId ||
|
|
1107
|
-
!mintRequest.signature ||
|
|
1108
|
-
!mintRequest.validityStartTimestamp ||
|
|
1109
|
-
!mintRequest.validityEndTimestamp) {
|
|
1110
|
-
throw new Error("Mint request missing required fields");
|
|
1111
|
-
}
|
|
1112
|
-
// 创建签名铸造请求
|
|
1113
|
-
const signedRequest = {
|
|
1114
|
-
request: {
|
|
1115
|
-
to: customerAddress,
|
|
1116
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
1117
|
-
quantity: BigInt(mintRequest.quantity || 1), // 默认数量为1
|
|
1118
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
1119
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
1120
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
1121
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
1122
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
1123
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
1124
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
1125
|
-
},
|
|
1126
|
-
signature: mintRequest.signature,
|
|
1127
|
-
};
|
|
1128
|
-
this.validateMintRequest(signedRequest.request);
|
|
1129
|
-
return (await this.anchorERC1155.mintWithSignature(signedRequest, contractAddress, { sendTransaction: false }));
|
|
1130
|
-
}));
|
|
1131
|
-
return batchUserOp;
|
|
1132
|
-
}
|
|
1133
|
-
// EOA 模式:链上批量 mint,返回最后一个收据
|
|
1134
|
-
let lastReceipt = null;
|
|
1135
|
-
for (const mintRequest of mintRequests) {
|
|
1136
|
-
if (!mintRequest.badgeId ||
|
|
1137
|
-
!mintRequest.signature ||
|
|
1138
|
-
!mintRequest.validityStartTimestamp ||
|
|
1139
|
-
!mintRequest.validityEndTimestamp) {
|
|
1140
|
-
console.warn("铸造请求缺失必要字段", mintRequest);
|
|
1141
|
-
continue;
|
|
1142
|
-
}
|
|
1143
|
-
const signedRequest = {
|
|
1144
|
-
request: {
|
|
1145
|
-
to: customerAddress,
|
|
1146
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
1147
|
-
quantity: BigInt(mintRequest.quantity || 1), // 默认数量为1
|
|
1148
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
1149
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
1150
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
1151
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
1152
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
1153
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
1154
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
1155
|
-
},
|
|
1156
|
-
signature: mintRequest.signature,
|
|
1157
|
-
};
|
|
1158
|
-
this.validateMintRequest(signedRequest.request);
|
|
1159
|
-
const result = await this.anchorERC1155.mintWithSignature(signedRequest, contractAddress, { sendTransaction: true });
|
|
1160
|
-
if ("transactionHash" in result) {
|
|
1161
|
-
lastReceipt = result;
|
|
1162
|
-
try {
|
|
1163
|
-
await this.processTransactionHash(result.transactionHash);
|
|
1164
|
-
}
|
|
1165
|
-
catch (error) {
|
|
1166
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
else {
|
|
1170
|
-
throw new Error("Expected transaction receipt, but received transaction data");
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
if (!lastReceipt) {
|
|
1174
|
-
throw new Error("No successful mint transaction");
|
|
1175
|
-
}
|
|
1176
|
-
return lastReceipt;
|
|
1177
|
-
}
|
|
1178
|
-
/**
|
|
1179
|
-
* 批量铸造徽章(Multicall V2)
|
|
1180
|
-
* @param customerAddress 客户地址
|
|
1181
|
-
* @param contractAddress NFT 合约地址
|
|
1182
|
-
* @param tokenIds 代币 ID 列表
|
|
1183
|
-
* @param options 选项,可以控制是否直接发送交易
|
|
1184
|
-
* @returns 如果直接发送交易,返回交易收据;AA 模式返回 multicall 交易数据
|
|
1185
|
-
*/
|
|
1186
|
-
async batchMintBadgeWithMulticall(customerAddress, contractAddress, tokenIds, options) {
|
|
1187
|
-
if (!this.anchorApi) {
|
|
1188
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
1189
|
-
}
|
|
1190
|
-
// 参数校验
|
|
1191
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
1192
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
1193
|
-
}
|
|
1194
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
1195
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
1196
|
-
}
|
|
1197
|
-
if (!Array.isArray(tokenIds) || tokenIds.length === 0) {
|
|
1198
|
-
throw new Error("tokenIds is required and must be a non-empty array");
|
|
1199
|
-
}
|
|
1200
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
1201
|
-
if (options?.sendTransaction !== false &&
|
|
1202
|
-
(!this.walletClient || !this.account)) {
|
|
1203
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
1204
|
-
}
|
|
1205
|
-
// 从后端获取批量铸造请求
|
|
1206
|
-
// 使用新的 API 设计,一次性获取所有徽章的签名
|
|
1207
|
-
const batchMintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
1208
|
-
customerAddress,
|
|
1209
|
-
badgeIds: tokenIds,
|
|
1210
|
-
});
|
|
1211
|
-
if (batchMintResponse.code !== "0000" ||
|
|
1212
|
-
!batchMintResponse.obj ||
|
|
1213
|
-
!batchMintResponse.obj.signatures ||
|
|
1214
|
-
batchMintResponse.obj.signatures.length === 0) {
|
|
1215
|
-
throw new Error(batchMintResponse.code ||
|
|
1216
|
-
"Failed to get batch mint request from backend");
|
|
1217
|
-
}
|
|
1218
|
-
const mintRequests = batchMintResponse.obj.signatures;
|
|
1219
|
-
// 编码所有 mintWithSignature 调用的 calldata
|
|
1220
|
-
const calldatas = mintRequests.map((mintRequest) => {
|
|
1221
|
-
if (!mintRequest.badgeId ||
|
|
1222
|
-
!mintRequest.signature ||
|
|
1223
|
-
!mintRequest.validityStartTimestamp ||
|
|
1224
|
-
!mintRequest.validityEndTimestamp) {
|
|
1225
|
-
throw new Error("Mint request missing required fields");
|
|
1226
|
-
}
|
|
1227
|
-
const signedRequest = {
|
|
1228
|
-
request: {
|
|
1229
|
-
to: customerAddress,
|
|
1230
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
1231
|
-
quantity: BigInt(mintRequest.quantity || 1), // 默认数量为1
|
|
1232
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
1233
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
1234
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
1235
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
1236
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
1237
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
1238
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
1239
|
-
},
|
|
1240
|
-
signature: mintRequest.signature,
|
|
1241
|
-
};
|
|
1242
|
-
this.validateMintRequest(signedRequest.request);
|
|
1243
|
-
// 注意:这里我们假设所有 mint 都发生在同一个 ERC1155 合约上
|
|
1244
|
-
// 并且这个合约地址是在 AnchorERC1155Client 中配置的
|
|
1245
|
-
return (0, viem_1.encodeFunctionData)({
|
|
1246
|
-
abi: AnchorERC1155_1.AnchorERC1155ABI,
|
|
1247
|
-
functionName: "mintWithSignature",
|
|
1248
|
-
args: [
|
|
1249
|
-
this.anchorERC1155["formatMintRequest"](signedRequest.request),
|
|
1250
|
-
signedRequest.signature,
|
|
1251
|
-
],
|
|
1252
|
-
});
|
|
1253
|
-
});
|
|
1254
|
-
// 调用 multicall
|
|
1255
|
-
const result = await this.anchorERC1155.multicall(calldatas, options);
|
|
1256
|
-
if (options?.sendTransaction !== false &&
|
|
1257
|
-
result &&
|
|
1258
|
-
typeof result === "object" &&
|
|
1259
|
-
"transactionHash" in result) {
|
|
1260
|
-
try {
|
|
1261
|
-
await this.processTransactionHash(result.transactionHash);
|
|
1262
|
-
}
|
|
1263
|
-
catch (error) {
|
|
1264
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
return result;
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* 批量铸造免费徽章(Multicall)
|
|
1271
|
-
* 从后端获取签名铸造请求,然后使用 multicall 批量铸造
|
|
1272
|
-
* @param customerAddress 客户地址
|
|
1273
|
-
* @param contractAddress NFT 合约地址
|
|
1274
|
-
* @param tokenIds badge 的 tokenId 数组
|
|
1275
|
-
* @param options 选项,可以控制是否直接发送交易
|
|
1276
|
-
* @returns 如果直接发送交易,返回交易收据;AA 模式返回 multicall 交易数据
|
|
1277
|
-
*/
|
|
1278
|
-
async mintFreeBadgeWithMulticall(customerAddress, contractAddress, tokenIds, options) {
|
|
1279
|
-
if (!this.anchorApi) {
|
|
1280
|
-
throw new Error("Anchor API client not initialized, please check apiBaseUrl configuration");
|
|
1281
|
-
}
|
|
1282
|
-
// 参数校验
|
|
1283
|
-
if (!customerAddress || !(0, viem_1.isAddress)(customerAddress)) {
|
|
1284
|
-
throw new Error("customerAddress is required and must be a valid Ethereum address");
|
|
1285
|
-
}
|
|
1286
|
-
if (!contractAddress || !(0, viem_1.isAddress)(contractAddress)) {
|
|
1287
|
-
throw new Error("contractAddress is required and must be a valid Ethereum address");
|
|
1288
|
-
}
|
|
1289
|
-
if (!Array.isArray(tokenIds) || tokenIds.length === 0) {
|
|
1290
|
-
throw new Error("tokenIds is required and must be a non-empty array");
|
|
1291
|
-
}
|
|
1292
|
-
for (const id of tokenIds) {
|
|
1293
|
-
if (!id || typeof id !== "string") {
|
|
1294
|
-
throw new Error("Each tokenId must be a non-empty string");
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
// 如果需要发送交易,但没有钱包客户端或账户
|
|
1298
|
-
if (options?.sendTransaction !== false &&
|
|
1299
|
-
(!this.walletClient || !this.account)) {
|
|
1300
|
-
throw new Error("Wallet client and account are required to send transactions");
|
|
1301
|
-
}
|
|
1302
|
-
// 从后端获取免费铸造请求
|
|
1303
|
-
const mintResponse = await this.anchorApi.getBadgeClaimSignatures({
|
|
1304
|
-
customerAddress,
|
|
1305
|
-
badgeIds: tokenIds,
|
|
1306
|
-
});
|
|
1307
|
-
if (mintResponse.code !== "0000" ||
|
|
1308
|
-
!mintResponse.obj ||
|
|
1309
|
-
!mintResponse.obj.signatures ||
|
|
1310
|
-
mintResponse.obj.signatures.length === 0) {
|
|
1311
|
-
throw new Error(mintResponse.code || "Failed to get mint request from backend");
|
|
1312
|
-
}
|
|
1313
|
-
// 编码所有 mintWithSignature 调用的 calldata
|
|
1314
|
-
const calldatas = mintResponse.obj.signatures.map((mintRequest) => {
|
|
1315
|
-
if (!mintRequest.badgeId ||
|
|
1316
|
-
!mintRequest.signature ||
|
|
1317
|
-
!mintRequest.validityStartTimestamp ||
|
|
1318
|
-
!mintRequest.validityEndTimestamp) {
|
|
1319
|
-
throw new Error("Mint request missing required fields");
|
|
1320
|
-
}
|
|
1321
|
-
const signedRequest = {
|
|
1322
|
-
request: {
|
|
1323
|
-
to: customerAddress,
|
|
1324
|
-
tokenId: BigInt(mintRequest.badgeId),
|
|
1325
|
-
quantity: BigInt(mintRequest.quantity || 1), // 默认数量为1
|
|
1326
|
-
price: BigInt(mintRequest.price || 0), // 从签名中获取价格信息
|
|
1327
|
-
currency: mintRequest.currency, // 从签名中获取货币信息
|
|
1328
|
-
validityStartTimestamp: BigInt(mintRequest.validityStartTimestamp),
|
|
1329
|
-
validityEndTimestamp: BigInt(mintRequest.validityEndTimestamp),
|
|
1330
|
-
uid: mintRequest.uid, // 从签名中获取 uid
|
|
1331
|
-
chainId: BigInt(mintRequest.chainId || this.network.id), // 从签名中获取链 ID
|
|
1332
|
-
projectHandle: mintRequest.projectHandle, // 从签名中获取项目句柄
|
|
1333
|
-
},
|
|
1334
|
-
signature: mintRequest.signature,
|
|
1335
|
-
};
|
|
1336
|
-
this.validateMintRequest(signedRequest.request);
|
|
1337
|
-
// 检查价格是否为 0
|
|
1338
|
-
if (BigInt(signedRequest.request.price) !== 0n) {
|
|
1339
|
-
throw new Error("Free Badge price must be 0");
|
|
1340
|
-
}
|
|
1341
|
-
// 编码 mintWithSignature 调用
|
|
1342
|
-
return (0, viem_1.encodeFunctionData)({
|
|
1343
|
-
abi: AnchorERC1155_1.AnchorERC1155ABI,
|
|
1344
|
-
functionName: "mintWithSignature",
|
|
1345
|
-
args: [
|
|
1346
|
-
this.anchorERC1155["formatMintRequest"](signedRequest.request),
|
|
1347
|
-
signedRequest.signature,
|
|
1348
|
-
],
|
|
1349
|
-
});
|
|
1350
|
-
});
|
|
1351
|
-
// 调用 multicall
|
|
1352
|
-
const result = await this.anchorERC1155.multicall(calldatas, options);
|
|
1353
|
-
if (options?.sendTransaction !== false &&
|
|
1354
|
-
result &&
|
|
1355
|
-
typeof result === "object" &&
|
|
1356
|
-
"transactionHash" in result) {
|
|
1357
|
-
try {
|
|
1358
|
-
await this.processTransactionHash(result.transactionHash);
|
|
1359
|
-
}
|
|
1360
|
-
catch (error) {
|
|
1361
|
-
console.warn(`Failed to process transaction hash: ${error instanceof Error ? error.message : String(error)}`);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
return result;
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
exports.AnchorSDK = AnchorSDK;
|
|
1368
|
-
// 导出类型和常量
|
|
1369
|
-
__exportStar(require("./types"), exports);
|
|
1370
|
-
__exportStar(require("./constants"), exports);
|
|
1371
|
-
var AnchorPayClient_2 = require("./AnchorPayClient");
|
|
1372
|
-
Object.defineProperty(exports, "AnchorPayClient", { enumerable: true, get: function () { return AnchorPayClient_2.AnchorPayClient; } });
|
|
1373
|
-
var AnchorApiClientV2_2 = require("./AnchorApiClientV2");
|
|
1374
|
-
Object.defineProperty(exports, "AnchorApiClientV2", { enumerable: true, get: function () { return AnchorApiClientV2_2.AnchorApiClientV2; } });
|
|
1375
|
-
var AnchorERC1155Client_2 = require("./AnchorERC1155Client");
|
|
1376
|
-
Object.defineProperty(exports, "AnchorERC1155Client", { enumerable: true, get: function () { return AnchorERC1155Client_2.AnchorERC1155Client; } });
|
|
1377
|
-
// 导出 React SDK
|
|
1378
|
-
__exportStar(require("./react"), exports);
|
|
1379
|
-
__exportStar(require("./generated/Api"), exports);
|
|
1
|
+
import{concat as Y,createPublicClient as D,createWalletClient as k,custom as V,encodeFunctionData as $,http as re,isAddress as b,keccak256 as C,parseEther as g,stringToHex as Q}from"viem";var c;((r)=>{r.Json="application/json";r.JsonApi="application/vnd.api+json";r.FormData="multipart/form-data";r.UrlEncoded="application/x-www-form-urlencoded";r.Text="text/plain"})(c||={});class B{baseUrl="https://anchordev.dipbit.xyz/";securityData=null;securityWorker;abortControllers=new Map;customFetch=(...e)=>fetch(...e);baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"};constructor(e={}){Object.assign(this,e)}setSecurityData=(e)=>{this.securityData=e};encodeQueryParam(e,n){return`${encodeURIComponent(e)}=${encodeURIComponent(typeof n==="number"?n:`${n}`)}`}addQueryParam(e,n){return this.encodeQueryParam(n,e[n])}addArrayQueryParam(e,n){return e[n].map((a)=>this.encodeQueryParam(n,a)).join("&")}toQueryString(e){let n=e||{};return Object.keys(n).filter((a)=>typeof n[a]<"u").map((a)=>Array.isArray(n[a])?this.addArrayQueryParam(n,a):this.addQueryParam(n,a)).join("&")}addQueryParams(e){let n=this.toQueryString(e);return n?`?${n}`:""}contentFormatters={["application/json"]:(e)=>e!==null&&(typeof e==="object"||typeof e==="string")?JSON.stringify(e):e,["application/vnd.api+json"]:(e)=>e!==null&&(typeof e==="object"||typeof e==="string")?JSON.stringify(e):e,["text/plain"]:(e)=>e!==null&&typeof e!=="string"?JSON.stringify(e):e,["multipart/form-data"]:(e)=>{if(e instanceof FormData)return e;return Object.keys(e||{}).reduce((n,t)=>{let a=e[t];return n.append(t,a instanceof Blob?a:typeof a==="object"&&a!==null?JSON.stringify(a):`${a}`),n},new FormData)},["application/x-www-form-urlencoded"]:(e)=>this.toQueryString(e)};mergeRequestParams(e,n){return{...this.baseApiParams,...e,...n||{},headers:{...this.baseApiParams.headers||{},...e.headers||{},...n&&n.headers||{}}}}createAbortSignal=(e)=>{if(this.abortControllers.has(e)){let t=this.abortControllers.get(e);if(t)return t.signal;return}let n=new AbortController;return this.abortControllers.set(e,n),n.signal};abortRequest=(e)=>{let n=this.abortControllers.get(e);if(n)n.abort(),this.abortControllers.delete(e)};request=async({body:e,secure:n,path:t,type:a,query:y,format:r,baseUrl:l,cancelToken:i,...p})=>{let u=(typeof n==="boolean"?n:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},T=this.mergeRequestParams(p,u),m=y&&this.toQueryString(y),d=this.contentFormatters[a||"application/json"],o=r||T.format;return this.customFetch(`${l||this.baseUrl||""}${t}${m?`?${m}`:""}`,{...T,headers:{...T.headers||{},...a&&a!=="multipart/form-data"?{"Content-Type":a}:{}},signal:(i?this.createAbortSignal(i):T.signal)||null,body:typeof e>"u"||e===null?null:d(e)}).then(async(U)=>{let v=U;v.data=null,v.error=null;let j=!o?v:await U[o]().then((s)=>{if(v.ok)v.data=s;else v.error=s;return v}).catch((s)=>{return v.error=s,v});if(i)this.abortControllers.delete(i);if(!U.ok)throw j;return j})}}class N extends B{v1={getNftSeriesById:(e,n,t,a={})=>this.request({path:`/v1/series/${e}/${n}`,method:"GET",query:t,format:"json",...a}),getTeamLeaderboard:(e,n={})=>this.request({path:"/v1/teams/leaderboard",method:"GET",query:e,format:"json",...n}),check:(e,n={})=>this.request({path:`/v1/check/${e}`,method:"POST",format:"json",...n}),getCheckResult:(e,n={})=>this.request({path:`/v1/check/${e}`,method:"GET",format:"json",...n}),getTeamDetail:(e,n={})=>this.request({path:`/v1/teams/${e}/detail`,method:"GET",format:"json",...n}),markNotificationRead:(e,n={})=>this.request({path:`/v1/notifications/${e}/read`,method:"POST",format:"json",...n}),listSeasonConfig:(e={})=>this.request({path:"/v1/seasons",method:"GET",format:"json",...e}),getBadgeContributors:(e,n={})=>this.request({path:`/v1/teams/badges/${e}/contributors`,method:"GET",format:"json",...n}),badgeAssets:(e,n={})=>this.request({path:"/v1/badges",method:"GET",query:e,format:"json",...n}),getTeamMemberRanking:(e,n,t={})=>this.request({path:`/v1/teams/${e}/members/ranking`,method:"GET",query:n,format:"json",...t}),getTeamBadges:(e,n={})=>this.request({path:"/v1/teams/badges",method:"GET",query:e,format:"json",...n}),nftSeries:(e,n={})=>this.request({path:`/v1/series/${e}`,method:"GET",format:"json",...n}),getMyTeamProfile:(e={})=>this.request({path:"/v1/teams/members/me",method:"GET",format:"json",...e}),getNotifications:(e,n={})=>this.request({path:"/v1/notifications",method:"GET",query:e,format:"json",...n}),userOpHashProcess:(e,n={})=>this.request({path:"/v1/transaction/process/userOpHash",method:"POST",body:e,type:"application/json",format:"json",...n}),transactionHashProcess:(e,n={})=>this.request({path:`/v1/transaction/process/${e}`,method:"POST",format:"json",...n})};v2={getUserClaimableBadges:(e,n={})=>this.request({path:"/v2/badges/claimable",method:"GET",query:e,format:"json",...n}),getBadgeSeriesDetail:(e,n,t={})=>this.request({path:`/v2/badges/series/${e}`,method:"GET",query:n,format:"json",...t}),getUserBadgeAssets:(e,n={})=>this.request({path:"/v2/badges/assets",method:"GET",query:e,format:"json",...n}),getBadgeVerifiers:(e,n={})=>this.request({path:"/v2/badges/verifiers",method:"GET",query:e,format:"json",...n}),checkUserClaimableBadges:(e,n={})=>this.request({path:"/v2/badges",method:"POST",body:e,type:"application/json",format:"json",...n}),getBadgeSeries:(e,n={})=>this.request({path:"/v2/badges/series",method:"GET",query:e,format:"json",...n}),mint:(e,n,t={})=>this.request({path:`/v2/mint/${e}`,method:"POST",body:n,type:"application/json",format:"json",...t}),batchMint:(e,n,t={})=>this.request({path:`/v2/batch/mint/${e}`,method:"POST",body:n,type:"application/json",format:"json",...t}),getBadgeClaimSignatures:(e,n={})=>this.request({path:"/v2/badges/signatures",method:"POST",body:e,type:"application/json",format:"json",...n}),checkSingleBadgeClaimable:(e,n,t={})=>this.request({path:`/v2/badges/${e}`,method:"POST",body:n,type:"application/json",format:"json",...t}),getBadgeDetail:(e,n={})=>this.request({path:`/v2/badges/${e}`,method:"GET",format:"json",...n})};s1={leaveTeam:(e,n={})=>this.request({path:`/s1/teams/leave/${e}`,method:"DELETE",format:"json",...n}),joinTeam:(e,n={})=>this.request({path:"/s1/teams/join",method:"POST",body:e,type:"application/json",format:"json",...n}),getNftSeriesDetail:(e,n,t,a={})=>this.request({path:`/s1/series/${e}/${n}`,method:"GET",query:t,format:"json",...a}),removeTeamMember:(e,n,t={})=>this.request({path:`/s1/teams/remove/${e}/${n}`,method:"DELETE",format:"json",...t}),intervalReset:(e,n={})=>this.request({path:"/s1/interval/reset",method:"POST",body:e,type:"application/json",format:"json",...n}),grantBadge:(e,n={})=>this.request({path:"/s1/badges",method:"POST",body:e,type:"application/json",format:"json",...n}),purchaseMint:(e,n,t={})=>this.request({path:`/s1/purchase/${e}`,method:"POST",body:n,type:"application/json",format:"json",...t}),queryAssets:(e,n,t={})=>this.request({path:`/s1/assets/${e}`,method:"POST",body:n,type:"application/json",format:"json",...t}),createTeam:(e,n={})=>this.request({path:"/s1/teams",method:"POST",body:e,type:"application/json",format:"json",...n}),checkByEvent:(e,n={})=>this.request({path:"/s1/check/event",method:"POST",body:e,type:"application/json",format:"json",...n}),badgesCheck:(e,n={})=>this.request({path:"/s1/badges/check",method:"POST",body:e,type:"application/json",format:"json",...n})}}class X{generatedApi;network;authToken;projectId;chainId;onTokenExpired;constructor(e){this.network=e.network,this.authToken=e.authToken,this.projectId=e.projectId,this.chainId=e.network.id.toString(),this.onTokenExpired=e.onTokenExpired,this.generatedApi=new N({baseUrl:e.apiBaseUrl.endsWith("/")?e.apiBaseUrl.slice(0,-1):e.apiBaseUrl})}setAuthToken(e){this.authToken=e}setTokenExpiredCallback(e){this.onTokenExpired=e}setProjectId(e){this.projectId=e}setChainId(e){this.chainId=e}createHeaders(){let e={"Content-Type":"application/json"};if(this.authToken)e.Authorization=`Bearer ${this.authToken}`,e.jwt_token=`${this.authToken}`;if(this.projectId)e["X-Project-Id"]=this.projectId,e.saas_id=this.projectId;if(this.chainId)e["X-Chain-Id"]=this.chainId,e.chain_id=this.chainId;return e}getRequestParams(){return{headers:this.createHeaders()}}async handleApiCall(e){try{let n=await e();if(this.isTokenExpiredResponse(n)){console.log("Token expired: JWT token is invalid or expired");let t=Error("Token expired: JWT token is invalid or expired");if(this.onTokenExpired)this.onTokenExpired(t);throw t}return n}catch(n){if(n?.status===401){if(this.onTokenExpired)this.onTokenExpired(n)}throw n}}isTokenExpiredResponse(e){if(e?.success===!1&&e?.code==="9101")return!0;if(e?.success===!1&&e?.msgKey==="params.jwt.check.invalid")return!0;return!1}async getBadgeVerifiers(e,n){return this.handleApiCall(async()=>{let t={platform:e,type:n};return(await this.generatedApi.v2.getBadgeVerifiers(t,this.getRequestParams())).data})}async getUserClaimableBadges(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getUserClaimableBadges(e,this.getRequestParams())).data})}async getUserBadgeAssets(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getUserBadgeAssets(e,this.getRequestParams())).data})}async getBadgeSeriesDetail(e,n){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getBadgeSeriesDetail(e,n,this.getRequestParams())).data})}async getBadgeDetail(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getBadgeDetail(e,this.getRequestParams())).data})}async checkSingleBadgeClaimable(e,n){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.checkSingleBadgeClaimable(e,n,this.getRequestParams())).data})}async checkUserClaimableBadges(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.checkUserClaimableBadges(e,this.getRequestParams())).data})}async getBadgeClaimSignatures(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getBadgeClaimSignatures(e,this.getRequestParams())).data})}async getBadgeSeries(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.getBadgeSeries(e,this.getRequestParams())).data})}async mint(e,n){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.mint(e,n,this.getRequestParams())).data})}async batchMint(e,n){return this.handleApiCall(async()=>{return(await this.generatedApi.v2.batchMint(e,n,this.getRequestParams())).data})}async transactionHashProcess(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v1.transactionHashProcess(e,this.getRequestParams())).data})}async userOpHashProcess(e){return this.handleApiCall(async()=>{return(await this.generatedApi.v1.userOpHashProcess(e,this.getRequestParams())).data})}}import{concat as H,encodeAbiParameters as P,encodeFunctionData as ne,keccak256 as E,stringToHex as W}from"viem";var O=[{type:"constructor",inputs:[],stateMutability:"nonpayable"},{type:"function",name:"DEFAULT_ADMIN_ROLE",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"UPGRADE_INTERFACE_VERSION",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"badgeToProject",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"balanceOf",inputs:[{name:"account",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"balanceOfBatch",inputs:[{name:"accounts",type:"address[]",internalType:"address[]"},{name:"ids",type:"uint256[]",internalType:"uint256[]"}],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"burnBatch",inputs:[{name:"from",type:"address",internalType:"address"},{name:"ids",type:"uint256[]",internalType:"uint256[]"},{name:"values",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"calculateProjectTokenId",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"projectTokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"pure"},{type:"function",name:"createBatch",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"_to",type:"address",internalType:"address"},{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"},{name:"_maxSupplies",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"createBatch",inputs:[{name:"_to",type:"address",internalType:"address"},{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"},{name:"_maxSupplies",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"eip712Domain",inputs:[],outputs:[{name:"fields",type:"bytes1",internalType:"bytes1"},{name:"name",type:"string",internalType:"string"},{name:"version",type:"string",internalType:"string"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"verifyingContract",type:"address",internalType:"address"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"extensions",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"exists",inputs:[{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"getRoleAdmin",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"grantAdminRole",inputs:[{name:"admin",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"grantProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"grantRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"hasRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"initialize",inputs:[{name:"_defaultAdmin",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_symbol",type:"string",internalType:"string"},{name:"_version",type:"string",internalType:"string"},{name:"_baseURI",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"account",type:"address",internalType:"address"},{name:"operator",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"mintWithSignature",inputs:[{name:"_req",type:"tuple",internalType:"struct AnchorDataTypes.MintRequest",components:[{name:"to",type:"address",internalType:"address"},{name:"tokenId",type:"uint256",internalType:"uint256"},{name:"quantity",type:"uint256",internalType:"uint256"},{name:"price",type:"uint256",internalType:"uint256"},{name:"currency",type:"address",internalType:"address"},{name:"validityStartTimestamp",type:"uint128",internalType:"uint128"},{name:"validityEndTimestamp",type:"uint128",internalType:"uint128"},{name:"uid",type:"bytes32",internalType:"bytes32"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"projectHandle",type:"bytes32",internalType:"bytes32"}]},{name:"_signature",type:"bytes",internalType:"bytes"}],outputs:[{name:"signer",type:"address",internalType:"address"}],stateMutability:"payable"},{type:"function",name:"multicall",inputs:[{name:"data",type:"bytes[]",internalType:"bytes[]"}],outputs:[{name:"results",type:"bytes[]",internalType:"bytes[]"}],stateMutability:"nonpayable"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"nextTokenIdToMint",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"projectTotalSupply",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"proxiableUUID",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"renounceRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"callerConfirmation",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"revokeProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"revokeRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"safeBatchTransferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"ids",type:"uint256[]",internalType:"uint256[]"},{name:"values",type:"uint256[]",internalType:"uint256[]"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"safeTransferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setApprovalForAll",inputs:[{name:"operator",type:"address",internalType:"address"},{name:"approved",type:"bool",internalType:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setMaxSupply",inputs:[{name:"_tokenId",type:"uint256",internalType:"uint256"},{name:"_maxSupply",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setRegistry",inputs:[{name:"registry",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setURIs",inputs:[{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setup",inputs:[{name:"_name",type:"string",internalType:"string"},{name:"_symbol",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"supportsInterface",inputs:[{name:"interfaceId",type:"bytes4",internalType:"bytes4"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"pure"},{type:"function",name:"symbol",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenReceived",inputs:[{name:"token",type:"address",internalType:"address"},{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"userData",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"totalSupply",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalSupply",inputs:[{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"upgradeTo",inputs:[{name:"newImplementation",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"upgradeToAndCall",inputs:[{name:"newImplementation",type:"address",internalType:"address"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"payable"},{type:"function",name:"uri",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AnchorInitialized",inputs:[{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ApprovalForAll",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"approved",type:"bool",indexed:!1,internalType:"bool"}],anonymous:!1},{type:"event",name:"BatchBurned",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"BatchCreated",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"projectTokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"tokenURIs",type:"string[]",indexed:!1,internalType:"string[]"},{name:"maxSupply",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"BatchURI",inputs:[{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"tokenURIs",type:"string[]",indexed:!1,internalType:"string[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"Initialized",inputs:[{name:"version",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"MaxSupplyUpdated",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"maxSupply",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"tokenId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"quantity",type:"uint256",indexed:!1,internalType:"uint256"},{name:"price",type:"uint256",indexed:!1,internalType:"uint256"},{name:"currency",type:"address",indexed:!1,internalType:"address"},{name:"uid",type:"bytes32",indexed:!1,internalType:"bytes32"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ProjectOperatorGranted",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ProjectOperatorRevoked",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"RoleAdminChanged",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"previousAdminRole",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"newAdminRole",type:"bytes32",indexed:!0,internalType:"bytes32"}],anonymous:!1},{type:"event",name:"RoleGranted",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"RoleRevoked",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"TransferBatch",inputs:[{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"ids",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"TransferSingle",inputs:[{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"uint256",indexed:!1,internalType:"uint256"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"URI",inputs:[{name:"value",type:"string",indexed:!1,internalType:"string"},{name:"id",type:"uint256",indexed:!0,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Upgraded",inputs:[{name:"implementation",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"error",name:"AccessControlBadConfirmation",inputs:[]},{type:"error",name:"AccessControlUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"},{name:"neededRole",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"AddressNotSet",inputs:[]},{type:"error",name:"ArrayLengthMismatch",inputs:[]},{type:"error",name:"ECDSAInvalidSignature",inputs:[]},{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"ERC1155InsufficientBalance",inputs:[{name:"sender",type:"address",internalType:"address"},{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"},{name:"tokenId",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC1155InvalidApprover",inputs:[{name:"approver",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidArrayLength",inputs:[{name:"idsLength",type:"uint256",internalType:"uint256"},{name:"valuesLength",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC1155InvalidOperator",inputs:[{name:"operator",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidReceiver",inputs:[{name:"receiver",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidSender",inputs:[{name:"sender",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155MissingApprovalForAll",inputs:[{name:"operator",type:"address",internalType:"address"},{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"ERC1967InvalidImplementation",inputs:[{name:"implementation",type:"address",internalType:"address"}]},{type:"error",name:"ERC1967NonPayable",inputs:[]},{type:"error",name:"EmptyArray",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InvalidChainId",inputs:[]},{type:"error",name:"InvalidInitialization",inputs:[]},{type:"error",name:"InvalidParameter",inputs:[]},{type:"error",name:"InvalidPayment",inputs:[]},{type:"error",name:"InvalidReceiver",inputs:[]},{type:"error",name:"InvalidRegistry",inputs:[]},{type:"error",name:"InvalidSignature",inputs:[]},{type:"error",name:"InvalidTokenId",inputs:[]},{type:"error",name:"MaxSupplyExceeded",inputs:[]},{type:"error",name:"NonTransferableToken",inputs:[]},{type:"error",name:"NotInitializing",inputs:[]},{type:"error",name:"NotProjectOperator",inputs:[]},{type:"error",name:"PaymentRequired",inputs:[]},{type:"error",name:"ProjectHandleZero",inputs:[]},{type:"error",name:"RecipientUndefined",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SignatureExpired",inputs:[]},{type:"error",name:"UUPSUnauthorizedCallContext",inputs:[]},{type:"error",name:"UUPSUnsupportedProxiableUUID",inputs:[{name:"slot",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"Unauthorized",inputs:[]},{type:"error",name:"ZeroQuantity",inputs:[]}];import{Contract as A,Interface as R}from"ethers";var K=[{type:"constructor",inputs:[],stateMutability:"nonpayable"},{type:"function",name:"DEFAULT_ADMIN_ROLE",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"UPGRADE_INTERFACE_VERSION",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"badgeToProject",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"balanceOf",inputs:[{name:"account",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"balanceOfBatch",inputs:[{name:"accounts",type:"address[]",internalType:"address[]"},{name:"ids",type:"uint256[]",internalType:"uint256[]"}],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"burnBatch",inputs:[{name:"from",type:"address",internalType:"address"},{name:"ids",type:"uint256[]",internalType:"uint256[]"},{name:"values",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"calculateProjectTokenId",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"projectTokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"pure"},{type:"function",name:"createBatch",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"_to",type:"address",internalType:"address"},{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"},{name:"_maxSupplies",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"createBatch",inputs:[{name:"_to",type:"address",internalType:"address"},{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"},{name:"_maxSupplies",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"eip712Domain",inputs:[],outputs:[{name:"fields",type:"bytes1",internalType:"bytes1"},{name:"name",type:"string",internalType:"string"},{name:"version",type:"string",internalType:"string"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"verifyingContract",type:"address",internalType:"address"},{name:"salt",type:"bytes32",internalType:"bytes32"},{name:"extensions",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"exists",inputs:[{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"getRoleAdmin",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"grantAdminRole",inputs:[{name:"admin",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"grantProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"grantRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"hasRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"initialize",inputs:[{name:"_defaultAdmin",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_symbol",type:"string",internalType:"string"},{name:"_version",type:"string",internalType:"string"},{name:"_baseURI",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"account",type:"address",internalType:"address"},{name:"operator",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"mintWithSignature",inputs:[{name:"_req",type:"tuple",internalType:"struct AnchorDataTypes.MintRequest",components:[{name:"to",type:"address",internalType:"address"},{name:"tokenId",type:"uint256",internalType:"uint256"},{name:"quantity",type:"uint256",internalType:"uint256"},{name:"price",type:"uint256",internalType:"uint256"},{name:"currency",type:"address",internalType:"address"},{name:"validityStartTimestamp",type:"uint128",internalType:"uint128"},{name:"validityEndTimestamp",type:"uint128",internalType:"uint128"},{name:"uid",type:"bytes32",internalType:"bytes32"},{name:"chainId",type:"uint256",internalType:"uint256"},{name:"projectHandle",type:"bytes32",internalType:"bytes32"}]},{name:"_signature",type:"bytes",internalType:"bytes"}],outputs:[{name:"signer",type:"address",internalType:"address"}],stateMutability:"payable"},{type:"function",name:"multicall",inputs:[{name:"data",type:"bytes[]",internalType:"bytes[]"}],outputs:[{name:"results",type:"bytes[]",internalType:"bytes[]"}],stateMutability:"nonpayable"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"nextTokenIdToMint",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"projectTotalSupply",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"proxiableUUID",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"renounceRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"callerConfirmation",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"revokeProjectOperator",inputs:[{name:"projectHandle",type:"bytes32",internalType:"bytes32"},{name:"operator",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"revokeRole",inputs:[{name:"role",type:"bytes32",internalType:"bytes32"},{name:"account",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"safeBatchTransferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"ids",type:"uint256[]",internalType:"uint256[]"},{name:"values",type:"uint256[]",internalType:"uint256[]"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"safeTransferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setApprovalForAll",inputs:[{name:"operator",type:"address",internalType:"address"},{name:"approved",type:"bool",internalType:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setMaxSupply",inputs:[{name:"_tokenId",type:"uint256",internalType:"uint256"},{name:"_maxSupply",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setRegistry",inputs:[{name:"registry",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setURIs",inputs:[{name:"_tokenIds",type:"uint256[]",internalType:"uint256[]"},{name:"_tokenURIs",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setup",inputs:[{name:"_name",type:"string",internalType:"string"},{name:"_symbol",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"supportsInterface",inputs:[{name:"interfaceId",type:"bytes4",internalType:"bytes4"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"pure"},{type:"function",name:"symbol",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenReceived",inputs:[{name:"token",type:"address",internalType:"address"},{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"userData",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"totalSupply",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalSupply",inputs:[{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"upgradeTo",inputs:[{name:"newImplementation",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"upgradeToAndCall",inputs:[{name:"newImplementation",type:"address",internalType:"address"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"payable"},{type:"function",name:"uri",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AnchorInitialized",inputs:[{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ApprovalForAll",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"approved",type:"bool",indexed:!1,internalType:"bool"}],anonymous:!1},{type:"event",name:"BatchBurned",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"BatchCreated",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"projectTokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"tokenURIs",type:"string[]",indexed:!1,internalType:"string[]"},{name:"maxSupply",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"BatchURI",inputs:[{name:"tokenIds",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"tokenURIs",type:"string[]",indexed:!1,internalType:"string[]"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"EIP712DomainChanged",inputs:[],anonymous:!1},{type:"event",name:"Initialized",inputs:[{name:"version",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"MaxSupplyUpdated",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"maxSupply",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"tokenId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"quantity",type:"uint256",indexed:!1,internalType:"uint256"},{name:"price",type:"uint256",indexed:!1,internalType:"uint256"},{name:"currency",type:"address",indexed:!1,internalType:"address"},{name:"uid",type:"bytes32",indexed:!1,internalType:"bytes32"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ProjectOperatorGranted",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ProjectOperatorRevoked",inputs:[{name:"projectHandle",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"RoleAdminChanged",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"previousAdminRole",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"newAdminRole",type:"bytes32",indexed:!0,internalType:"bytes32"}],anonymous:!1},{type:"event",name:"RoleGranted",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"RoleRevoked",inputs:[{name:"role",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"TransferBatch",inputs:[{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"ids",type:"uint256[]",indexed:!1,internalType:"uint256[]"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"TransferSingle",inputs:[{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"uint256",indexed:!1,internalType:"uint256"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"URI",inputs:[{name:"value",type:"string",indexed:!1,internalType:"string"},{name:"id",type:"uint256",indexed:!0,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Upgraded",inputs:[{name:"implementation",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"error",name:"AccessControlBadConfirmation",inputs:[]},{type:"error",name:"AccessControlUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"},{name:"neededRole",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"AddressNotSet",inputs:[]},{type:"error",name:"ArrayLengthMismatch",inputs:[]},{type:"error",name:"ECDSAInvalidSignature",inputs:[]},{type:"error",name:"ECDSAInvalidSignatureLength",inputs:[{name:"length",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ECDSAInvalidSignatureS",inputs:[{name:"s",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"ERC1155InsufficientBalance",inputs:[{name:"sender",type:"address",internalType:"address"},{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"},{name:"tokenId",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC1155InvalidApprover",inputs:[{name:"approver",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidArrayLength",inputs:[{name:"idsLength",type:"uint256",internalType:"uint256"},{name:"valuesLength",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC1155InvalidOperator",inputs:[{name:"operator",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidReceiver",inputs:[{name:"receiver",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155InvalidSender",inputs:[{name:"sender",type:"address",internalType:"address"}]},{type:"error",name:"ERC1155MissingApprovalForAll",inputs:[{name:"operator",type:"address",internalType:"address"},{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"ERC1967InvalidImplementation",inputs:[{name:"implementation",type:"address",internalType:"address"}]},{type:"error",name:"ERC1967NonPayable",inputs:[]},{type:"error",name:"EmptyArray",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InvalidChainId",inputs:[]},{type:"error",name:"InvalidInitialization",inputs:[]},{type:"error",name:"InvalidParameter",inputs:[]},{type:"error",name:"InvalidPayment",inputs:[]},{type:"error",name:"InvalidReceiver",inputs:[]},{type:"error",name:"InvalidRegistry",inputs:[]},{type:"error",name:"InvalidSignature",inputs:[]},{type:"error",name:"InvalidTokenId",inputs:[]},{type:"error",name:"MaxSupplyExceeded",inputs:[]},{type:"error",name:"NonTransferableToken",inputs:[]},{type:"error",name:"NotInitializing",inputs:[]},{type:"error",name:"NotProjectOperator",inputs:[]},{type:"error",name:"PaymentRequired",inputs:[]},{type:"error",name:"ProjectHandleZero",inputs:[]},{type:"error",name:"RecipientUndefined",inputs:[]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SignatureExpired",inputs:[]},{type:"error",name:"UUPSUnauthorizedCallContext",inputs:[]},{type:"error",name:"UUPSUnsupportedProxiableUUID",inputs:[{name:"slot",type:"bytes32",internalType:"bytes32"}]},{type:"error",name:"Unauthorized",inputs:[]},{type:"error",name:"ZeroQuantity",inputs:[]}];class I{static abi=K;static createInterface(){return new R(K)}static connect(e,n){return new A(e,K,n)}}import{Contract as Ne,Interface as Ke}from"ethers";class _{publicClient;walletClient;account;network;contracts;constructor(e,n,t,a,y){this.publicClient=e,this.network=n,this.walletClient=t,this.account=a,this.contracts=y||{}}async getTokenURI(e){if(!this.contracts?.anchorERC1155)throw Error("AnchorERC1155 contract address not set, please check network configuration");return await this.publicClient.readContract({address:this.contracts.anchorERC1155,abi:O,functionName:"uri",args:[e]})}async getName(){if(!this.contracts?.anchorERC1155)throw Error("AnchorERC1155 contract address not set, please check network configuration");return await this.publicClient.readContract({address:this.contracts.anchorERC1155,abi:O,functionName:"name"})}async getSymbol(){if(!this.contracts?.anchorERC1155)throw Error("AnchorERC1155 contract address not set, please check network configuration");return await this.publicClient.readContract({address:this.contracts.anchorERC1155,abi:O,functionName:"symbol"})}async mintWithSignature(e,n,t){if(BigInt(e.request.price)!==0n)throw Error("mintWithSignature method can only be used to mint free tokens");let a=n||this.contracts?.anchorERC1155,y=I.createInterface().encodeFunctionData("mintWithSignature",[this.formatMintRequest(e.request),e.signature]);if(console.log(y,"data"),t?.sendTransaction===!1)return{to:a,data:y,value:0n};if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let{maxFeePerGas:r,maxPriorityFeePerGas:l}=await this.publicClient.estimateFeesPerGas(),i=await this.publicClient.estimateGas({to:a,data:y,value:0n,account:this.account}),p=await this.walletClient.writeContract({account:this.account,address:a,abi:I.abi,functionName:"mintWithSignature",args:[this.formatMintRequest(e.request),e.signature],chain:this.publicClient.chain,maxFeePerGas:r,maxPriorityFeePerGas:l,gas:i});return await this.publicClient.waitForTransactionReceipt({hash:p})}encodeTokenReceivedData(e){let n=E(W("AnchorERC1155")),t=e.signature.startsWith("0x")?e.signature:`0x${e.signature}`,a=this.formatMintRequest(e.request);console.log("Formatted request data:",JSON.stringify(a,(r,l)=>typeof l==="bigint"?l.toString():l)),console.log("Signature:",t);let y=P([{components:[{name:"to",type:"address"},{name:"tokenId",type:"uint256"},{name:"quantity",type:"uint256"},{name:"price",type:"uint256"},{name:"currency",type:"address"},{name:"validityStartTimestamp",type:"uint128"},{name:"validityEndTimestamp",type:"uint128"},{name:"uid",type:"bytes32"},{name:"chainId",type:"uint256"},{name:"projectHandle",type:"bytes32"}],name:"req",type:"tuple"},{name:"signature",type:"bytes"}],[a,t]);return console.log("Encoded userData:",y),H([n,y])}encodeTokenReceivedDataWithEmptyInterface(e){let n=E(W("")),t=e.signature.startsWith("0x")?e.signature:`0x${e.signature}`,a=this.formatMintRequest(e.request);console.log("Formatted request data (empty interface):",JSON.stringify(a,(r,l)=>typeof l==="bigint"?l.toString():l)),console.log("Signature:",t);let y=P([{components:[{name:"to",type:"address"},{name:"tokenId",type:"uint256"},{name:"quantity",type:"uint256"},{name:"price",type:"uint256"},{name:"currency",type:"address"},{name:"validityStartTimestamp",type:"uint128"},{name:"validityEndTimestamp",type:"uint128"},{name:"uid",type:"bytes32"},{name:"chainId",type:"uint256"},{name:"projectHandle",type:"bytes32"}],name:"req",type:"tuple"},{name:"signature",type:"bytes"}],[a,t]);return console.log("Encoded userData (empty interface):",y),H([n,y])}async multicall(e,n){if(!this.contracts?.anchorERC1155)throw Error("AnchorERC1155 contract address not set, please check network configuration");let t=this.contracts.anchorERC1155,a=ne({abi:O,functionName:"multicall",args:[e]});if(n?.sendTransaction===!1)return{to:t,data:a,value:0n};if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let{maxFeePerGas:y,maxPriorityFeePerGas:r}=await this.publicClient.estimateFeesPerGas(),l=await this.publicClient.estimateGas({to:t,data:a,value:0n,account:this.account}),i=await this.walletClient.writeContract({account:this.account,address:t,abi:O,functionName:"multicall",args:[e],chain:this.publicClient.chain,maxFeePerGas:y,maxPriorityFeePerGas:r,gas:l});return await this.publicClient.waitForTransactionReceipt({hash:i})}formatMintRequest(e){let n;if(typeof e.uid==="string")if(e.uid.startsWith("0x"))n=e.uid;else n=E(W(e.uid));else n=e.uid;let t=BigInt(Math.floor(Date.now()/1000));return{to:e.to,tokenId:BigInt(e.tokenId),quantity:BigInt(e.quantity),price:BigInt(e.price),currency:e.currency,validityStartTimestamp:e.validityStartTimestamp?BigInt(e.validityStartTimestamp):t,validityEndTimestamp:e.validityEndTimestamp?BigInt(e.validityEndTimestamp):e.validUntil?BigInt(e.validUntil):t+3600n,uid:n,chainId:BigInt(e.chainId||this.network.id),projectHandle:e.projectHandle}}}import{encodeFunctionData as f}from"viem";var x=[{type:"constructor",inputs:[],stateMutability:"nonpayable"},{type:"function",name:"UPGRADE_INTERFACE_VERSION",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"acceptOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"balanceOf",inputs:[{name:"account",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"depositFor",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"getInterfaceImplementer",inputs:[{name:"account",type:"address",internalType:"address"},{name:"_interfaceHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"initialize",inputs:[{name:"_defaultAdmin",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"pendingOwner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"proxiableUUID",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"send",inputs:[{name:"recipient",type:"address",internalType:"address"},{name:"token",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setInterfaceImplementer",inputs:[{name:"account",type:"address",internalType:"address"},{name:"_interfaceHash",type:"bytes32",internalType:"bytes32"},{name:"implementer",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"upgradeToAndCall",inputs:[{name:"newImplementation",type:"address",internalType:"address"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"payable"},{type:"function",name:"withdraw",inputs:[{name:"token",type:"address",internalType:"address"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Deposited",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"token",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Initialized",inputs:[{name:"version",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"InterfaceImplementerSet",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"interfaceHash",type:"bytes32",indexed:!0,internalType:"bytes32"},{name:"implementer",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"OwnershipTransferStarted",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paid",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"data",type:"bytes",indexed:!1,internalType:"bytes"}],anonymous:!1},{type:"event",name:"Upgraded",inputs:[{name:"implementation",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Withdrawn",inputs:[{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"token",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"AddressNotSet",inputs:[]},{type:"error",name:"ERC1967InvalidImplementation",inputs:[{name:"implementation",type:"address",internalType:"address"}]},{type:"error",name:"ERC1967NonPayable",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[]},{type:"error",name:"InsufficientPayment",inputs:[]},{type:"error",name:"InvalidAddress",inputs:[]},{type:"error",name:"InvalidAmount",inputs:[]},{type:"error",name:"InvalidInitialization",inputs:[]},{type:"error",name:"InvalidMsgValue",inputs:[]},{type:"error",name:"InvalidState",inputs:[]},{type:"error",name:"NotInitializing",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"PaymentTransferFailed",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]},{type:"error",name:"UUPSUnauthorizedCallContext",inputs:[]},{type:"error",name:"UUPSUnsupportedProxiableUUID",inputs:[{name:"slot",type:"bytes32",internalType:"bytes32"}]}];import{abstract as ae,abstractTestnet as G,base as ye,baseSepolia as h,berachain as pe,berachainBepolia as F,ronin as ie,saigon as L}from"viem/chains";var le;((a)=>{a.DEV="dev";a.BETA="beta";a.PROD="prod"})(le||={});var M=[{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}],Z={dev:{apiBaseUrl:"https://anchordev.dipbit.xyz",contracts:{[L.id]:{anchorPay:"0x8551891728967D2D7b6B502eF5339EEb2281143a",anchorERC1155:"0x23Da7778F6152D7B91C20808bEF7163c5EC2C470"},[h.id]:{anchorPay:"0x2C69537d9b82d2C863BCfF3442D1c4E7633ead7c",anchorERC1155:"0x1CE9506cdDdD304AA753c0E8f1F898ab97Ec2870"},[F.id]:{anchorPay:"0x80635645c4B4dA367F2eE6D8F38BED1c2CF8C484",anchorERC1155:"0x20a6e4aa138cF4635c0abFC79272FBeB8a116F36"},[G.id]:{anchorPay:"0xc5c1606fDe120018E74751253F572796EDbaBC09",anchorERC1155:"0x0E03d8fA4A37287eabfb2e5BBdc7AcD7C1D3e869"},["1962"]:{anchorERC1155:"0xa670ca0270c46876e5a78c9a7c596bfef91185a8"}}},beta:{apiBaseUrl:"https://anchorbeta.dipbit.xyz",contracts:{[L.id]:{anchorPay:"0xcbA8A3FE5fa94A807143bC2467A012010b02Cd94",anchorERC1155:"0x4a4D5888A284fED88fbE998c2C59957CE87923D2"},[h.id]:{anchorPay:"0x2EB31dAbb95F3697eC6bBfE0c41b55D9C321571e",anchorERC1155:"0xE78F00BBD1be39Db6C404142Cf4a3A2471A915e7"},[F.id]:{anchorPay:"0x382F7946378e8A7A848d04166083711c90D76061",anchorERC1155:"0x99eed4522a3Da62CaEE3e87BfFd3779d7d5EF853"},[G.id]:{anchorPay:"0x7dc99a343555711aB92fc844d0Df657161df7D67",anchorERC1155:"0xa34F267d3Ab2Ce21CBD1F04F593300f6CB609a29"},["1962"]:{anchorERC1155:"0xa51B53Dc3aA7f4ef5fE9bb429521a73f411ad867"}}},prod:{apiBaseUrl:"https://api-anchor.deek.network",contracts:{[ae.id]:{anchorPay:"0xf87C02027f36067a87E4eaeeD61b7Ce2ffE0813A",anchorERC1155:"0xd6895dc1740e057D564C795923542122f1513142"},[ye.id]:{anchorPay:"0x56f0fAF3a0336F57289e61Be6F32380B38C171E1"},[ie.id]:{anchorPay:"0x56f0fAF3a0336F57289e61Be6F32380B38C171E1",anchorERC1155:"0xA412f7D0B39c7451E9A8a34a66f0D69CB5A378dA"},[pe.id]:{anchorPay:"0x4567890123456789012345678901234567890123",anchorERC1155:"0xdefabcdefabcdefabcdefabcdefabcdefabcdefab"}}}},nn={TOKEN_RECEIVED:"0x8b2cb2c7b7e2282e2e4b29a6a8c2b2db4218c6a5f8e8fcb3d5598f3e1e6c59d9"},z="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",w="0xcA11bde05977b3631167028862bE2a173976CA11",J=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall3.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"payable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bool",name:"allowFailure",type:"bool"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall3.Call3[]",name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall3.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"payable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bool",name:"allowFailure",type:"bool"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall3.Call3Value[]",name:"calls",type:"tuple[]"}],name:"aggregate3Value",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall3.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"payable",type:"function"}];class S{publicClient;walletClient;account;network;contracts;constructor(e,n,t,a,y){this.publicClient=e,this.network=n,this.walletClient=t,this.account=a,this.contracts=y||{}}async sendETH(e,n,t="0x",a){if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=f({abi:x,functionName:"send",args:[e,z,n,t]});if(a?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:y,value:n};let{maxFeePerGas:r,maxPriorityFeePerGas:l}=await this.publicClient.estimateFeesPerGas(),i=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:y,value:n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let p=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:y,value:n,maxFeePerGas:a?.maxFeePerGas||r,maxPriorityFeePerGas:a?.maxPriorityFeePerGas||l,gas:a?.gas||i,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:p})}async sendERC20(e,n,t,a="0x",y){if(y?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");if(y?.autoApprove!==!1&&this.walletClient&&this.account)try{console.log(`Checking ERC20 token approval status: ${n}`);let m=await this.publicClient.readContract({address:n,abi:M,functionName:"allowance",args:[this.account.address,this.contracts?.anchorPay]});if(console.log(`Current allowance: ${m}, Required amount: ${t}, AnchorPay contract address: ${this.contracts?.anchorPay}`),m<t){console.log(`Approving ${t} tokens to AnchorPay contract...`);let d=2n**256n-1n,{maxFeePerGas:o,maxPriorityFeePerGas:U}=await this.publicClient.estimateFeesPerGas(),v=f({abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d]}),j=await this.publicClient.estimateGas({to:n,data:v,value:0n,account:this.account}),s=await this.walletClient.writeContract({account:this.account,address:n,abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d],chain:this.publicClient.chain,maxFeePerGas:o,maxPriorityFeePerGas:U,gas:j});console.log(`Approval transaction sent, hash: ${s}`),await this.publicClient.waitForTransactionReceipt({hash:s}),console.log("Approval transaction confirmed")}else console.log("Sufficient allowance already exists, no need for additional approval")}catch(m){throw console.error("Approval failed:",m),Error(`ERC20 approval failed: ${m instanceof Error?m.message:String(m)}`)}let r=f({abi:x,functionName:"send",args:[e,n,t,a]});if(y?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:r,value:0n};let{maxFeePerGas:l,maxPriorityFeePerGas:i}=await this.publicClient.estimateFeesPerGas(),p=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:r,value:0n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let u=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:r,maxFeePerGas:y?.maxFeePerGas||l,maxPriorityFeePerGas:y?.maxPriorityFeePerGas||i,gas:y?.gas||p,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:u})}async getInterfaceImplementer(e,n){return await this.publicClient.readContract({address:this.contracts?.anchorPay||"",abi:x,functionName:"getInterfaceImplementer",args:[e,n]})}async setInterfaceImplementer(e,n,t){if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let{maxFeePerGas:a,maxPriorityFeePerGas:y}=await this.publicClient.estimateFeesPerGas(),r=f({abi:x,functionName:"setInterfaceImplementer",args:[e,n,t]}),l=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:r,value:0n,account:this.account}),i=await this.walletClient.writeContract({account:this.account,address:this.contracts?.anchorPay||"",abi:x,functionName:"setInterfaceImplementer",args:[e,n,t],chain:this.publicClient.chain,maxFeePerGas:a,maxPriorityFeePerGas:y,gas:l});return await this.publicClient.waitForTransactionReceipt({hash:i})}getERC20ApprovalData(e,n,t){let a=t||this.contracts?.anchorPay||"",y=f({abi:M,functionName:"approve",args:[a,n]});return{to:e,data:y,value:0n}}async balanceOf(e,n){return await this.publicClient.readContract({address:this.contracts?.anchorPay||"",abi:x,functionName:"balanceOf",args:[e,n]})}async depositETH(e,n,t){if(t?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let a=f({abi:x,functionName:"depositFor",args:[e,z,n]});if(t?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:a,value:n};let{maxFeePerGas:y,maxPriorityFeePerGas:r}=await this.publicClient.estimateFeesPerGas(),l=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:a,value:n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let i=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:a,value:n,maxFeePerGas:t?.maxFeePerGas||y,maxPriorityFeePerGas:t?.maxPriorityFeePerGas||r,gas:t?.gas||l,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:i})}async depositERC20(e,n,t,a){if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");if(a?.autoApprove!==!1&&this.walletClient&&this.account)try{console.log(`Checking ERC20 token approval status: ${n}`);let T=await this.publicClient.readContract({address:n,abi:M,functionName:"allowance",args:[this.account.address,this.contracts?.anchorPay]});if(console.log(`Current allowance: ${T}, Required amount: ${t}, AnchorPay contract address: ${this.contracts?.anchorPay}`),T<t){console.log(`Approving ${t} tokens to AnchorPay contract...`);let m=2n**256n-1n,{maxFeePerGas:d,maxPriorityFeePerGas:o}=await this.publicClient.estimateFeesPerGas(),U=f({abi:M,functionName:"approve",args:[this.contracts?.anchorPay,m]}),v=await this.publicClient.estimateGas({to:n,data:U,value:0n,account:this.account}),j=await this.walletClient.writeContract({account:this.account,address:n,abi:M,functionName:"approve",args:[this.contracts?.anchorPay,m],chain:this.publicClient.chain,maxFeePerGas:d,maxPriorityFeePerGas:o,gas:v});console.log(`Approval transaction sent, hash: ${j}`),await this.publicClient.waitForTransactionReceipt({hash:j}),console.log("Approval transaction confirmed")}else console.log("Sufficient allowance already exists, no need for additional approval")}catch(T){throw console.error("Approval failed:",T),Error(`ERC20 approval failed: ${T instanceof Error?T.message:String(T)}`)}let y=f({abi:x,functionName:"depositFor",args:[e,n,t]});if(a?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:y,value:0n};let{maxFeePerGas:r,maxPriorityFeePerGas:l}=await this.publicClient.estimateFeesPerGas(),i=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:y,value:0n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let p=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:y,maxFeePerGas:a?.maxFeePerGas||r,maxPriorityFeePerGas:a?.maxPriorityFeePerGas||l,gas:a?.gas||i,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:p})}async withdraw(e,n,t){if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let{maxFeePerGas:a,maxPriorityFeePerGas:y}=await this.publicClient.estimateFeesPerGas(),r=f({abi:x,functionName:"withdraw",args:[e,n]}),l=await this.publicClient.estimateGas({to:this.contracts?.anchorPay||"",data:r,value:0n,account:this.account}),i=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:r,maxFeePerGas:t?.maxFeePerGas||a,maxPriorityFeePerGas:t?.maxPriorityFeePerGas||y,gas:t?.gas||l,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:i})}async batchDepositETH(e,n){if(e.length===0)throw Error("No deposits provided");if(n?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let t=e.map((T)=>{let m=f({abi:x,functionName:"depositFor",args:[T.recipient,z,T.amount]});return{target:this.contracts?.anchorPay||"",allowFailure:!1,value:T.amount,callData:m}}),a=e.reduce((T,m)=>T+m.amount,0n),y=f({abi:J,functionName:"aggregate3Value",args:[t]});if(n?.sendTransaction===!1)return{to:w,data:y,value:a};let{maxFeePerGas:r,maxPriorityFeePerGas:l}=await this.publicClient.estimateFeesPerGas(),i=await this.publicClient.estimateGas({to:w,data:y,value:a,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let p=await this.walletClient.sendTransaction({account:this.account,to:w,data:y,value:a,maxFeePerGas:n?.maxFeePerGas||r,maxPriorityFeePerGas:n?.maxPriorityFeePerGas||l,gas:n?.gas||i,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:p})}async batchDepositERC20(e,n,t){if(n.length===0)throw Error("No deposits provided");if(t?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let a=n.reduce((m,d)=>m+d.amount,0n);if(t?.autoApprove!==!1&&this.walletClient&&this.account)try{console.log(`Checking ERC20 token approval status: ${e}`);let m=await this.publicClient.readContract({address:e,abi:M,functionName:"allowance",args:[this.account.address,this.contracts?.anchorPay]});if(console.log(`Current allowance: ${m}, Required amount: ${a}, AnchorPay contract address: ${this.contracts?.anchorPay}`),m<a){console.log(`Approving ${a} tokens to AnchorPay contract...`);let d=2n**256n-1n,{maxFeePerGas:o,maxPriorityFeePerGas:U}=await this.publicClient.estimateFeesPerGas(),v=f({abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d]}),j=await this.publicClient.estimateGas({to:e,data:v,value:0n,account:this.account}),s=await this.walletClient.writeContract({account:this.account,address:e,abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d],chain:this.publicClient.chain,maxFeePerGas:o,maxPriorityFeePerGas:U,gas:j});console.log(`Approval transaction sent, hash: ${s}`),await this.publicClient.waitForTransactionReceipt({hash:s}),console.log("Approval transaction confirmed")}else console.log("Sufficient allowance already exists, no need for additional approval")}catch(m){throw console.error("Approval failed:",m),Error(`ERC20 approval failed: ${m instanceof Error?m.message:String(m)}`)}let y=n.map((m)=>{let d=f({abi:x,functionName:"depositFor",args:[m.recipient,e,m.amount]});return{target:this.contracts?.anchorPay||"",allowFailure:!1,value:0n,callData:d}}),r=f({abi:J,functionName:"aggregate3Value",args:[y]});if(t?.sendTransaction===!1)return{to:w,data:r,value:0n};let{maxFeePerGas:l,maxPriorityFeePerGas:i}=await this.publicClient.estimateFeesPerGas(),p=await this.publicClient.estimateGas({to:w,data:r,value:0n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let u=await this.walletClient.sendTransaction({account:this.account,to:w,data:r,maxFeePerGas:t?.maxFeePerGas||l,maxPriorityFeePerGas:t?.maxPriorityFeePerGas||i,gas:t?.gas||p,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:u})}async batchSendETH(e,n){if(e.length===0)throw Error("No transfers provided");if(n?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let t=e.map((T)=>{let m=f({abi:x,functionName:"send",args:[T.recipient,z,T.amount,T.data||"0x"]});return{target:this.contracts?.anchorPay||"",allowFailure:!1,value:T.amount,callData:m}}),a=e.reduce((T,m)=>T+m.amount,0n),y=f({abi:J,functionName:"aggregate3Value",args:[t]});if(n?.sendTransaction===!1)return{to:w,data:y,value:a};let{maxFeePerGas:r,maxPriorityFeePerGas:l}=await this.publicClient.estimateFeesPerGas(),i=await this.publicClient.estimateGas({to:w,data:y,value:a,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let p=await this.walletClient.sendTransaction({account:this.account,to:w,data:y,value:a,maxFeePerGas:n?.maxFeePerGas||r,maxPriorityFeePerGas:n?.maxPriorityFeePerGas||l,gas:n?.gas||i,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:p})}async batchSendERC20(e,n,t){if(n.length===0)throw Error("No transfers provided");if(t?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let a=n.reduce((m,d)=>m+d.amount,0n);if(t?.autoApprove!==!1&&this.walletClient&&this.account)try{console.log(`Checking ERC20 token approval status: ${e}`);let m=await this.publicClient.readContract({address:e,abi:M,functionName:"allowance",args:[this.account.address,this.contracts?.anchorPay]});if(console.log(`Current allowance: ${m}, Required amount: ${a}, AnchorPay contract address: ${this.contracts?.anchorPay}`),m<a){console.log(`Approving ${a} tokens to AnchorPay contract...`);let d=2n**256n-1n,{maxFeePerGas:o,maxPriorityFeePerGas:U}=await this.publicClient.estimateFeesPerGas(),v=f({abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d]}),j=await this.publicClient.estimateGas({to:e,data:v,value:0n,account:this.account}),s=await this.walletClient.writeContract({account:this.account,address:e,abi:M,functionName:"approve",args:[this.contracts?.anchorPay,d],chain:this.publicClient.chain,maxFeePerGas:o,maxPriorityFeePerGas:U,gas:j});console.log(`Approval transaction sent, hash: ${s}`),await this.publicClient.waitForTransactionReceipt({hash:s}),console.log("Approval transaction confirmed")}else console.log("Sufficient allowance already exists, no need for additional approval")}catch(m){throw console.error("Approval failed:",m),Error(`ERC20 approval failed: ${m instanceof Error?m.message:String(m)}`)}let y=n.map((m)=>{let d=f({abi:x,functionName:"send",args:[m.recipient,e,m.amount,m.data||"0x"]});return{target:this.contracts?.anchorPay||"",allowFailure:!1,value:0n,callData:d}}),r=f({abi:J,functionName:"aggregate3Value",args:[y]});if(t?.sendTransaction===!1)return{to:w,data:r,value:0n};let{maxFeePerGas:l,maxPriorityFeePerGas:i}=await this.publicClient.estimateFeesPerGas(),p=await this.publicClient.estimateGas({to:w,data:r,value:0n,account:this.account});if(!this.walletClient||!this.account)throw Error("Wallet client and account are required to send transactions");let u=await this.walletClient.sendTransaction({account:this.account,to:w,data:r,maxFeePerGas:t?.maxFeePerGas||l,maxPriorityFeePerGas:t?.maxPriorityFeePerGas||i,gas:t?.gas||p,chain:this.publicClient.chain});return await this.publicClient.waitForTransactionReceipt({hash:u})}}class ue{publicClient;walletClient;account;network;config;contracts;anchorPay;anchorERC1155;anchorApi;constructor(e){if(this.config=e,this.contracts={},"publicClient"in e&&e.publicClient)this.publicClient=e.publicClient,this.walletClient=e.walletClient,this.account=this.walletClient?.account,this.network=this.createChainFromNetwork(e.network);else{this.network=this.createChainFromNetwork(e.network),this.publicClient=this.initializePublicClient(e.provider);let t=e.signer||e.provider;this.walletClient=t?this.initializeWalletClient(t):void 0,this.account=this.walletClient?.account||this.getAccountFromSigner(t)}if(e.anchorPayAddress)this.contracts.anchorPay=e.anchorPayAddress;if(e.anchorERC1155Address)this.contracts.anchorERC1155=e.anchorERC1155Address;this.anchorPay=new S(this.publicClient,this.network,this.walletClient,this.account,this.contracts),this.anchorERC1155=new _(this.publicClient,this.network,this.walletClient,this.account,this.contracts);let n=e.apiBaseUrl;if(e.env&&Z[e.env]){if(!n)n=Z[e.env].apiBaseUrl;if(this.network.id&&Z[e.env].contracts[this.network.id]){let t=Z[e.env].contracts[this.network.id];if(t?.anchorPay&&!this.contracts.anchorPay)this.contracts.anchorPay=t.anchorPay;if(t?.anchorERC1155&&!this.contracts.anchorERC1155)this.contracts.anchorERC1155=t.anchorERC1155;this.anchorPay=new S(this.publicClient,this.network,this.walletClient,this.account,this.contracts),this.anchorERC1155=new _(this.publicClient,this.network,this.walletClient,this.account,this.contracts)}}if(n)this.anchorApi=new X({apiBaseUrl:n,authToken:e.authToken,projectId:e.projectId,network:this.network,onTokenExpired:e.onTokenExpired})}setTokenExpiredCallback(e){if(this.anchorApi)this.anchorApi.setTokenExpiredCallback(e)}setWalletClient(e){if(e&&"account"in e)this.walletClient=e,this.account=e.account;else{let n=e||this.config.provider;this.walletClient=this.initializeWalletClient(n),this.account=this.walletClient?.account||this.getAccountFromSigner(n)}return this.anchorPay=new S(this.publicClient,this.network,this.walletClient,this.account,this.contracts),this.anchorERC1155=new _(this.publicClient,this.network,this.walletClient,this.account,this.contracts),console.log("SDK wallet client updated:",this.account),this}initializePublicClient(e){if(typeof e==="string")return D({chain:this.network,transport:re(e)});if(e&&typeof e==="object")return D({chain:this.network,transport:V(e)});throw Error("Invalid provider. Please provide a valid RPC URL or Web3 Provider.")}initializeWalletClient(e){if(!e)return;if(e&&typeof e==="object"){if(e.selectedAddress)return k({chain:this.network,transport:V(e),account:e.selectedAddress});if(e.address)return k({chain:this.network,transport:V(e.provider||e),account:e.address})}return}getAccountFromSigner(e){if(!e)return;if(e.selectedAddress)return{address:e.selectedAddress,type:"json-rpc"};if(e.address)return{address:e.address,type:"json-rpc"};return}createChainFromNetwork(e){return{...e,nativeCurrency:e.nativeCurrency||{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:[typeof this.config.provider==="string"?this.config.provider:""]},public:{http:[typeof this.config.provider==="string"?this.config.provider:""]}}}}async buyBadgeWithETHWithSignedRequest(e,n,t){if(!e||!e.request||!e.signature)throw Error("signedRequest is required and must contain request and signature");if(!n||!b(n))throw Error("receiptAddress is required and must be a valid Ethereum address");if(t?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");if(this.validateMintRequest(e.request),e.request.currency!==z)throw Error("Currency must be ETH");let a=BigInt(e.request.price)*BigInt(e.request.quantity),y=this.anchorERC1155.encodeTokenReceivedData(e),r=await this.anchorPay.sendETH(n,a,y,t);if(t?.sendTransaction!==!1&&r&&typeof r==="object"&&"transactionHash"in r)try{await this.processTransactionHash(r.transactionHash)}catch(l){console.warn(`Failed to process transaction hash: ${l instanceof Error?l.message:String(l)}`)}return r}async buyBadgeWithERC20WithSignedRequest(e,n,t){if(!e||!e.request||!e.signature)throw Error("signedRequest is required and must contain request and signature");if(!n||!b(n))throw Error("receiptAddress is required and must be a valid Ethereum address");if(t?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");if(this.validateMintRequest(e.request),e.request.currency===z)throw Error("Currency cannot be native token");let a=BigInt(e.request.price)*BigInt(e.request.quantity),y=this.anchorERC1155.encodeTokenReceivedData(e),r=await this.anchorPay.sendERC20(n,e.request.currency,a,y,t);if(t?.sendTransaction!==!1&&r&&typeof r==="object"&&"transactionHash"in r)try{await this.processTransactionHash(r.transactionHash)}catch(l){console.warn(`Failed to process transaction hash: ${l instanceof Error?l.message:String(l)}`)}return r}async buyBadgeWithETH(e,n,t,a=1,y,r){if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!y||!b(y))throw Error("receiptAddress is required and must be a valid Ethereum address");if(t===void 0||t==="")throw Error("tokenId is required");if(BigInt(a.toString())<=0n)throw Error("quantity must be greater than 0");if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(r?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let i=[`${t.toString()}`],p=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:i});if(p.code!=="0000"||!p.obj||!p.obj.signatures||p.obj.signatures.length===0)throw Error(p.code||"Failed to get mint request from backend");let u=p.obj.signatures[0];if(!u)throw Error("Mint request not found");if(!u.badgeId||!u.signature||!u.validityStartTimestamp||!u.validityEndTimestamp)throw Error("Mint request missing required fields");let T={request:{to:e,tokenId:BigInt(u.badgeId||t),quantity:BigInt(u.quantity||a),price:BigInt(u.price||0),currency:u.currency,validityStartTimestamp:BigInt(u.validityStartTimestamp||Math.floor(Date.now()/1000)),validityEndTimestamp:BigInt(u.validityEndTimestamp||Math.floor(Date.now()/1000)+3600),uid:u.uid,chainId:BigInt(u.chainId||this.network.id),projectHandle:u.projectHandle},signature:u.signature};return await this.buyBadgeWithETHWithSignedRequest(T,y,r)}async buyBadgeWithETHWithCustomSignature(e,n,t){if(!e)throw Error("signedRequest is required");if(!e.to||!b(e.to))throw Error("signedRequest.to is required and must be a valid Ethereum address");if(e.tokenId===void 0||e.tokenId==="")throw Error("signedRequest.tokenId is required");if(e.quantity===void 0||BigInt(e.quantity.toString())<=0n)throw Error("signedRequest.quantity is required and must be greater than 0");if(e.price===void 0)throw Error("signedRequest.price is required");if(!e.uid)throw Error("signedRequest.uid is required");if(!e.signature)throw Error("signedRequest.signature is required");if(!e.chainId)throw Error("signedRequest.chainId is required");if(!n||!b(n))throw Error("receiptAddress is required and must be a valid Ethereum address");let a={request:{to:e.to,tokenId:BigInt(e.tokenId),quantity:BigInt(e.quantity),price:BigInt(e.price),currency:e.currency,validityStartTimestamp:BigInt(e.validityStartTimestamp||Math.floor(Date.now()/1000)+3600),validityEndTimestamp:BigInt(e.validityEndTimestamp||Math.floor(Date.now()/1000)+3600),uid:e.uid,chainId:BigInt(e.chainId||this.network.id),projectHandle:e.projectHandle},signature:e.signature.startsWith("0x")?e.signature:`0x${e.signature}`};return await this.buyBadgeWithETHWithSignedRequest(a,n,t)}async buyBadgeWithERC20(e,n,t,a=1,y,r,l){if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(l?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!r||!b(r))throw Error("receiptAddress is required and must be a valid Ethereum address");if(!y||!b(y))throw Error("currency is required and must be a valid ERC20 token address");if(t===void 0||t==="")throw Error("tokenId is required");if(BigInt(a.toString())<=0n)throw Error("quantity must be greater than 0");let p=[`${t.toString()}`],u=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:p});if(u.code!=="0000"||!u.obj||!u.obj.signatures||u.obj.signatures.length===0)throw Error(u.code||"Failed to get mint request from backend");let T=u.obj.signatures[0];if(!T)throw Error("Mint request not found");if(T.badgeId||T.signature||T.validityStartTimestamp||T.validityEndTimestamp)throw Error("Mint request missing required fields");let m={request:{to:e,tokenId:BigInt(T.badgeId||t),quantity:BigInt(T.quantity||a),price:BigInt(T.price||0),currency:T.currency,validityStartTimestamp:BigInt(T.validityStartTimestamp||Math.floor(Date.now()/1000)),validityEndTimestamp:BigInt(T.validityEndTimestamp||Math.floor(Date.now()/1000)+3600),uid:T.uid,chainId:BigInt(T.chainId||this.network.id),projectHandle:T.projectHandle},signature:T.signature};return await this.buyBadgeWithERC20WithSignedRequest(m,r,l)}async buyBadgeWithERC20WithCustomSignature(e,n,t){if(!e)throw Error("signedRequest is required");if(!e.to||!b(e.to))throw Error("signedRequest.to is required and must be a valid Ethereum address");if(e.tokenId===void 0||e.tokenId==="")throw Error("signedRequest.tokenId is required");if(e.quantity===void 0||BigInt(e.quantity.toString())<=0n)throw Error("signedRequest.quantity is required and must be greater than 0");if(e.price===void 0)throw Error("signedRequest.price is required");if(!e.uid)throw Error("signedRequest.uid is required");if(!e.signature)throw Error("signedRequest.signature is required");if(!e.chainId)throw Error("signedRequest.chainId is required");if(!n||!b(n))throw Error("receiptAddress is required and must be a valid Ethereum address");let a={request:{to:e.to,tokenId:BigInt(e.tokenId),quantity:BigInt(e.quantity),price:BigInt(e.price),currency:e.currency,validityStartTimestamp:BigInt(e.validityStartTimestamp||Math.floor(Date.now()/1000)+3600),validityEndTimestamp:BigInt(e.validityEndTimestamp||Math.floor(Date.now()/1000)+3600),uid:e.uid,chainId:BigInt(e.chainId||this.network.id),projectHandle:e.projectHandle},signature:e.signature.startsWith("0x")?e.signature:`0x${e.signature}`};return await this.buyBadgeWithERC20WithSignedRequest(a,n,t)}async pay(e,n,t,a){if(!e||e.trim()==="")throw Error("orderId is required and cannot be empty");if(!t||!b(t))throw Error("receiptAddress is required and must be a valid Ethereum address");if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=typeof n==="string"||typeof n==="number"?g(n.toString()):n,r=this.encodeUserData(e),l=$({abi:x,functionName:"send",args:[t,z,y,r]});if(a?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:l,value:y};let i=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:l,value:y}),p=await this.publicClient.waitForTransactionReceipt({hash:i});if(p&&typeof p==="object"&&"transactionHash"in p)try{await this.processTransactionHash(p.transactionHash)}catch(u){console.warn(`Failed to process transaction hash: ${u instanceof Error?u.message:String(u)}`)}return p}async sendPaymentWithNativeToken(e){let{callData:n,amount:t,receiptAddress:a,contractName:y,options:r}=e;if(!n||n.trim()==="")throw Error("callData is required and cannot be empty");if(!a||!b(a))throw Error("receiptAddress is required and must be a valid Ethereum address");if(r?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let l=typeof t==="string"||typeof t==="number"?g(t.toString()):t,i=C(Q(y||"")),p=Y([i,n]),u=$({abi:x,functionName:"send",args:[a,z,l,p]});if(r?.sendTransaction===!1)return{to:this.contracts?.anchorPay||"",data:u,value:l};let T=await this.walletClient.sendTransaction({account:this.account,to:this.contracts?.anchorPay||"",data:u,value:l}),m=await this.publicClient.waitForTransactionReceipt({hash:T});if(m&&typeof m==="object"&&"transactionHash"in m)try{await this.processTransactionHash(m.transactionHash)}catch(d){console.warn(`Failed to process transaction hash: ${d instanceof Error?d.message:String(d)}`)}return m}async sendPaymentWithERC20(e){let{callData:n,amount:t,receiptAddress:a,tokenAddress:y,contractName:r,options:l}=e;if(!n||n.trim()==="")throw Error("callData is required and cannot be empty");if(!a||!b(a))throw Error("receiptAddress is required and must be a valid Ethereum address");if(!y||!b(y))throw Error("tokenAddress is required and must be a valid Ethereum address");let i=await this.publicClient.readContract({address:y,abi:M,functionName:"decimals"}),p=typeof t==="bigint"?t:BigInt(Math.floor(Number(t)*10**i)),u=C(Q(r||""));console.log(`Interface hash: ${u}`);let T=Y([u,n]);console.log(`callData: ${n}`),console.log(`Data: ${T}`);let m=await this.anchorPay.sendERC20(a,y,p,T,l);if(m&&typeof m==="object"&&"transactionHash"in m)try{await this.processTransactionHash(m.transactionHash)}catch(d){console.warn(`Failed to process transaction hash ${m.transactionHash} with Anchor API: ${d}`)}return m}encodeUserData(e){let n=C(Q(""));console.log(n,"interfaceHash");let t=Q(e);return console.log(Y([n,t]),"concat"),Y([n,t])}async mintFreeBadge(e,n,t,a){if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!t||!Array.isArray(t)||t.length===0)throw Error("tokenIds is required and must be a non-empty array");for(let l of t)if(!l||typeof l!=="string")throw Error("Each tokenId must be a non-empty string");if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:t});if(console.log(JSON.stringify(y)),y.code!=="0000"||!y.obj||!y.obj.signatures||y.obj.signatures.length===0)throw Error(y.code||"Failed to get mint request from backend");if(a?.sendTransaction===!1){let l=y.obj.signatures;return await Promise.all(l.map(async(p)=>{if(!p.badgeId||!p.signature||!p.validityStartTimestamp||!p.validityEndTimestamp)throw Error("Mint request missing required fields");let u={request:{to:e,tokenId:BigInt(p.badgeId),quantity:BigInt(p.quantity||1),price:BigInt(p.price||0),currency:p.currency,validityStartTimestamp:BigInt(p.validityStartTimestamp),validityEndTimestamp:BigInt(p.validityEndTimestamp),uid:p.uid,chainId:BigInt(p.chainId||this.network.id),projectHandle:p.projectHandle},signature:p.signature};if(this.validateMintRequest(u.request),BigInt(u.request.price)!==0n)throw Error("Free Badge price must be 0");return await this.anchorERC1155.mintWithSignature(u,n,{sendTransaction:!1})}))}let r=null;for(let l of y.obj.signatures){if(!l.badgeId||!l.signature||!l.validityStartTimestamp||!l.validityEndTimestamp){console.warn("铸造请求缺失必要字段",l);continue}let i={request:{to:e,tokenId:BigInt(l.badgeId),quantity:BigInt(l.quantity||1),price:BigInt(l.price||0),currency:l.currency,validityStartTimestamp:BigInt(l.validityStartTimestamp),validityEndTimestamp:BigInt(l.validityEndTimestamp),uid:l.uid,chainId:BigInt(l.chainId||this.network.id),projectHandle:l.projectHandle},signature:l.signature};if(this.validateMintRequest(i.request),BigInt(i.request.price)!==0n)throw Error("Free Badge price must be 0");console.log(i,"signedRequest");let p=await this.anchorERC1155.mintWithSignature(i,n,{sendTransaction:!0});if("transactionHash"in p){r=p;try{await this.processTransactionHash(p.transactionHash)}catch(u){console.warn(`Failed to process transaction hash: ${u instanceof Error?u.message:String(u)}`)}}else throw Error("Expected transaction receipt, but received transaction data")}if(!r)throw Error("No successful mint transaction");return r}async mintFreeBadgeWithSignedRequest(e,n){if(this.validateMintRequest(e.request),BigInt(e.request.price)!==0n)throw Error("Free Badge price must be 0");let t=await this.anchorERC1155.mintWithSignature(e,e?.request?.contractAddress,n);if(n?.sendTransaction!==!1&&t&&typeof t==="object"&&"transactionHash"in t)try{await this.processTransactionHash(t.transactionHash)}catch(a){console.warn(`Failed to process transaction hash: ${a instanceof Error?a.message:String(a)}`)}return t}getERC20ApprovalData(e,n,t){return this.anchorPay.getERC20ApprovalData(e,n,t)}validateMintRequest(e){if(!b(e.to))throw Error("Invalid recipient address");let n=Math.floor(Date.now()/1000),t=e.validityEndTimestamp;if(t&&BigInt(t)<BigInt(n))throw Error("Mint request expired");if(BigInt(e.quantity)<=0n)throw Error("Quantity must be greater than 0")}async processTransactionHash(e){try{if(this.anchorApi){let n=await this.anchorApi.transactionHashProcess(e);return console.log(`Transaction processing accelerated: ${e}`),n}}catch(n){console.warn(`Failed to accelerate transaction processing: ${n instanceof Error?n.message:String(n)}`)}return}async batchMintBadge(e,n,t,a){if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!Array.isArray(t)||t.length===0)throw Error("tokenIds is required and must be a non-empty array");for(let i of t)if(!i||typeof i!=="string")throw Error("Each tokenId must be a non-empty string");if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:t});if(y.code!=="0000"||!y.obj||!y.obj.signatures||y.obj.signatures.length===0)throw Error(y.code||"Failed to get batch mint request from backend");let r=y.obj.signatures;if(a?.sendTransaction===!1)return await Promise.all(r.map(async(p)=>{if(!p.badgeId||!p.signature||!p.validityStartTimestamp||!p.validityEndTimestamp)throw Error("Mint request missing required fields");let u={request:{to:e,tokenId:BigInt(p.badgeId),quantity:BigInt(p.quantity||1),price:BigInt(p.price||0),currency:p.currency,validityStartTimestamp:BigInt(p.validityStartTimestamp),validityEndTimestamp:BigInt(p.validityEndTimestamp),uid:p.uid,chainId:BigInt(p.chainId||this.network.id),projectHandle:p.projectHandle},signature:p.signature};return this.validateMintRequest(u.request),await this.anchorERC1155.mintWithSignature(u,n,{sendTransaction:!1})}));let l=null;for(let i of r){if(!i.badgeId||!i.signature||!i.validityStartTimestamp||!i.validityEndTimestamp){console.warn("铸造请求缺失必要字段",i);continue}let p={request:{to:e,tokenId:BigInt(i.badgeId),quantity:BigInt(i.quantity||1),price:BigInt(i.price||0),currency:i.currency,validityStartTimestamp:BigInt(i.validityStartTimestamp),validityEndTimestamp:BigInt(i.validityEndTimestamp),uid:i.uid,chainId:BigInt(i.chainId||this.network.id),projectHandle:i.projectHandle},signature:i.signature};this.validateMintRequest(p.request);let u=await this.anchorERC1155.mintWithSignature(p,n,{sendTransaction:!0});if("transactionHash"in u){l=u;try{await this.processTransactionHash(u.transactionHash)}catch(T){console.warn(`Failed to process transaction hash: ${T instanceof Error?T.message:String(T)}`)}}else throw Error("Expected transaction receipt, but received transaction data")}if(!l)throw Error("No successful mint transaction");return l}async batchMintBadgeWithMulticall(e,n,t,a){if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!Array.isArray(t)||t.length===0)throw Error("tokenIds is required and must be a non-empty array");if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:t});if(y.code!=="0000"||!y.obj||!y.obj.signatures||y.obj.signatures.length===0)throw Error(y.code||"Failed to get batch mint request from backend");let l=y.obj.signatures.map((p)=>{if(!p.badgeId||!p.signature||!p.validityStartTimestamp||!p.validityEndTimestamp)throw Error("Mint request missing required fields");let u={request:{to:e,tokenId:BigInt(p.badgeId),quantity:BigInt(p.quantity||1),price:BigInt(p.price||0),currency:p.currency,validityStartTimestamp:BigInt(p.validityStartTimestamp),validityEndTimestamp:BigInt(p.validityEndTimestamp),uid:p.uid,chainId:BigInt(p.chainId||this.network.id),projectHandle:p.projectHandle},signature:p.signature};return this.validateMintRequest(u.request),$({abi:O,functionName:"mintWithSignature",args:[this.anchorERC1155.formatMintRequest(u.request),u.signature]})}),i=await this.anchorERC1155.multicall(l,a);if(a?.sendTransaction!==!1&&i&&typeof i==="object"&&"transactionHash"in i)try{await this.processTransactionHash(i.transactionHash)}catch(p){console.warn(`Failed to process transaction hash: ${p instanceof Error?p.message:String(p)}`)}return i}async mintFreeBadgeWithMulticall(e,n,t,a){if(!this.anchorApi)throw Error("Anchor API client not initialized, please check apiBaseUrl configuration");if(!e||!b(e))throw Error("customerAddress is required and must be a valid Ethereum address");if(!n||!b(n))throw Error("contractAddress is required and must be a valid Ethereum address");if(!Array.isArray(t)||t.length===0)throw Error("tokenIds is required and must be a non-empty array");for(let i of t)if(!i||typeof i!=="string")throw Error("Each tokenId must be a non-empty string");if(a?.sendTransaction!==!1&&(!this.walletClient||!this.account))throw Error("Wallet client and account are required to send transactions");let y=await this.anchorApi.getBadgeClaimSignatures({customerAddress:e,badgeIds:t});if(y.code!=="0000"||!y.obj||!y.obj.signatures||y.obj.signatures.length===0)throw Error(y.code||"Failed to get mint request from backend");let r=y.obj.signatures.map((i)=>{if(!i.badgeId||!i.signature||!i.validityStartTimestamp||!i.validityEndTimestamp)throw Error("Mint request missing required fields");let p={request:{to:e,tokenId:BigInt(i.badgeId),quantity:BigInt(i.quantity||1),price:BigInt(i.price||0),currency:i.currency,validityStartTimestamp:BigInt(i.validityStartTimestamp),validityEndTimestamp:BigInt(i.validityEndTimestamp),uid:i.uid,chainId:BigInt(i.chainId||this.network.id),projectHandle:i.projectHandle},signature:i.signature};if(this.validateMintRequest(p.request),BigInt(p.request.price)!==0n)throw Error("Free Badge price must be 0");return $({abi:O,functionName:"mintWithSignature",args:[this.anchorERC1155.formatMintRequest(p.request),p.signature]})}),l=await this.anchorERC1155.multicall(r,a);if(a?.sendTransaction!==!1&&l&&typeof l==="object"&&"transactionHash"in l)try{await this.processTransactionHash(l.transactionHash)}catch(i){console.warn(`Failed to process transaction hash: ${i instanceof Error?i.message:String(i)}`)}return l}}export{z as NATIVE_TOKEN_ADDRESS,w as MULTICALL3_ADDRESS,J as MULTICALL3_ABI,nn as INTERFACE_HASHES,B as HttpClient,le as Environment,M as ERC20_ABI,Z as ENVIRONMENTS,c as ContentType,N as Api,ue as AnchorSDK,S as AnchorPayClient,_ as AnchorERC1155Client,X as AnchorApiClientV2};
|
|
2
|
+
|
|
3
|
+
//# debugId=33F7A538F772C39F64756E2164756E21
|