@mysten/zksend 0.3.1 → 0.4.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cjs/channel/events.d.ts +27 -27
  3. package/dist/cjs/channel/index.d.ts +1 -1
  4. package/dist/cjs/index.d.ts +4 -2
  5. package/dist/cjs/index.js +5 -1
  6. package/dist/cjs/index.js.map +3 -3
  7. package/dist/cjs/links/builder.d.ts +13 -2
  8. package/dist/cjs/links/builder.js +130 -42
  9. package/dist/cjs/links/builder.js.map +2 -2
  10. package/dist/cjs/links/claim.d.ts +10 -47
  11. package/dist/cjs/links/claim.js +157 -126
  12. package/dist/cjs/links/claim.js.map +3 -3
  13. package/dist/cjs/links/list-created-links.d.ts +22 -0
  14. package/dist/cjs/links/list-created-links.js +145 -0
  15. package/dist/cjs/links/list-created-links.js.map +7 -0
  16. package/dist/cjs/links/utils.d.ts +30 -17
  17. package/dist/cjs/links/utils.js +66 -109
  18. package/dist/cjs/links/utils.js.map +3 -3
  19. package/dist/cjs/links/zk-bag.d.ts +1 -0
  20. package/dist/cjs/links/zk-bag.js +6 -0
  21. package/dist/cjs/links/zk-bag.js.map +2 -2
  22. package/dist/esm/channel/events.d.ts +27 -27
  23. package/dist/esm/channel/index.d.ts +1 -1
  24. package/dist/esm/index.d.ts +4 -2
  25. package/dist/esm/index.js +6 -2
  26. package/dist/esm/index.js.map +2 -2
  27. package/dist/esm/links/builder.d.ts +13 -2
  28. package/dist/esm/links/builder.js +131 -43
  29. package/dist/esm/links/builder.js.map +2 -2
  30. package/dist/esm/links/claim.d.ts +10 -47
  31. package/dist/esm/links/claim.js +155 -124
  32. package/dist/esm/links/claim.js.map +2 -2
  33. package/dist/esm/links/list-created-links.d.ts +22 -0
  34. package/dist/esm/links/list-created-links.js +125 -0
  35. package/dist/esm/links/list-created-links.js.map +7 -0
  36. package/dist/esm/links/utils.d.ts +30 -17
  37. package/dist/esm/links/utils.js +67 -110
  38. package/dist/esm/links/utils.js.map +3 -3
  39. package/dist/esm/links/zk-bag.d.ts +1 -0
  40. package/dist/esm/links/zk-bag.js +6 -0
  41. package/dist/esm/links/zk-bag.js.map +2 -2
  42. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  43. package/dist/tsconfig.tsbuildinfo +1 -1
  44. package/package.json +3 -3
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/links/builder.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { getFullnodeUrl, SuiClient } from '@mysten/sui.js/client';\nimport type { CoinStruct } from '@mysten/sui.js/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui.js/cryptography';\nimport type { Keypair, Signer } from '@mysten/sui.js/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';\nimport type {\n\tTransactionObjectArgument,\n\tTransactionObjectInput,\n} from '@mysten/sui.js/transactions';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress, SUI_TYPE_ARG, toB64 } from '@mysten/sui.js/utils';\n\nimport type { ZkBagContractOptions } from './zk-bag.js';\nimport { ZkBag } from './zk-bag.js';\n\ninterface ZkSendLinkRedirect {\n\turl: string;\n\tname?: string;\n}\n\nexport interface ZkSendLinkBuilderOptions {\n\thost?: string;\n\tpath?: string;\n\tkeypair?: Keypair;\n\tnetwork?: 'mainnet' | 'testnet';\n\tclient?: SuiClient;\n\tsender: string;\n\tredirect?: ZkSendLinkRedirect;\n\tcontract?: ZkBagContractOptions;\n}\n\nconst DEFAULT_ZK_SEND_LINK_OPTIONS = {\n\thost: 'https://zksend.com',\n\tpath: '/claim',\n\tnetwork: 'mainnet' as const,\n};\n\nconst SUI_COIN_TYPE = normalizeStructTag(SUI_TYPE_ARG);\n\nexport interface CreateZkSendLinkOptions {\n\ttransactionBlock?: TransactionBlock;\n\tcalculateGas?: (options: {\n\t\tbalances: Map<string, bigint>;\n\t\tobjects: TransactionObjectInput[];\n\t\tgasEstimateFromDryRun: bigint;\n\t}) => Promise<bigint> | bigint;\n}\n\nexport class ZkSendLinkBuilder {\n\t#host: string;\n\t#path: string;\n\t#keypair: Keypair;\n\t#client: SuiClient;\n\t#redirect?: ZkSendLinkRedirect;\n\t#objects = new Set<string>();\n\t#balances = new Map<string, bigint>();\n\t#sender: string;\n\n\t#coinsByType = new Map<string, CoinStruct[]>();\n\t#contract?: ZkBag<ZkBagContractOptions>;\n\n\tconstructor({\n\t\thost = DEFAULT_ZK_SEND_LINK_OPTIONS.host,\n\t\tpath = DEFAULT_ZK_SEND_LINK_OPTIONS.path,\n\t\tkeypair = new Ed25519Keypair(),\n\t\tnetwork = DEFAULT_ZK_SEND_LINK_OPTIONS.network,\n\t\tclient = new SuiClient({ url: getFullnodeUrl(network) }),\n\t\tsender,\n\t\tredirect,\n\t\tcontract,\n\t}: ZkSendLinkBuilderOptions) {\n\t\tthis.#host = host;\n\t\tthis.#path = path;\n\t\tthis.#redirect = redirect;\n\t\tthis.#keypair = keypair;\n\t\tthis.#client = client;\n\t\tthis.#sender = normalizeSuiAddress(sender);\n\n\t\tif (contract) {\n\t\t\tthis.#contract = new ZkBag(contract.packageId, contract);\n\t\t}\n\t}\n\n\taddClaimableMist(amount: bigint) {\n\t\tthis.addClaimableBalance(SUI_COIN_TYPE, amount);\n\t}\n\n\taddClaimableBalance(coinType: string, amount: bigint) {\n\t\tconst normalizedType = normalizeStructTag(coinType);\n\t\tthis.#balances.set(normalizedType, (this.#balances.get(normalizedType) ?? 0n) + amount);\n\t}\n\n\taddClaimableObject(id: string) {\n\t\tthis.#objects.add(id);\n\t}\n\n\tgetLink(): string {\n\t\tconst link = new URL(this.#host);\n\t\tlink.pathname = this.#path;\n\t\tlink.hash = `${this.#contract ? '$' : ''}${toB64(\n\t\t\tdecodeSuiPrivateKey(this.#keypair.getSecretKey()).secretKey,\n\t\t)}`;\n\n\t\tif (this.#redirect) {\n\t\t\tlink.searchParams.set('redirect_url', this.#redirect.url);\n\t\t\tif (this.#redirect.name) {\n\t\t\t\tlink.searchParams.set('name', this.#redirect.name);\n\t\t\t}\n\t\t}\n\n\t\treturn link.toString();\n\t}\n\n\tasync create({\n\t\tsigner,\n\t\t...options\n\t}: CreateZkSendLinkOptions & {\n\t\tsigner: Signer;\n\t\twaitForTransactionBlock?: boolean;\n\t}) {\n\t\tconst txb = await this.createSendTransaction(options);\n\n\t\tconst result = await this.#client.signAndExecuteTransactionBlock({\n\t\t\ttransactionBlock: await txb.build({ client: this.#client }),\n\t\t\tsigner,\n\t\t});\n\n\t\tif (options.waitForTransactionBlock) {\n\t\t\tawait this.#client.waitForTransactionBlock({ digest: result.digest });\n\t\t}\n\n\t\treturn result;\n\t}\n\tasync createSendTransaction({\n\t\ttransactionBlock: txb = new TransactionBlock(),\n\t\tcalculateGas,\n\t}: CreateZkSendLinkOptions = {}) {\n\t\tif (!this.#contract) {\n\t\t\treturn this.#createSendTransactionWithoutContract({ transactionBlock: txb, calculateGas });\n\t\t}\n\t\tconst receiver = txb.pure.address(this.#keypair.toSuiAddress());\n\t\tconst store = txb.object(this.#contract.ids.bagStoreId);\n\n\t\tthis.#contract.new(txb, { arguments: [store, receiver] });\n\t\ttxb.setSenderIfNotSet(this.#sender);\n\n\t\tconst objectsToTransfer = await this.#objectsToTransfer(txb);\n\n\t\tfor (const object of objectsToTransfer) {\n\t\t\tthis.#contract.add(txb, {\n\t\t\t\targuments: [store, receiver, object.ref],\n\t\t\t\ttypeArguments: [object.type],\n\t\t\t});\n\t\t}\n\n\t\treturn txb;\n\t}\n\n\tasync #objectsToTransfer(txb: TransactionBlock) {\n\t\tconst objectIDs = [...this.#objects];\n\t\tconst refsWithType: {\n\t\t\tref: TransactionObjectArgument;\n\t\t\ttype: string;\n\t\t}[] = (\n\t\t\tawait this.#client.multiGetObjects({\n\t\t\t\tids: objectIDs,\n\t\t\t\toptions: {\n\t\t\t\t\tshowType: true,\n\t\t\t\t},\n\t\t\t})\n\t\t).map((res, i) => {\n\t\t\tif (!res.data || res.error) {\n\t\t\t\tthrow new Error(`Failed to load object ${objectIDs[i]} (${res.error?.code})`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tref: txb.objectRef({\n\t\t\t\t\tversion: res.data.version,\n\t\t\t\t\tdigest: res.data.digest,\n\t\t\t\t\tobjectId: res.data.objectId,\n\t\t\t\t}),\n\t\t\t\ttype: res.data.type!,\n\t\t\t};\n\t\t});\n\n\t\ttxb.setSenderIfNotSet(this.#sender);\n\n\t\tfor (const [coinType, amount] of this.#balances) {\n\t\t\tif (coinType === SUI_COIN_TYPE) {\n\t\t\t\tconst [sui] = txb.splitCoins(txb.gas, [amount]);\n\t\t\t\trefsWithType.push({\n\t\t\t\t\tref: sui,\n\t\t\t\t\ttype: `0x2::coin::Coin<${coinType}>`,\n\t\t\t\t} as never);\n\t\t\t} else {\n\t\t\t\tconst coins = (await this.#getCoinsByType(coinType)).map((coin) => coin.coinObjectId);\n\n\t\t\t\tif (coins.length > 1) {\n\t\t\t\t\ttxb.mergeCoins(coins[0], coins.slice(1));\n\t\t\t\t}\n\t\t\t\tconst [split] = txb.splitCoins(coins[0], [amount]);\n\t\t\t\trefsWithType.push({\n\t\t\t\t\tref: split,\n\t\t\t\t\ttype: `0x2::coin:Coin<${coinType}>`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn refsWithType;\n\t}\n\n\tasync #createSendTransactionWithoutContract({\n\t\ttransactionBlock: txb = new TransactionBlock(),\n\t\tcalculateGas,\n\t}: CreateZkSendLinkOptions = {}) {\n\t\tconst gasEstimateFromDryRun = await this.#estimateClaimGasFee();\n\t\tconst baseGasAmount = calculateGas\n\t\t\t? await calculateGas({\n\t\t\t\t\tbalances: this.#balances,\n\t\t\t\t\tobjects: [...this.#objects],\n\t\t\t\t\tgasEstimateFromDryRun,\n\t\t\t })\n\t\t\t: gasEstimateFromDryRun * 2n;\n\n\t\t// Ensure that rounded gas is not less than the calculated gas\n\t\tconst gasWithBuffer = baseGasAmount + 1013n;\n\t\t// Ensure that gas amount ends in 987\n\t\tconst roundedGasAmount = gasWithBuffer - (gasWithBuffer % 1000n) - 13n;\n\n\t\tconst address = this.#keypair.toSuiAddress();\n\t\tconst objectsToTransfer = (await this.#objectsToTransfer(txb)).map((obj) => obj.ref);\n\t\tconst [gas] = txb.splitCoins(txb.gas, [roundedGasAmount]);\n\t\tobjectsToTransfer.push(gas);\n\n\t\ttxb.setSenderIfNotSet(this.#sender);\n\t\ttxb.transferObjects(objectsToTransfer, address);\n\n\t\treturn txb;\n\t}\n\n\tasync #estimateClaimGasFee(): Promise<bigint> {\n\t\tconst txb = new TransactionBlock();\n\t\ttxb.setSender(this.#sender);\n\t\ttxb.setGasPayment([]);\n\t\ttxb.transferObjects([txb.gas], this.#keypair.toSuiAddress());\n\n\t\tconst idsToTransfer = [...this.#objects];\n\n\t\tfor (const [coinType] of this.#balances) {\n\t\t\tconst coins = await this.#getCoinsByType(coinType);\n\n\t\t\tif (!coins.length) {\n\t\t\t\tthrow new Error(`Sending account does not contain any coins of type ${coinType}`);\n\t\t\t}\n\n\t\t\tidsToTransfer.push(coins[0].coinObjectId);\n\t\t}\n\n\t\tif (idsToTransfer.length > 0) {\n\t\t\ttxb.transferObjects(\n\t\t\t\tidsToTransfer.map((id) => txb.object(id)),\n\t\t\t\tthis.#keypair.toSuiAddress(),\n\t\t\t);\n\t\t}\n\n\t\tconst result = await this.#client.dryRunTransactionBlock({\n\t\t\ttransactionBlock: await txb.build({ client: this.#client }),\n\t\t});\n\n\t\treturn (\n\t\t\tBigInt(result.effects.gasUsed.computationCost) +\n\t\t\tBigInt(result.effects.gasUsed.storageCost) -\n\t\t\tBigInt(result.effects.gasUsed.storageRebate)\n\t\t);\n\t}\n\n\tasync #getCoinsByType(coinType: string) {\n\t\tif (this.#coinsByType.has(coinType)) {\n\t\t\treturn this.#coinsByType.get(coinType)!;\n\t\t}\n\n\t\tconst coins = await this.#client.getCoins({\n\t\t\tcoinType,\n\t\t\towner: this.#sender,\n\t\t});\n\n\t\tthis.#coinsByType.set(coinType, coins.data);\n\n\t\treturn coins.data;\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAGA,SAAS,gBAAgB,iBAAiB;AAE1C,SAAS,2BAA2B;AAEpC,SAAS,sBAAsB;AAK/B,SAAS,wBAAwB;AACjC,SAAS,oBAAoB,qBAAqB,cAAc,aAAa;AAG7E,SAAS,aAAa;AAkBtB,MAAM,+BAA+B;AAAA,EACpC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AACV;AAEA,MAAM,gBAAgB,mBAAmB,YAAY;AAW9C,MAAM,kBAAkB;AAAA,EAa9B,YAAY;AAAA,IACX,OAAO,6BAA6B;AAAA,IACpC,OAAO,6BAA6B;AAAA,IACpC,UAAU,IAAI,eAAe;AAAA,IAC7B,UAAU,6BAA6B;AAAA,IACvC,SAAS,IAAI,UAAU,EAAE,KAAK,eAAe,OAAO,EAAE,CAAC;AAAA,IACvD;AAAA,IACA;AAAA,IACA;AAAA,EACD,GAA6B;AAwF7B,uBAAM;AAqDN,uBAAM;AA6BN,uBAAM;AAoCN,uBAAM;AAnON;AACA;AACA;AACA;AACA;AACA,iCAAW,oBAAI,IAAY;AAC3B,kCAAY,oBAAI,IAAoB;AACpC;AAEA,qCAAe,oBAAI,IAA0B;AAC7C;AAYC,uBAAK,OAAQ;AACb,uBAAK,OAAQ;AACb,uBAAK,WAAY;AACjB,uBAAK,UAAW;AAChB,uBAAK,SAAU;AACf,uBAAK,SAAU,oBAAoB,MAAM;AAEzC,QAAI,UAAU;AACb,yBAAK,WAAY,IAAI,MAAM,SAAS,WAAW,QAAQ;AAAA,IACxD;AAAA,EACD;AAAA,EAEA,iBAAiB,QAAgB;AAChC,SAAK,oBAAoB,eAAe,MAAM;AAAA,EAC/C;AAAA,EAEA,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// SPDX-License-Identifier: Apache-2.0\n\nimport { getFullnodeUrl, SuiClient } from '@mysten/sui.js/client';\nimport type { CoinStruct } from '@mysten/sui.js/client';\nimport { decodeSuiPrivateKey } from '@mysten/sui.js/cryptography';\nimport type { Keypair, Signer } from '@mysten/sui.js/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';\nimport type {\n\tTransactionObjectArgument,\n\tTransactionObjectInput,\n} from '@mysten/sui.js/transactions';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress, SUI_TYPE_ARG, toB64 } from '@mysten/sui.js/utils';\n\nimport type { ZkBagContractOptions } from './zk-bag.js';\nimport { MAINNET_CONTRACT_IDS, ZkBag } from './zk-bag.js';\n\ninterface ZkSendLinkRedirect {\n\turl: string;\n\tname?: string;\n}\n\nexport interface ZkSendLinkBuilderOptions {\n\thost?: string;\n\tpath?: string;\n\tkeypair?: Keypair;\n\tnetwork?: 'mainnet' | 'testnet';\n\tclient?: SuiClient;\n\tsender: string;\n\tredirect?: ZkSendLinkRedirect;\n\tcontract?: ZkBagContractOptions | null;\n}\n\nconst DEFAULT_ZK_SEND_LINK_OPTIONS = {\n\thost: 'https://zksend.com',\n\tpath: '/claim',\n\tnetwork: 'mainnet' as const,\n};\n\nconst SUI_COIN_TYPE = normalizeStructTag(SUI_TYPE_ARG);\n\nexport interface CreateZkSendLinkOptions {\n\ttransactionBlock?: TransactionBlock;\n\tcalculateGas?: (options: {\n\t\tbalances: Map<string, bigint>;\n\t\tobjects: TransactionObjectInput[];\n\t\tgasEstimateFromDryRun: bigint;\n\t}) => Promise<bigint> | bigint;\n}\n\nexport class ZkSendLinkBuilder {\n\tobjectIds = new Set<string>();\n\tbalances = new Map<string, bigint>();\n\tsender: string;\n\t#host: string;\n\t#path: string;\n\tkeypair: Keypair;\n\t#client: SuiClient;\n\t#redirect?: ZkSendLinkRedirect;\n\t#coinsByType = new Map<string, CoinStruct[]>();\n\t#contract?: ZkBag<ZkBagContractOptions>;\n\n\tconstructor({\n\t\thost = DEFAULT_ZK_SEND_LINK_OPTIONS.host,\n\t\tpath = DEFAULT_ZK_SEND_LINK_OPTIONS.path,\n\t\tkeypair = new Ed25519Keypair(),\n\t\tnetwork = DEFAULT_ZK_SEND_LINK_OPTIONS.network,\n\t\tclient = new SuiClient({ url: getFullnodeUrl(network) }),\n\t\tsender,\n\t\tredirect,\n\t\tcontract = network === 'mainnet' ? MAINNET_CONTRACT_IDS : undefined,\n\t}: ZkSendLinkBuilderOptions) {\n\t\tthis.#host = host;\n\t\tthis.#path = path;\n\t\tthis.#redirect = redirect;\n\t\tthis.keypair = keypair;\n\t\tthis.#client = client;\n\t\tthis.sender = normalizeSuiAddress(sender);\n\n\t\tif (contract) {\n\t\t\tthis.#contract = new ZkBag(contract.packageId, contract);\n\t\t}\n\t}\n\n\taddClaimableMist(amount: bigint) {\n\t\tthis.addClaimableBalance(SUI_COIN_TYPE, amount);\n\t}\n\n\taddClaimableBalance(coinType: string, amount: bigint) {\n\t\tconst normalizedType = normalizeStructTag(coinType);\n\t\tthis.balances.set(normalizedType, (this.balances.get(normalizedType) ?? 0n) + amount);\n\t}\n\n\taddClaimableObject(id: string) {\n\t\tthis.objectIds.add(id);\n\t}\n\n\tgetLink(): string {\n\t\tconst link = new URL(this.#host);\n\t\tlink.pathname = this.#path;\n\t\tlink.hash = `${this.#contract ? '$' : ''}${toB64(\n\t\t\tdecodeSuiPrivateKey(this.keypair.getSecretKey()).secretKey,\n\t\t)}`;\n\n\t\tif (this.#redirect) {\n\t\t\tlink.searchParams.set('redirect_url', this.#redirect.url);\n\t\t\tif (this.#redirect.name) {\n\t\t\t\tlink.searchParams.set('name', this.#redirect.name);\n\t\t\t}\n\t\t}\n\n\t\treturn link.toString();\n\t}\n\n\tasync create({\n\t\tsigner,\n\t\t...options\n\t}: CreateZkSendLinkOptions & {\n\t\tsigner: Signer;\n\t\twaitForTransactionBlock?: boolean;\n\t}) {\n\t\tconst txb = await this.createSendTransaction(options);\n\n\t\tconst result = await this.#client.signAndExecuteTransactionBlock({\n\t\t\ttransactionBlock: await txb.build({ client: this.#client }),\n\t\t\tsigner,\n\t\t});\n\n\t\tif (options.waitForTransactionBlock) {\n\t\t\tawait this.#client.waitForTransactionBlock({ digest: result.digest });\n\t\t}\n\n\t\treturn result;\n\t}\n\tasync createSendTransaction({\n\t\ttransactionBlock = new TransactionBlock(),\n\t\tcalculateGas,\n\t}: CreateZkSendLinkOptions = {}) {\n\t\tif (!this.#contract) {\n\t\t\treturn this.#createSendTransactionWithoutContract({ transactionBlock, calculateGas });\n\t\t}\n\n\t\ttransactionBlock.setSenderIfNotSet(this.sender);\n\n\t\treturn ZkSendLinkBuilder.createLinks({\n\t\t\ttransactionBlock,\n\t\t\tclient: this.#client,\n\t\t\tcontract: this.#contract.ids,\n\t\t\tlinks: [this],\n\t\t});\n\t}\n\n\tasync #objectsToTransfer(txb: TransactionBlock) {\n\t\tconst objectIDs = [...this.objectIds];\n\t\tconst refsWithType: {\n\t\t\tref: TransactionObjectArgument;\n\t\t\ttype: string;\n\t\t}[] = (\n\t\t\tawait this.#client.multiGetObjects({\n\t\t\t\tids: objectIDs,\n\t\t\t\toptions: {\n\t\t\t\t\tshowType: true,\n\t\t\t\t},\n\t\t\t})\n\t\t).map((res, i) => {\n\t\t\tif (!res.data || res.error) {\n\t\t\t\tthrow new Error(`Failed to load object ${objectIDs[i]} (${res.error?.code})`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tref: txb.objectRef({\n\t\t\t\t\tversion: res.data.version,\n\t\t\t\t\tdigest: res.data.digest,\n\t\t\t\t\tobjectId: res.data.objectId,\n\t\t\t\t}),\n\t\t\t\ttype: res.data.type!,\n\t\t\t};\n\t\t});\n\n\t\ttxb.setSenderIfNotSet(this.sender);\n\n\t\tfor (const [coinType, amount] of this.balances) {\n\t\t\tif (coinType === SUI_COIN_TYPE) {\n\t\t\t\tconst [sui] = txb.splitCoins(txb.gas, [amount]);\n\t\t\t\trefsWithType.push({\n\t\t\t\t\tref: sui,\n\t\t\t\t\ttype: `0x2::coin::Coin<${coinType}>`,\n\t\t\t\t} as never);\n\t\t\t} else {\n\t\t\t\tconst coins = (await this.#getCoinsByType(coinType)).map((coin) => coin.coinObjectId);\n\n\t\t\t\tif (coins.length > 1) {\n\t\t\t\t\ttxb.mergeCoins(coins[0], coins.slice(1));\n\t\t\t\t}\n\t\t\t\tconst [split] = txb.splitCoins(coins[0], [amount]);\n\t\t\t\trefsWithType.push({\n\t\t\t\t\tref: split,\n\t\t\t\t\ttype: `0x2::coin:Coin<${coinType}>`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn refsWithType;\n\t}\n\n\tasync #createSendTransactionWithoutContract({\n\t\ttransactionBlock: txb = new TransactionBlock(),\n\t\tcalculateGas,\n\t}: CreateZkSendLinkOptions = {}) {\n\t\tconst gasEstimateFromDryRun = await this.#estimateClaimGasFee();\n\t\tconst baseGasAmount = calculateGas\n\t\t\t? await calculateGas({\n\t\t\t\t\tbalances: this.balances,\n\t\t\t\t\tobjects: [...this.objectIds],\n\t\t\t\t\tgasEstimateFromDryRun,\n\t\t\t })\n\t\t\t: gasEstimateFromDryRun * 2n;\n\n\t\t// Ensure that rounded gas is not less than the calculated gas\n\t\tconst gasWithBuffer = baseGasAmount + 1013n;\n\t\t// Ensure that gas amount ends in 987\n\t\tconst roundedGasAmount = gasWithBuffer - (gasWithBuffer % 1000n) - 13n;\n\n\t\tconst address = this.keypair.toSuiAddress();\n\t\tconst objectsToTransfer = (await this.#objectsToTransfer(txb)).map((obj) => obj.ref);\n\t\tconst [gas] = txb.splitCoins(txb.gas, [roundedGasAmount]);\n\t\tobjectsToTransfer.push(gas);\n\n\t\ttxb.setSenderIfNotSet(this.sender);\n\t\ttxb.transferObjects(objectsToTransfer, address);\n\n\t\treturn txb;\n\t}\n\n\tasync #estimateClaimGasFee(): Promise<bigint> {\n\t\tconst txb = new TransactionBlock();\n\t\ttxb.setSender(this.sender);\n\t\ttxb.setGasPayment([]);\n\t\ttxb.transferObjects([txb.gas], this.keypair.toSuiAddress());\n\n\t\tconst idsToTransfer = [...this.objectIds];\n\n\t\tfor (const [coinType] of this.balances) {\n\t\t\tconst coins = await this.#getCoinsByType(coinType);\n\n\t\t\tif (!coins.length) {\n\t\t\t\tthrow new Error(`Sending account does not contain any coins of type ${coinType}`);\n\t\t\t}\n\n\t\t\tidsToTransfer.push(coins[0].coinObjectId);\n\t\t}\n\n\t\tif (idsToTransfer.length > 0) {\n\t\t\ttxb.transferObjects(\n\t\t\t\tidsToTransfer.map((id) => txb.object(id)),\n\t\t\t\tthis.keypair.toSuiAddress(),\n\t\t\t);\n\t\t}\n\n\t\tconst result = await this.#client.dryRunTransactionBlock({\n\t\t\ttransactionBlock: await txb.build({ client: this.#client }),\n\t\t});\n\n\t\treturn (\n\t\t\tBigInt(result.effects.gasUsed.computationCost) +\n\t\t\tBigInt(result.effects.gasUsed.storageCost) -\n\t\t\tBigInt(result.effects.gasUsed.storageRebate)\n\t\t);\n\t}\n\n\tasync #getCoinsByType(coinType: string) {\n\t\tif (this.#coinsByType.has(coinType)) {\n\t\t\treturn this.#coinsByType.get(coinType)!;\n\t\t}\n\n\t\tconst coins = await this.#client.getCoins({\n\t\t\tcoinType,\n\t\t\towner: this.sender,\n\t\t});\n\n\t\tthis.#coinsByType.set(coinType, coins.data);\n\n\t\treturn coins.data;\n\t}\n\n\tstatic async createLinks({\n\t\tlinks,\n\t\tnetwork = 'mainnet',\n\t\tclient = new SuiClient({ url: getFullnodeUrl(network) }),\n\t\ttransactionBlock = new TransactionBlock(),\n\t\tcontract: contractIds = MAINNET_CONTRACT_IDS,\n\t}: {\n\t\ttransactionBlock?: TransactionBlock;\n\t\tclient?: SuiClient;\n\t\tnetwork?: 'mainnet' | 'testnet';\n\t\tlinks: ZkSendLinkBuilder[];\n\t\tcontract: ZkBagContractOptions;\n\t}) {\n\t\tconst contract = new ZkBag(contractIds.packageId, contractIds);\n\t\tconst store = transactionBlock.object(contract.ids.bagStoreId);\n\n\t\tconst coinsByType = new Map<string, CoinStruct[]>();\n\t\tconst allIds = links.flatMap((link) => [...link.objectIds]);\n\n\t\tawait Promise.all(\n\t\t\t[...new Set(links.flatMap((link) => [...link.balances.keys()]))].map(async (coinType) => {\n\t\t\t\tconst coins = await client.getCoins({\n\t\t\t\t\tcoinType,\n\t\t\t\t\towner: links[0].sender,\n\t\t\t\t});\n\n\t\t\t\tcoinsByType.set(\n\t\t\t\t\tcoinType,\n\t\t\t\t\tcoins.data.filter((coin) => !allIds.includes(coin.coinObjectId)),\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\n\t\tconst objectRefs = new Map<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tref: TransactionObjectArgument;\n\t\t\t\ttype: string;\n\t\t\t}\n\t\t>();\n\n\t\tconst pageSize = 50;\n\t\tlet offset = 0;\n\t\twhile (offset < allIds.length) {\n\t\t\tlet chunk = allIds.slice(offset, offset + pageSize);\n\t\t\toffset += pageSize;\n\n\t\t\tconst objects = await client.multiGetObjects({\n\t\t\t\tids: chunk,\n\t\t\t\toptions: {\n\t\t\t\t\tshowType: true,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tfor (const [i, res] of objects.entries()) {\n\t\t\t\tif (!res.data || res.error) {\n\t\t\t\t\tthrow new Error(`Failed to load object ${chunk[i]} (${res.error?.code})`);\n\t\t\t\t}\n\t\t\t\tobjectRefs.set(chunk[i], {\n\t\t\t\t\tref: transactionBlock.objectRef({\n\t\t\t\t\t\tversion: res.data.version,\n\t\t\t\t\t\tdigest: res.data.digest,\n\t\t\t\t\t\tobjectId: res.data.objectId,\n\t\t\t\t\t}),\n\t\t\t\t\ttype: res.data.type!,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst mergedCoins = new Map<string, TransactionObjectArgument>([\n\t\t\t[SUI_COIN_TYPE, transactionBlock.gas],\n\t\t]);\n\n\t\tfor (const [coinType, coins] of coinsByType) {\n\t\t\tif (coinType === SUI_COIN_TYPE) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst [first, ...rest] = coins.map((coin) =>\n\t\t\t\ttransactionBlock.objectRef({\n\t\t\t\t\tobjectId: coin.coinObjectId,\n\t\t\t\t\tversion: coin.version,\n\t\t\t\t\tdigest: coin.digest,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (rest.length > 0) {\n\t\t\t\ttransactionBlock.mergeCoins(first, rest);\n\t\t\t}\n\t\t\tmergedCoins.set(coinType, transactionBlock.object(first));\n\t\t}\n\n\t\tfor (const link of links) {\n\t\t\tconst receiver = link.keypair.toSuiAddress();\n\t\t\tcontract.new(transactionBlock, { arguments: [store, receiver] });\n\n\t\t\tlink.objectIds.forEach((id) => {\n\t\t\t\tconst object = objectRefs.get(id);\n\t\t\t\tif (!object) {\n\t\t\t\t\tthrow new Error(`Object ${id} not found`);\n\t\t\t\t}\n\t\t\t\tcontract.add(transactionBlock, {\n\t\t\t\t\targuments: [store, receiver, object.ref],\n\t\t\t\t\ttypeArguments: [object.type],\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tfor (const [coinType, merged] of mergedCoins) {\n\t\t\tconst linksWithCoin = links.filter((link) => link.balances.has(coinType));\n\t\t\tif (linksWithCoin.length === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst balances = linksWithCoin.map((link) => link.balances.get(coinType)!);\n\t\t\tconst splits = transactionBlock.splitCoins(merged, balances);\n\t\t\tfor (const [i, link] of linksWithCoin.entries()) {\n\t\t\t\tcontract.add(transactionBlock, {\n\t\t\t\t\targuments: [store, link.keypair.toSuiAddress(), splits[i]],\n\t\t\t\t\ttypeArguments: [`0x2::coin::Coin<${coinType}>`],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn transactionBlock;\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAGA,SAAS,gBAAgB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
  }
@@ -2,6 +2,7 @@ import { SuiClient } from '@mysten/sui.js/client';
2
2
  import type { Keypair } from '@mysten/sui.js/cryptography';
3
3
  import { TransactionBlock } from '@mysten/sui.js/transactions';
4
4
  import type { ZkSendLinkBuilderOptions } from './builder.js';
5
+ import type { LinkAssets } from './utils.js';
5
6
  import type { ZkBagContractOptions } from './zk-bag.js';
6
7
  export type ZkSendLinkOptions = {
7
8
  claimApi?: string;
@@ -11,66 +12,28 @@ export type ZkSendLinkOptions = {
11
12
  host?: string;
12
13
  path?: string;
13
14
  address?: string;
15
+ isContractLink: boolean;
16
+ contract?: ZkBagContractOptions | null;
14
17
  } & ({
15
18
  address: string;
16
19
  keypair?: never;
17
20
  } | {
18
21
  keypair: Keypair;
19
22
  address?: never;
20
- }) & ({
21
- isContractLink: true;
22
- contract: ZkBagContractOptions;
23
- } | {
24
- isContractLink: false;
25
- contract?: never;
26
23
  });
27
24
  export declare class ZkSendLink {
28
25
  #private;
29
26
  address: string;
30
27
  keypair?: Keypair;
31
28
  creatorAddress?: string;
29
+ assets?: LinkAssets;
30
+ claimed?: boolean;
32
31
  constructor({ network, claimApi, client, keypair, contract, address, host, path, isContractLink, }: ZkSendLinkOptions);
33
- static fromUrl(url: string, { contract, ...options }?: Omit<ZkSendLinkOptions, 'keypair' | 'address' | 'isContractLink'>): Promise<ZkSendLink>;
34
- static fromAddress(address: string, options: Omit<ZkSendLinkOptions, 'keypair' | 'address' | 'isContractLink'> & {
35
- contract: ZkBagContractOptions;
36
- }): Promise<ZkSendLink>;
37
- loadOwnedData(): Promise<void>;
38
- listClaimableAssets(address: string, options?: {
39
- claimObjectsAddedAfterCreation?: boolean;
40
- coinTypes?: string[];
41
- objects?: string[];
42
- }): Promise<{
43
- balances: {
44
- coinType: string;
45
- amount: bigint;
46
- }[];
47
- nfts: {
48
- objectId: string;
49
- type: string;
50
- version: string;
51
- digest: string;
52
- }[];
53
- coins: {
54
- objectId: string;
55
- type: string;
56
- version: string;
57
- digest: string;
58
- }[];
59
- }>;
60
- claimAssets(address: string,
61
- /** @deprecated filtering claims is not supported in contract based links */
62
- options?: {
63
- claimObjectsAddedAfterCreation?: boolean;
64
- coinTypes?: string[];
65
- objects?: string[];
66
- }): Promise<import("@mysten/sui.js/client").SuiTransactionBlockResponse>;
67
- createClaimTransaction(address: string, { reclaim, ...options }?: {
68
- /** @deprecated filtering claims is not supported in contract based links */
69
- claimObjectsAddedAfterCreation?: boolean;
70
- /** @deprecated filtering claims is not supported in contract based links */
71
- coinTypes?: string[];
72
- /** @deprecated filtering claims is not supported in contract based links */
73
- objects?: string[];
32
+ static fromUrl(url: string, options?: Omit<ZkSendLinkOptions, 'keypair' | 'address' | 'isContractLink'>): Promise<ZkSendLink>;
33
+ static fromAddress(address: string, options: Omit<ZkSendLinkOptions, 'keypair' | 'address' | 'isContractLink'>): Promise<ZkSendLink>;
34
+ loadAssets(): Promise<void>;
35
+ claimAssets(address: string): Promise<import("@mysten/sui.js/client").SuiTransactionBlockResponse>;
36
+ createClaimTransaction(address: string, { reclaim, }?: {
74
37
  reclaim?: boolean;
75
38
  }): TransactionBlock;
76
39
  createRegenerateTransaction(sender: string, options?: Omit<ZkSendLinkBuilderOptions, 'sender'>): Promise<{
@@ -20,7 +20,8 @@ var __privateMethod = (obj, member, method) => {
20
20
  __accessCheck(obj, member, "access private method");
21
21
  return method;
22
22
  };
23
- var _client, _initiallyOwnedObjects, _ownedObjects, _bagObjects, _gasCoin, _hasSui, _contract, _claimApi, _network, _host, _path, _loadBag, loadBag_fn, _createSponsoredTransactionBlock, createSponsoredTransactionBlock_fn, _executeSponsoredTransactionBlock, executeSponsoredTransactionBlock_fn, _fetch, fetch_fn, _listNonContractClaimableAssets, listNonContractClaimableAssets_fn, _createNonContractClaimTransaction, createNonContractClaimTransaction_fn, _loadOwnedObjects, loadOwnedObjects_fn, _loadInitialTransactionData, loadInitialTransactionData_fn;
23
+ var _client, _contract, _claimApi, _network, _host, _path, _gasCoin, _hasSui, _ownedObjects, _loadBag, loadBag_fn, _loadClaimedAssets, loadClaimedAssets_fn, _createSponsoredTransactionBlock, createSponsoredTransactionBlock_fn, _executeSponsoredTransactionBlock, executeSponsoredTransactionBlock_fn, _fetch, fetch_fn, _listNonContractClaimableAssets, listNonContractClaimableAssets_fn, _createNonContractClaimTransaction, createNonContractClaimTransaction_fn, _loadOwnedObjects, loadOwnedObjects_fn;
24
+ import { bcs } from "@mysten/sui.js/bcs";
24
25
  import { getFullnodeUrl, SuiClient } from "@mysten/sui.js/client";
25
26
  import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
26
27
  import { TransactionBlock } from "@mysten/sui.js/transactions";
@@ -34,7 +35,8 @@ import {
34
35
  toB64
35
36
  } from "@mysten/sui.js/utils";
36
37
  import { ZkSendLinkBuilder } from "./builder.js";
37
- import { ZkBag } from "./zk-bag.js";
38
+ import { getAssetsFromTxnBlock, isOwner, ownedAfterChange } from "./utils.js";
39
+ import { MAINNET_CONTRACT_IDS, ZkBag } from "./zk-bag.js";
38
40
  const DEFAULT_ZK_SEND_LINK_OPTIONS = {
39
41
  host: "https://zksend.com",
40
42
  path: "/claim",
@@ -49,31 +51,30 @@ const _ZkSendLink = class {
49
51
  claimApi = DEFAULT_ZK_SEND_LINK_OPTIONS.claimApi,
50
52
  client = new SuiClient({ url: getFullnodeUrl(network) }),
51
53
  keypair,
52
- contract,
54
+ contract = network === "mainnet" ? MAINNET_CONTRACT_IDS : null,
53
55
  address,
54
56
  host,
55
57
  path,
56
58
  isContractLink
57
59
  }) {
58
60
  __privateAdd(this, _loadBag);
61
+ __privateAdd(this, _loadClaimedAssets);
59
62
  __privateAdd(this, _createSponsoredTransactionBlock);
60
63
  __privateAdd(this, _executeSponsoredTransactionBlock);
61
64
  __privateAdd(this, _fetch);
62
65
  __privateAdd(this, _listNonContractClaimableAssets);
63
66
  __privateAdd(this, _createNonContractClaimTransaction);
64
67
  __privateAdd(this, _loadOwnedObjects);
65
- __privateAdd(this, _loadInitialTransactionData);
66
68
  __privateAdd(this, _client, void 0);
67
- __privateAdd(this, _initiallyOwnedObjects, /* @__PURE__ */ new Set());
68
- __privateAdd(this, _ownedObjects, []);
69
- __privateAdd(this, _bagObjects, null);
70
- __privateAdd(this, _gasCoin, void 0);
71
- __privateAdd(this, _hasSui, false);
72
69
  __privateAdd(this, _contract, void 0);
73
70
  __privateAdd(this, _claimApi, void 0);
74
71
  __privateAdd(this, _network, void 0);
75
72
  __privateAdd(this, _host, void 0);
76
73
  __privateAdd(this, _path, void 0);
74
+ // State for non-contract based links
75
+ __privateAdd(this, _gasCoin, void 0);
76
+ __privateAdd(this, _hasSui, false);
77
+ __privateAdd(this, _ownedObjects, []);
77
78
  if (!keypair && !address) {
78
79
  throw new Error("Either keypair or address must be provided");
79
80
  }
@@ -91,25 +92,18 @@ const _ZkSendLink = class {
91
92
  __privateSet(this, _contract, new ZkBag(contract.packageId, contract));
92
93
  }
93
94
  }
94
- static async fromUrl(url, {
95
- contract,
96
- ...options
97
- } = {}) {
95
+ static async fromUrl(url, options = {}) {
98
96
  const parsed = new URL(url);
99
97
  const isContractLink = parsed.hash.startsWith("#$");
100
98
  let link;
101
99
  if (isContractLink) {
102
- if (!contract) {
103
- throw new Error("Contract options are required for contract based links");
104
- }
105
100
  const keypair = Ed25519Keypair.fromSecretKey(fromB64(parsed.hash.slice(2)));
106
101
  link = new _ZkSendLink({
107
102
  ...options,
108
103
  keypair,
109
104
  host: `${parsed.protocol}//${parsed.host}`,
110
105
  path: parsed.pathname,
111
- isContractLink: true,
112
- contract
106
+ isContractLink: true
113
107
  });
114
108
  } else {
115
109
  const keypair = Ed25519Keypair.fromSecretKey(
@@ -123,7 +117,7 @@ const _ZkSendLink = class {
123
117
  isContractLink: false
124
118
  });
125
119
  }
126
- await link.loadOwnedData();
120
+ await link.loadAssets();
127
121
  return link;
128
122
  }
129
123
  static async fromAddress(address, options) {
@@ -132,72 +126,41 @@ const _ZkSendLink = class {
132
126
  address,
133
127
  isContractLink: true
134
128
  });
135
- await link.loadOwnedData();
129
+ await link.loadAssets();
136
130
  return link;
137
131
  }
138
- async loadOwnedData() {
132
+ async loadAssets() {
139
133
  if (__privateGet(this, _contract)) {
140
134
  await __privateMethod(this, _loadBag, loadBag_fn).call(this);
141
135
  } else {
142
- await Promise.all([__privateMethod(this, _loadInitialTransactionData, loadInitialTransactionData_fn).call(this), __privateMethod(this, _loadOwnedObjects, loadOwnedObjects_fn).call(this)]);
136
+ await __privateMethod(this, _loadOwnedObjects, loadOwnedObjects_fn).call(this);
143
137
  }
144
138
  }
145
- async listClaimableAssets(address, options) {
146
- if (!__privateGet(this, _contract)) {
147
- return __privateMethod(this, _listNonContractClaimableAssets, listNonContractClaimableAssets_fn).call(this, address, options);
148
- }
149
- const coins = [];
150
- const nfts = [];
151
- for (const object of __privateGet(this, _bagObjects) ?? []) {
152
- const type = parseStructTag(object.type);
153
- if (type.address === normalizeSuiAddress("0x2") && type.module === "coin" && type.name === "Coin") {
154
- coins.push(object);
155
- } else {
156
- nfts.push(object);
157
- }
158
- }
159
- const balances = /* @__PURE__ */ new Map();
160
- coins.forEach((coin) => {
161
- if (coin.content?.dataType !== "moveObject") {
162
- return;
163
- }
164
- const amount = BigInt(coin.content.fields.balance);
165
- const coinType = normalizeStructTag(parseStructTag(coin.content.type).typeParams[0]);
166
- if (!balances.has(coinType)) {
167
- balances.set(coinType, { coinType, amount });
168
- } else {
169
- balances.get(coinType).amount += amount;
170
- }
171
- });
172
- return {
173
- balances: [...balances.values()],
174
- nfts,
175
- coins
176
- };
177
- }
178
- async claimAssets(address, options) {
139
+ async claimAssets(address) {
179
140
  if (!this.keypair) {
180
141
  throw new Error("Cannot claim assets without links keypair");
181
142
  }
182
- const txb = this.createClaimTransaction(address, options);
183
- if (!__privateGet(this, _contract) || !__privateGet(this, _bagObjects)) {
143
+ if (this.claimed) {
144
+ throw new Error("Assets have already been claimed");
145
+ }
146
+ if (!__privateGet(this, _contract)) {
184
147
  return __privateGet(this, _client).signAndExecuteTransactionBlock({
185
- transactionBlock: txb,
148
+ transactionBlock: this.createClaimTransaction(address),
186
149
  signer: this.keypair
187
150
  });
188
151
  }
152
+ if (!this.assets) {
153
+ await __privateMethod(this, _loadBag, loadBag_fn).call(this);
154
+ }
155
+ const txb = this.createClaimTransaction(address);
189
156
  const { digest } = await __privateMethod(this, _executeSponsoredTransactionBlock, executeSponsoredTransactionBlock_fn).call(this, await __privateMethod(this, _createSponsoredTransactionBlock, createSponsoredTransactionBlock_fn).call(this, txb, address, this.keypair.toSuiAddress()), this.keypair);
190
157
  return __privateGet(this, _client).waitForTransactionBlock({ digest });
191
158
  }
192
159
  createClaimTransaction(address, {
193
- reclaim,
194
- ...options
160
+ reclaim
195
161
  } = {}) {
196
162
  if (!__privateGet(this, _contract)) {
197
- return __privateMethod(this, _createNonContractClaimTransaction, createNonContractClaimTransaction_fn).call(this, address, options);
198
- }
199
- if (Object.keys(options).length > 0) {
200
- throw new Error("Filtering claims is not supported for contract based links");
163
+ return __privateMethod(this, _createNonContractClaimTransaction, createNonContractClaimTransaction_fn).call(this, address);
201
164
  }
202
165
  if (!this.keypair && !reclaim) {
203
166
  throw new Error("Cannot claim assets without the links keypair");
@@ -208,7 +171,8 @@ const _ZkSendLink = class {
208
171
  const store = txb.object(__privateGet(this, _contract).ids.bagStoreId);
209
172
  const [bag, proof] = reclaim ? __privateGet(this, _contract).reclaim(txb, { arguments: [store, this.address] }) : __privateGet(this, _contract).init_claim(txb, { arguments: [store] });
210
173
  const objectsToTransfer = [];
211
- for (const object of __privateGet(this, _bagObjects) ?? []) {
174
+ const objects = [...this.assets?.coins ?? [], ...this.assets?.nfts ?? []];
175
+ for (const object of objects) {
212
176
  objectsToTransfer.push(
213
177
  __privateGet(this, _contract).claim(txb, {
214
178
  arguments: [
@@ -231,7 +195,13 @@ const _ZkSendLink = class {
231
195
  return txb;
232
196
  }
233
197
  async createRegenerateTransaction(sender, options = {}) {
234
- if (!__privateGet(this, _contract) || !__privateGet(this, _bagObjects)) {
198
+ if (!this.assets) {
199
+ await __privateMethod(this, _loadBag, loadBag_fn).call(this);
200
+ }
201
+ if (this.claimed) {
202
+ throw new Error("Assets have already been claimed");
203
+ }
204
+ if (!__privateGet(this, _contract)) {
235
205
  throw new Error("Regenerating non-contract based links is not supported");
236
206
  }
237
207
  const txb = new TransactionBlock();
@@ -257,21 +227,24 @@ const _ZkSendLink = class {
257
227
  };
258
228
  let ZkSendLink = _ZkSendLink;
259
229
  _client = new WeakMap();
260
- _initiallyOwnedObjects = new WeakMap();
261
- _ownedObjects = new WeakMap();
262
- _bagObjects = new WeakMap();
263
- _gasCoin = new WeakMap();
264
- _hasSui = new WeakMap();
265
230
  _contract = new WeakMap();
266
231
  _claimApi = new WeakMap();
267
232
  _network = new WeakMap();
268
233
  _host = new WeakMap();
269
234
  _path = new WeakMap();
235
+ _gasCoin = new WeakMap();
236
+ _hasSui = new WeakMap();
237
+ _ownedObjects = new WeakMap();
270
238
  _loadBag = new WeakSet();
271
239
  loadBag_fn = async function() {
272
240
  if (!__privateGet(this, _contract)) {
273
241
  return;
274
242
  }
243
+ this.assets = {
244
+ balances: [],
245
+ nfts: [],
246
+ coins: []
247
+ };
275
248
  const bagField = await __privateGet(this, _client).getDynamicFieldObject({
276
249
  parentId: __privateGet(this, _contract).ids.bagStoreTableId,
277
250
  name: {
@@ -280,7 +253,11 @@ loadBag_fn = async function() {
280
253
  }
281
254
  });
282
255
  if (!bagField.data) {
256
+ this.claimed = true;
257
+ await __privateMethod(this, _loadClaimedAssets, loadClaimedAssets_fn).call(this);
283
258
  return;
259
+ } else {
260
+ this.claimed = false;
284
261
  }
285
262
  const itemIds = bagField.data?.content?.fields?.value?.fields?.item_ids.fields.contents;
286
263
  this.creatorAddress = bagField.data?.content?.fields?.value?.fields?.owner;
@@ -294,18 +271,81 @@ loadBag_fn = async function() {
294
271
  showContent: true
295
272
  }
296
273
  });
297
- __privateSet(this, _bagObjects, objectsResponse.map((object, i) => {
298
- if (!object.data) {
274
+ const balances = /* @__PURE__ */ new Map();
275
+ objectsResponse.forEach((object, i) => {
276
+ if (!object.data || !object.data.type) {
299
277
  throw new Error(`Failed to load claimable object ${itemIds[i]}`);
300
278
  }
301
- return {
302
- objectId: object.data.objectId,
303
- type: normalizeStructTag(object.data.type),
304
- version: object.data.version,
305
- digest: object.data.digest,
306
- content: object.data.content
307
- };
308
- }));
279
+ const type = parseStructTag(normalizeStructTag(object.data.type));
280
+ if (type.address === normalizeSuiAddress("0x2") && type.module === "coin" && type.name === "Coin") {
281
+ this.assets.coins.push({
282
+ objectId: object.data.objectId,
283
+ type: object.data.type,
284
+ version: object.data.version,
285
+ digest: object.data.digest
286
+ });
287
+ if (object.data.content?.dataType === "moveObject") {
288
+ const amount = BigInt(object.data.content.fields.balance);
289
+ const coinType = normalizeStructTag(
290
+ parseStructTag(object.data.content.type).typeParams[0]
291
+ );
292
+ if (!balances.has(coinType)) {
293
+ balances.set(coinType, { coinType, amount });
294
+ } else {
295
+ balances.get(coinType).amount += amount;
296
+ }
297
+ }
298
+ } else {
299
+ this.assets.nfts.push({
300
+ objectId: object.data.objectId,
301
+ type: object.data.type,
302
+ version: object.data.version,
303
+ digest: object.data.digest
304
+ });
305
+ }
306
+ });
307
+ this.assets.balances = [...balances.values()];
308
+ };
309
+ _loadClaimedAssets = new WeakSet();
310
+ loadClaimedAssets_fn = async function() {
311
+ const result = await __privateGet(this, _client).queryTransactionBlocks({
312
+ limit: 1,
313
+ filter: {
314
+ FromAddress: this.address
315
+ },
316
+ options: {
317
+ showObjectChanges: true,
318
+ showBalanceChanges: true,
319
+ showInput: true
320
+ }
321
+ });
322
+ if (!result?.data[0]) {
323
+ return;
324
+ }
325
+ const [txb] = result.data;
326
+ if (txb.transaction?.data.transaction.kind !== "ProgrammableTransaction") {
327
+ return;
328
+ }
329
+ const transfer = txb.transaction.data.transaction.transactions.findLast(
330
+ (tx) => "TransferObjects" in tx
331
+ );
332
+ if (!transfer) {
333
+ return;
334
+ }
335
+ const receiverArg = transfer.TransferObjects[1];
336
+ if (!(typeof receiverArg === "object" && "Input" in receiverArg)) {
337
+ return;
338
+ }
339
+ const input = txb.transaction.data.transaction.inputs[receiverArg.Input];
340
+ if (input.type !== "pure") {
341
+ return;
342
+ }
343
+ const receiver = typeof input.value === "string" ? input.value : bcs.Address.parse(new Uint8Array(input.value.Pure));
344
+ this.assets = getAssetsFromTxnBlock({
345
+ transactionBlock: txb,
346
+ address: receiver,
347
+ isSent: false
348
+ });
309
349
  };
310
350
  _createSponsoredTransactionBlock = new WeakSet();
311
351
  createSponsoredTransactionBlock_fn = async function(txb, claimer, sender) {
@@ -357,18 +397,26 @@ fetch_fn = async function(path, init) {
357
397
  return data;
358
398
  };
359
399
  _listNonContractClaimableAssets = new WeakSet();
360
- listNonContractClaimableAssets_fn = async function(address, options) {
400
+ listNonContractClaimableAssets_fn = async function() {
401
+ const balances = [];
402
+ const nfts = [];
403
+ const coins = [];
404
+ if (__privateGet(this, _ownedObjects).length === 0 && !__privateGet(this, _hasSui)) {
405
+ return {
406
+ balances,
407
+ nfts,
408
+ coins
409
+ };
410
+ }
411
+ const address = new Ed25519Keypair().toSuiAddress();
361
412
  const normalizedAddress = normalizeSuiAddress(address);
362
- const txb = this.createClaimTransaction(normalizedAddress, options);
413
+ const txb = this.createClaimTransaction(normalizedAddress);
363
414
  if (__privateGet(this, _gasCoin) || !__privateGet(this, _hasSui)) {
364
415
  txb.setGasPayment([]);
365
416
  }
366
417
  const dryRun = await __privateGet(this, _client).dryRunTransactionBlock({
367
418
  transactionBlock: await txb.build({ client: __privateGet(this, _client) })
368
419
  });
369
- const balances = [];
370
- const nfts = [];
371
- const coins = [];
372
420
  dryRun.balanceChanges.forEach((balanceChange) => {
373
421
  if (BigInt(balanceChange.amount) > 0n && isOwner(balanceChange.owner, normalizedAddress)) {
374
422
  balances.push({
@@ -398,16 +446,12 @@ listNonContractClaimableAssets_fn = async function(address, options) {
398
446
  };
399
447
  };
400
448
  _createNonContractClaimTransaction = new WeakSet();
401
- createNonContractClaimTransaction_fn = function(address, options) {
449
+ createNonContractClaimTransaction_fn = function(address) {
402
450
  if (!this.keypair) {
403
451
  throw new Error("Cannot claim assets without the links keypair");
404
452
  }
405
- const claimAll = !options?.coinTypes && !options?.objects;
406
453
  const txb = new TransactionBlock();
407
454
  txb.setSender(this.keypair.toSuiAddress());
408
- const coinTypes = new Set(
409
- options?.coinTypes?.map((type) => normalizeStructTag(`0x2::coin::Coin<${type}>`)) ?? []
410
- );
411
455
  const objectsToTransfer = __privateGet(this, _ownedObjects).filter((object) => {
412
456
  if (__privateGet(this, _gasCoin)) {
413
457
  if (object.objectId === __privateGet(this, _gasCoin).coinObjectId) {
@@ -416,17 +460,11 @@ createNonContractClaimTransaction_fn = function(address, options) {
416
460
  } else if (object.type === SUI_COIN_OBJECT_TYPE) {
417
461
  return false;
418
462
  }
419
- if (coinTypes?.has(object.type) || options?.objects?.includes(object.objectId)) {
420
- return true;
421
- }
422
- if (!options?.claimObjectsAddedAfterCreation && !__privateGet(this, _initiallyOwnedObjects).has(object.objectId)) {
423
- return false;
424
- }
425
- return claimAll;
463
+ return true;
426
464
  }).map((object) => txb.object(object.objectId));
427
465
  if (__privateGet(this, _gasCoin) && this.creatorAddress) {
428
466
  txb.transferObjects([txb.gas], this.creatorAddress);
429
- } else if (claimAll || coinTypes?.has(SUI_COIN_TYPE)) {
467
+ } else {
430
468
  objectsToTransfer.push(txb.gas);
431
469
  }
432
470
  if (objectsToTransfer.length > 0) {
@@ -436,14 +474,19 @@ createNonContractClaimTransaction_fn = function(address, options) {
436
474
  };
437
475
  _loadOwnedObjects = new WeakSet();
438
476
  loadOwnedObjects_fn = async function() {
439
- __privateSet(this, _ownedObjects, []);
477
+ this.assets = {
478
+ nfts: [],
479
+ balances: [],
480
+ coins: []
481
+ };
440
482
  let nextCursor;
441
483
  do {
442
484
  const ownedObjects = await __privateGet(this, _client).getOwnedObjects({
443
485
  cursor: nextCursor,
444
486
  owner: this.address,
445
487
  options: {
446
- showType: true
488
+ showType: true,
489
+ showContent: true
447
490
  }
448
491
  });
449
492
  nextCursor = ownedObjects.hasNextPage ? ownedObjects.nextCursor : null;
@@ -464,9 +507,6 @@ loadOwnedObjects_fn = async function() {
464
507
  });
465
508
  __privateSet(this, _hasSui, coins.data.length > 0);
466
509
  __privateSet(this, _gasCoin, coins.data.find((coin) => BigInt(coin.balance) % 1000n === 987n));
467
- };
468
- _loadInitialTransactionData = new WeakSet();
469
- loadInitialTransactionData_fn = async function() {
470
510
  const result = await __privateGet(this, _client).queryTransactionBlocks({
471
511
  limit: 1,
472
512
  order: "ascending",
@@ -474,29 +514,20 @@ loadInitialTransactionData_fn = async function() {
474
514
  ToAddress: this.address
475
515
  },
476
516
  options: {
477
- showObjectChanges: true,
478
- showInput: true
479
- }
480
- });
481
- result.data[0]?.objectChanges?.forEach((objectChange) => {
482
- if (ownedAfterChange(objectChange, this.address)) {
483
- __privateGet(this, _initiallyOwnedObjects).add(normalizeSuiObjectId(objectChange.objectId));
517
+ showInput: true,
518
+ showBalanceChanges: true,
519
+ showObjectChanges: true
484
520
  }
485
521
  });
486
522
  this.creatorAddress = result.data[0]?.transaction?.data.sender;
487
- };
488
- function ownedAfterChange(objectChange, address) {
489
- if (objectChange.type === "transferred" && isOwner(objectChange.recipient, address)) {
490
- return true;
523
+ if (__privateGet(this, _hasSui) || __privateGet(this, _ownedObjects).length > 0) {
524
+ this.claimed = false;
525
+ this.assets = await __privateMethod(this, _listNonContractClaimableAssets, listNonContractClaimableAssets_fn).call(this);
526
+ } else if (result.data[0]) {
527
+ this.claimed = true;
528
+ await __privateMethod(this, _loadClaimedAssets, loadClaimedAssets_fn).call(this);
491
529
  }
492
- if ((objectChange.type === "created" || objectChange.type === "mutated") && isOwner(objectChange.owner, address)) {
493
- return true;
494
- }
495
- return false;
496
- }
497
- function isOwner(owner, address) {
498
- return owner && typeof owner === "object" && "AddressOwner" in owner && normalizeSuiAddress(owner.AddressOwner) === address;
499
- }
530
+ };
500
531
  export {
501
532
  ZkSendLink
502
533
  };