storacha-sol 0.0.4 → 0.0.6
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/README.md +65 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -23
- package/dist/index.d.ts +204 -23
- package/dist/index.js +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -11,12 +11,12 @@ Here are a couple of things you can do with this package:
|
|
|
11
11
|
- View your upload history (all files you've stored with their details)
|
|
12
12
|
- Get expiration warnings via email before your files expire
|
|
13
13
|
- Automatic deletion of expired files from Storacha
|
|
14
|
+
- Renew/extend storage duration for existing uploads
|
|
14
15
|
|
|
15
16
|
Stuffs we hope to cover or extend:
|
|
16
17
|
|
|
17
18
|
- Allow payments from other chains. (Filecoin next)
|
|
18
19
|
- Include implementations for other libs. Right now, we only have React. Hoping to cover, Vue, Svelte etc.
|
|
19
|
-
- Add ability to renew/increase upload duration (coming soon! see [GitHub issues](https://github.com/seetadev/storacha-solana-sdk/issues))
|
|
20
20
|
|
|
21
21
|
## Usage
|
|
22
22
|
|
|
@@ -123,6 +123,7 @@ console.log(history.userHistory); // Array of all deposits
|
|
|
123
123
|
```
|
|
124
124
|
|
|
125
125
|
Each deposit in the history includes:
|
|
126
|
+
|
|
126
127
|
- File details (name, size, type, CID)
|
|
127
128
|
- Expiration date
|
|
128
129
|
- Deletion status (`active`, `warned`, `deleted`)
|
|
@@ -149,6 +150,7 @@ const result = await client.createDeposit({
|
|
|
149
150
|
If provided, you'll receive an email notification **7 days before your file expires**, giving you time to extend the storage duration (feature coming soon!).
|
|
150
151
|
|
|
151
152
|
The warning email includes:
|
|
153
|
+
|
|
152
154
|
- File name and CID
|
|
153
155
|
- Exact expiration date
|
|
154
156
|
- Number of days remaining
|
|
@@ -157,12 +159,74 @@ The warning email includes:
|
|
|
157
159
|
### Automatic Cleanup
|
|
158
160
|
|
|
159
161
|
Files that have expired are automatically deleted from Storacha storage. This happens through a scheduled job that:
|
|
162
|
+
|
|
160
163
|
1. Identifies expired deposits
|
|
161
164
|
2. Removes the data from Storacha (including shards)
|
|
162
165
|
3. Updates the deletion status in the database
|
|
163
166
|
|
|
164
167
|
Your upload history will show the deletion status, so you can track which files are still active, warned, or deleted.
|
|
165
168
|
|
|
169
|
+
### Storage Renewal
|
|
170
|
+
|
|
171
|
+
Extend the storage duration for your existing uploads before they expire:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
const client = useDeposit('testnet' as Environment);
|
|
175
|
+
const { publicKey, signTransaction } = useSolanaWallet();
|
|
176
|
+
|
|
177
|
+
// First, get a quote to see what it'll cost
|
|
178
|
+
const quote = await client.getStorageRenewalCost(cid, 30); // 30 additional days
|
|
179
|
+
|
|
180
|
+
console.log(`Current expiration: ${quote.currentExpirationDate}`);
|
|
181
|
+
console.log(`New expiration: ${quote.newExpirationDate}`);
|
|
182
|
+
console.log(`Cost: ${quote.costInSOL} SOL`);
|
|
183
|
+
|
|
184
|
+
const result = await client.renewStorageDuration({
|
|
185
|
+
cid,
|
|
186
|
+
additionalDays: 30,
|
|
187
|
+
payer: publicKey,
|
|
188
|
+
signTransaction: async (tx) => {
|
|
189
|
+
const signed = await signTransaction(tx);
|
|
190
|
+
return signed;
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
if (result.success) {
|
|
195
|
+
console.log('Storage renewed! Transaction:', result.signature);
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**How it works:**
|
|
200
|
+
|
|
201
|
+
- `getStorageRenewalCost()` shows you the cost and new expiration date before committing
|
|
202
|
+
- `renewStorageDuration()` creates a payment transaction (same flow as initial upload)
|
|
203
|
+
- After payment confirms, your file's expiration date gets updated
|
|
204
|
+
|
|
205
|
+
## Usage with Vite
|
|
206
|
+
|
|
207
|
+
When using this SDK in a project built with Vite, you may encounter a `ReferenceError: process is not defined`. This is because Vite does not automatically polyfill the Node.js `process` global, which this library may use.
|
|
208
|
+
|
|
209
|
+
To resolve this, you can define `process.env` to safely access `NODE_ENV` and additionally install `vite-plugin-node-polyfills` as a dev dependency and edit your `vite.config.ts` file:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
// vite.config.ts
|
|
213
|
+
import { defineConfig } from 'vite';
|
|
214
|
+
import react from '@vitejs/plugin-react';
|
|
215
|
+
import { nodePolyfills } from 'vite-plugin-node-polyfills';
|
|
216
|
+
|
|
217
|
+
export default defineConfig({
|
|
218
|
+
plugins: [react(), nodePolyfills()],
|
|
219
|
+
// ... other config
|
|
220
|
+
define: {
|
|
221
|
+
'process.env': {
|
|
222
|
+
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'production'),
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
This will prevent the runtime error and allow the SDK to function correctly.
|
|
229
|
+
|
|
166
230
|
## Want to contribute?
|
|
167
231
|
|
|
168
232
|
Read the [Contributing guide](CONTRIBUTING.md)
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var H=(r,e)=>{for(var o in e)P(r,o,{get:e[o],enumerable:!0})},L=(r,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of B(e))!_.call(r,n)&&n!==o&&P(r,n,{get:()=>e[n],enumerable:!(t=F(e,n))||t.enumerable});return r};var q=r=>L(P({},"__esModule",{value:!0}),r);var M={};H(M,{Client:()=>g,Environment:()=>$,createDepositTxn:()=>D,fetchUserDepositHistory:()=>C,fetchUserUploadHistory:()=>C,getRpcUrl:()=>N,getStorageRenewalCost:()=>I,getUserUploadHistory:()=>C,renewStorageTxn:()=>k,useDeposit:()=>z,useUpload:()=>z});module.exports=q(M);var x=require("@solana/web3.js");var l=typeof window<"u"&&window.location.hostname==="localhost"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",O=86400,j=1e9;var p=require("@solana/web3.js");async function D({file:r,duration:e,payer:o,connection:t,signTransaction:n,userEmail:i}){try{let a=new FormData;r.forEach(s=>a.append("file",s)),a.append("duration",e.toString()),a.append("publicKey",o.toBase58()),i&&a.append("userEmail",i);let d=r.length>1,y,m=await fetch(`${l}/api/solana/deposit`,{method:"POST",body:a});if(!m.ok)throw new Error("Failed to get deposit instructions");let c=await m.json();if(!c.instructions||!c.instructions.length)throw new Error("No instructions from deposit API");let S=await t.getLatestBlockhash("confirmed"),u=c.instructions[0],w=new p.TransactionInstruction({programId:new p.PublicKey(u.programId),keys:u.keys.map(s=>({pubkey:new p.PublicKey(s.pubkey),isSigner:s.isSigner,isWritable:s.isWritable})),data:Buffer.from(u.data,"base64")}),b=new p.Transaction;b.recentBlockhash=S.blockhash,b.feePayer=o,b.add(w);let v=await n(b),R;try{R=await t.sendRawTransaction(v.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"})}catch(s){throw s instanceof p.SendTransactionError?(s.logs??[]).some(A=>A.includes("already in use"))?new Error("This file has already been uploaded. You can find it in your dashboard."):new Error("Transaction failed during simulation. Please try again."):s}let E=await t.confirmTransaction({signature:R,blockhash:S.blockhash,lastValidBlockHeight:S.lastValidBlockHeight},"confirmed");if(E.value.err)throw console.error("Failed to confirm this transaction:",E.value.err),new Error(`Transaction failed: ${JSON.stringify(E.value.err)}`);try{await fetch(`${l}/api/user/update-transaction-hash`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:c.cid,transactionHash:R})})}catch(s){console.warn("Failed to update transaction hash:",s)}c.error&&(y=c.error);let U=new FormData;r.forEach(s=>U.append("file",s));let h;if(d?h=await fetch(`${l}/api/user/upload-files?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:U}):h=await fetch(`${l}/api/user/upload-file?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:U}),!h.ok){let s="Unknown error";try{let T=await h.json();s=T.message||T.error||s}catch{}throw new Error("Deposit API error: "+s)}let f=await h?.json();return{signature:R,success:!0,cid:c.cid,url:f.object.url,message:f.object.message,fileInfo:f.object?{filename:f.object.fileInfo?.filename||"",size:f?.object?.fileInfo?.size||0,uploadedAt:f?.object?.fileInfo?.uploadedAt||"",type:f?.object?.fileInfo?.type||""}:void 0}}catch(a){return console.error(a),a instanceof Error&&(console.error("Error name:",a.name),console.error("Error message:",a.message),console.error("Error stack:",a.stack)),{signature:"",success:!1,cid:"",url:"",message:"",fileInfo:void 0,error:a instanceof Error?a.message:"Unknown error occurred"}}}async function I(r,e){try{let o=await fetch(`${l}/api/user/renewal-cost?cid=${encodeURIComponent(r)}&duration=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let t=await o.json();throw new Error(t.message||"Failed to get storage renewal cost")}return await o.json()}catch(o){return console.error("Failed to get storage renewal cost",o),null}}async function k({cid:r,duration:e,payer:o,connection:t,signTransaction:n}){let i=await fetch(`${l}/api/user/renew-storage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:r,duration:e,publicKey:o.toString()})});if(!i.ok){let u=await i.json().catch(()=>({}));throw new Error(u.message||"Failed to create renewal transaction")}let a=await i.json(),d=new p.Transaction;a.instructions.forEach(u=>{d.add({programId:new p.PublicKey(u.programId),keys:u.keys.map(w=>({pubkey:new p.PublicKey(w.pubkey),isSigner:w.isSigner,isWritable:w.isWritable})),data:Buffer.from(u.data,"base64")})});let{blockhash:y}=await t.getLatestBlockhash();d.recentBlockhash=y,d.feePayer=o;let m=await n(d),c=await t.sendRawTransaction(m.serialize());return await t.confirmTransaction(c,"confirmed"),(await fetch(`${l}/api/user/confirm-renewal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:r,duration:e,transactionHash:c})})).ok||console.error("Failed to confirm renewal"),{success:!0,cid:r,signature:c,url:`https://w3s.link/ipfs/${r}`,message:"Storage renewed successfully"}}async function C(r,e={}){if(!r||typeof r!="string")throw new Error("User address is required and must be a string");let o=e.url||l;try{let t=await fetch(`${o}/api/user/user-upload-history?userAddress=${encodeURIComponent(r)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok){let i=await t.json().catch(()=>({}));throw new Error(i.message||`Failed to fetch upload history: ${t.status} ${t.statusText}`)}let n=await t.json();if(typeof n!="object"||n===null)throw new Error("Invalid response format from server");if(typeof n.userAddress!="string")throw new Error("Invalid userAddress in response");return n}catch(t){throw t instanceof Error?t:new Error("Unknown error occurred while fetching upload history")}}var $=(t=>(t.mainnet="mainnet-beta",t.testnet="testnet",t.devnet="devnet",t))($||{});function N(r){switch(r){case"mainnet-beta":return"https://api.mainnet-beta.solana.com";case"testnet":return"https://api.testnet.solana.com";case"devnet":return"https://api.devnet.solana.com";default:throw new Error(`Unsupported environment: ${r}`)}}var g=class{constructor(e){this.rpcUrl=N(e.environment)}async createDeposit({payer:e,file:o,durationDays:t,signTransaction:n,userEmail:i}){console.log("Creating deposit transaction with environment:",this.rpcUrl);let a=new x.Connection(this.rpcUrl,"confirmed");return await D({file:o,duration:t*O,payer:e,connection:a,signTransaction:n,userEmail:i})}async estimateStorageCost(e,o){let t=e.reduce((m,c)=>m+c.size,0),n=Math.floor(o/86400),i=await fetch(`${l}/api/user/get-quote?size=${t}&duration=${n}`);if(!i.ok)throw new Error("Failed to get storage cost estimate");let{quote:a}=await i.json(),d=a.totalCost;return{sol:d/j,lamports:d}}async getUserUploadHistory(e){return await C(e)}async getStorageRenewalCost(e,o){return await I(e,o)}async renewStorageDuration({cid:e,duration:o,payer:t,signTransaction:n}){let i=new x.Connection(this.rpcUrl,"confirmed");return await k({cid:e,duration:o,payer:t,connection:i,signTransaction:n})}async getSolPrice(){let e=await fetch(`${l}/api/user/sol-price`);if(!e.ok)throw new Error("Couldn't fetch SOL price");return(await e.json()).price}};var z=r=>new g({environment:r||"testnet"});0&&(module.exports={Client,Environment,createDepositTxn,fetchUserDepositHistory,fetchUserUploadHistory,getRpcUrl,getStorageRenewalCost,getUserUploadHistory,renewStorageTxn,useDeposit,useUpload});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/constants.ts","../src/depositHistory.ts","../src/payment.ts","../src/hooks.ts"],"sourcesContent":["export * from \"./client\"\nexport * from \"./types\"\nexport * from \"./payment\"\nexport * from \"./hooks\"\nexport * from \"./depositHistory\"\n","import { Connection, PublicKey } from '@solana/web3.js';\nimport { DAY_TIME_IN_SECONDS } from './constants';\nimport { fetchUserDepositHistory } from './depositHistory';\nimport { createDepositTxn } from './payment';\nimport { CreateDepositArgs, UploadResult } from './types';\n\nexport enum Environment {\n mainnet = 'mainnet-beta',\n testnet = 'testnet',\n devnet = 'devnet',\n}\n\nexport function getRpcUrl(env: Environment): string {\n switch (env) {\n case Environment.mainnet:\n return 'https://api.mainnet-beta.solana.com';\n case Environment.testnet:\n return 'https://api.testnet.solana.com';\n case Environment.devnet:\n return 'https://api.devnet.solana.com';\n default:\n throw new Error(`Unsupported environment: ${env}`);\n }\n}\n\nexport interface ClientOptions {\n /** Solana RPC endpoint to use for chain interactions */\n environment: Environment;\n}\n\nexport interface DepositParams\n extends Pick<CreateDepositArgs, 'signTransaction' | 'userEmail'> {\n /** Wallet public key of the payer */\n payer: PublicKey;\n /** File(s) to be stored */\n file: File[];\n /** Duration in days to store the data */\n durationDays: number;\n}\n\n/**\n * Solana Storage Client — simplified (no fee estimation)\n */\nexport class Client {\n private rpcUrl: string;\n\n constructor(options: ClientOptions) {\n this.rpcUrl = getRpcUrl(options.environment);\n }\n\n /**\n * Creates a deposit transaction ready to be signed & sent by user's wallet.\n *\n * @param {Object} params\n * @param {PublicKey} params.payer - The public key (wallet address) of the connected wallet.\n * @param {File} params.file - The file to be uploaded.\n * @param {number} params.durationDays - How long (in days) the file should be stored.\n * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction -\n * A callback function to authorize the transaction via the Solana wallet library.\n *\n * @example\n * const { publicKey, signTransaction } = useSolanaWallet();\n * const result = await createDeposit({\n * payer: publicKey,\n * file,\n * durationDays: 30,\n * signTransaction,\n * });\n *\n * @returns {Promise<UploadResult>} The upload result after transaction is processed.\n */\n async createDeposit({\n payer,\n file,\n durationDays,\n signTransaction,\n userEmail,\n }: DepositParams): Promise<UploadResult> {\n console.log('Creating deposit transaction with environment:', this.rpcUrl);\n const connection = new Connection(this.rpcUrl, 'confirmed');\n\n return await createDepositTxn({\n file,\n duration: durationDays * DAY_TIME_IN_SECONDS,\n payer,\n connection,\n signTransaction,\n userEmail,\n });\n }\n\n /**\n * estimates the cost for a file based on the amount of days it should be stored for\n * @param {File} file - a file to be uploaded\n * @param {number} duration - how long (in seconds) the file should be stored for\n */\n estimateStorageCost = (file: File[], duration: number) => {\n const ratePerBytePerDay = 1000; // this would be obtained from the program config later\n const fileSizeInBytes = file.reduce((acc, f) => acc + f.size, 0);\n const totalLamports = fileSizeInBytes * duration * ratePerBytePerDay;\n const totalSOL = totalLamports / 1_000_000_000;\n\n return {\n sol: totalSOL,\n lamports: totalLamports,\n };\n };\n\n async getUserUploadHistory(userAddress: string) {\n const response = await fetchUserDepositHistory(userAddress);\n return response;\n }\n}\n","const { NODE_ENV } = process.env;\n\nexport const ENDPOINT =\n NODE_ENV === 'development'\n ? 'http://localhost:5040'\n : 'https://storacha-solana-sdk-bshc.onrender.com';\n\nexport const DAY_TIME_IN_SECONDS = 86400;\n","import { ENDPOINT } from './constants';\nimport { DepositHistoryResponse, ServerOptions } from './types';\n\n/**\n * Fetches the deposit history for a given user address from the backend\n *\n * @param userAddress - The wallet address of the user to fetch deposit history for\n * @param options - Optional server configuration\n * @returns Promise<DepositHistoryResponse> - The user's deposit history\n *\n * @example\n * ```typescript\n * const history = await fetchUserDepositHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');\n * console.log('User deposit history:', history.userHistory);\n * ```\n *\n * @throws {Error} When the user address is invalid or the request fails\n */\nexport async function fetchUserDepositHistory(\n userAddress: string,\n options: ServerOptions = {}\n): Promise<DepositHistoryResponse> {\n // Validate user address\n if (!userAddress || typeof userAddress !== 'string') {\n throw new Error('User address is required and must be a string');\n }\n\n // Use ENDPOINT constant, or allow override via options\n const baseUrl = options.url || ENDPOINT;\n\n try {\n const response = await fetch(\n `${baseUrl}/api/user/user-upload-history?userAddress=${encodeURIComponent(userAddress)}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.message ||\n `Failed to fetch deposit history: ${response.status} ${response.statusText}`\n );\n }\n\n const data: DepositHistoryResponse = await response.json();\n\n // Validate response structure\n if (typeof data !== 'object' || data === null) {\n throw new Error('Invalid response format from server');\n }\n\n if (typeof data.userAddress !== 'string') {\n throw new Error('Invalid userAddress in response');\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error) {\n throw error;\n }\n throw new Error('Unknown error occurred while fetching deposit history');\n }\n}\n","import { Signature } from '@solana/kit';\nimport {\n PublicKey,\n Transaction,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { ENDPOINT } from './constants';\nimport { CreateDepositArgs, DepositResult, UploadResult } from './types';\n\n/**\n * Calls the deposit API for on-chain storage and returns a Transaction\n * which must be signed and sent externally by the user.\n *\n * @param params - {\n * cid: string;\n * file: File;\n * duration: number;\n * payer: PublicKey;\n * connection: Connection;\n * }\n * @returns Transaction\n */\nexport async function createDepositTxn({\n file,\n duration,\n payer,\n connection,\n signTransaction,\n userEmail,\n}: CreateDepositArgs): Promise<UploadResult> {\n try {\n const formData = new FormData();\n file.forEach((f) => formData.append('file', f));\n formData.append('duration', duration.toString());\n formData.append('publicKey', payer.toBase58());\n if (userEmail) {\n formData.append('userEmail', userEmail);\n }\n\n const isMultipleFiles = file.length > 1;\n\n let uploadErr;\n\n const depositReq = await fetch(`${ENDPOINT}/api/solana/deposit`, {\n method: 'POST',\n body: formData,\n });\n if (!depositReq.ok) throw new Error('Failed to get deposit instructions');\n\n const depositRes: DepositResult = await depositReq.json();\n if (!depositRes.instructions || !depositRes.instructions.length)\n throw new Error('No instructions from deposit API');\n\n const latestBlockhash = await connection.getLatestBlockhash('confirmed');\n const instructions = depositRes.instructions[0];\n\n const depositInstruction = new TransactionInstruction({\n programId: new PublicKey(instructions.programId),\n keys: instructions.keys.map((k) => ({\n pubkey: new PublicKey(k.pubkey),\n isSigner: k.isSigner,\n isWritable: k.isWritable,\n })),\n data: Buffer.from(instructions.data, 'base64'),\n });\n\n const tx = new Transaction();\n tx.recentBlockhash = latestBlockhash.blockhash;\n tx.feePayer = payer;\n tx.add(depositInstruction);\n\n const signedTx = await signTransaction(tx);\n const signature = await connection.sendRawTransaction(\n signedTx.serialize(),\n {\n skipPreflight: false, // not sure we should be disabling this verification step\n preflightCommitment: 'confirmed',\n }\n );\n const confirmation = await connection.confirmTransaction(\n {\n signature,\n blockhash: latestBlockhash.blockhash,\n lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,\n },\n 'confirmed'\n );\n\n if (confirmation.value.err) {\n console.error(\n 'Failed to confirm this transaction:',\n confirmation.value.err\n );\n throw new Error(\n `Transaction failed: ${JSON.stringify(confirmation.value.err)}`\n );\n }\n\n try {\n await fetch(`${ENDPOINT}/api/user/update-transaction-hash`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n cid: depositRes.cid,\n transactionHash: signature,\n }),\n });\n } catch (err) {\n console.warn('Failed to update transaction hash:', err);\n }\n\n if (depositRes.error) {\n uploadErr = depositRes.error;\n }\n\n const uploadForm = new FormData();\n file.forEach((f) => uploadForm.append('file', f));\n\n let fileUploadReq;\n // calls the upload functionality on our server with the file when deposit is succesful\n if (isMultipleFiles) {\n fileUploadReq = await fetch(\n `${ENDPOINT}/api/user/upload-files?cid=${encodeURIComponent(depositRes.cid)}`,\n {\n method: 'POST',\n body: uploadForm,\n }\n );\n } else {\n fileUploadReq = await fetch(\n `${ENDPOINT}/api/user/upload-file?cid=${encodeURIComponent(depositRes.cid)}`,\n {\n method: 'POST',\n body: uploadForm,\n }\n );\n }\n\n if (!fileUploadReq.ok) {\n let err = 'Unknown error';\n try {\n const data: DepositResult = await fileUploadReq.json();\n err = data.message || data.error || err;\n } catch {}\n throw new Error('Deposit API error: ' + err);\n }\n\n const fileUploadRes: Pick<DepositResult, 'object' | 'cid' | 'message'> =\n await fileUploadReq?.json();\n\n return {\n signature: signature as Signature,\n success: true,\n cid: depositRes.cid,\n url: fileUploadRes.object.url,\n message: fileUploadRes.object.message,\n fileInfo: fileUploadRes.object\n ? {\n filename: fileUploadRes.object.fileInfo?.filename || '',\n size: fileUploadRes?.object?.fileInfo?.size || 0,\n uploadedAt: fileUploadRes?.object?.fileInfo?.uploadedAt || '',\n type: fileUploadRes?.object?.fileInfo?.type || '',\n }\n : undefined,\n };\n } catch (error) {\n console.error(error);\n if (error instanceof Error) {\n console.error('Error name:', error.name);\n console.error('Error message:', error.message);\n console.error('Error stack:', error.stack);\n }\n\n return {\n signature: '' as Signature,\n success: false,\n cid: '',\n url: '',\n message: '',\n fileInfo: undefined,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n}\n","import { Client, ClientOptions } from './client';\n\nexport const useDeposit = (environment: ClientOptions['environment']) => {\n const client = new Client({ environment: environment || 'testnet' });\n return client;\n};\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,4BAAAC,EAAA,cAAAC,EAAA,eAAAC,IAAA,eAAAC,EAAAR,GCAA,IAAAS,EAAsC,2BCAtC,GAAM,CAAE,SAAAC,CAAS,EAAI,QAAQ,IAEhBC,EACXD,IAAa,cACT,wBACA,gDAEOE,EAAsB,MCWnC,eAA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AAA,QAAU,eACVA,EAAA,QAAU,UACVA,EAAA,OAAS,SAHCA,OAAA,IAML,SAASC,EAAUC,EAA0B,CAClD,OAAQA,EAAK,CACX,IAAK,eACH,MAAO,sCACT,IAAK,UACH,MAAO,iCACT,IAAK,SACH,MAAO,gCACT,QACE,MAAM,IAAI,MAAM,4BAA4BA,CAAG,EAAE,CACrD,CACF,CAoBO,IAAMC,EAAN,KAAa,CAGlB,YAAYC,EAAwB,CAkDpC,yBAAsB,CAACC,EAAcC,IAAqB,CAGxD,IAAMC,EADkBF,EAAK,OAAO,CAACG,EAAKC,IAAMD,EAAMC,EAAE,KAAM,CAAC,EACvBH,EAAW,IAGnD,MAAO,CACL,IAHeC,EAAgB,IAI/B,SAAUA,CACZ,CACF,EA3DE,KAAK,OAASN,EAAUG,EAAQ,WAAW,CAC7C,CAuBA,MAAM,cAAc,CAClB,MAAAM,EACA,KAAAL,EACA,aAAAM,EACA,gBAAAC,EACA,UAAAC,CACF,EAAyC,CACvC,QAAQ,IAAI,iDAAkD,KAAK,MAAM,EACzE,IAAMC,EAAa,IAAI,aAAW,KAAK,OAAQ,WAAW,EAE1D,OAAO,MAAMC,EAAiB,CAC5B,KAAAV,EACA,SAAUM,EAAeK,EACzB,MAAAN,EACA,WAAAI,EACA,gBAAAF,EACA,UAAAC,CACF,CAAC,CACH,CAmBA,MAAM,qBAAqBI,EAAqB,CAE9C,OADiB,MAAMC,EAAwBD,CAAW,CAE5D,CACF,EI9GO,IAAME,EAAcC,GACV,IAAIC,EAAO,CAAE,YAAaD,GAAe,SAAU,CAAC","names":["index_exports","__export","Client","Environment","createDepositTxn","fetchUserDepositHistory","getRpcUrl","useDeposit","__toCommonJS","import_web3","NODE_ENV","ENDPOINT","DAY_TIME_IN_SECONDS","fetchUserDepositHistory","userAddress","options","baseUrl","ENDPOINT","response","errorData","data","error","import_web3","createDepositTxn","file","duration","payer","connection","signTransaction","userEmail","formData","f","isMultipleFiles","uploadErr","depositReq","ENDPOINT","depositRes","latestBlockhash","instructions","depositInstruction","k","tx","signedTx","signature","confirmation","err","uploadForm","fileUploadReq","data","fileUploadRes","error","Environment","getRpcUrl","env","Client","options","file","duration","totalLamports","acc","f","payer","durationDays","signTransaction","userEmail","connection","createDepositTxn","DAY_TIME_IN_SECONDS","userAddress","fetchUserDepositHistory","useDeposit","environment","Client"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/constants.ts","../src/payment.ts","../src/upload-history.ts","../src/hooks.ts"],"sourcesContent":["export * from './client';\nexport * from './hooks';\nexport * from './payment';\nexport * from './types';\nexport * from './upload-history';\n","import { Connection, PublicKey } from '@solana/web3.js';\nimport {\n DAY_TIME_IN_SECONDS,\n ENDPOINT,\n ONE_BILLION_LAMPORTS,\n} from './constants';\nimport {\n createDepositTxn,\n getStorageRenewalCost,\n renewStorageTxn,\n} from './payment';\nimport {\n CreateDepositArgs,\n StorageRenewalCost,\n StorageRenewalParams,\n UploadResult,\n} from './types';\nimport { getUserUploadHistory } from './upload-history';\n\nexport enum Environment {\n mainnet = 'mainnet-beta',\n testnet = 'testnet',\n devnet = 'devnet',\n}\n\nexport function getRpcUrl(env: Environment): string {\n switch (env) {\n case Environment.mainnet:\n return 'https://api.mainnet-beta.solana.com';\n case Environment.testnet:\n return 'https://api.testnet.solana.com';\n case Environment.devnet:\n return 'https://api.devnet.solana.com';\n default:\n throw new Error(`Unsupported environment: ${env}`);\n }\n}\n\nexport interface ClientOptions {\n /** Solana RPC endpoint to use for chain interactions */\n environment: Environment;\n}\n\nexport interface UploadParams extends Pick<\n CreateDepositArgs,\n 'signTransaction' | 'userEmail'\n> {\n /** Wallet public key of the payer */\n payer: PublicKey;\n /** File(s) to be stored */\n file: File[];\n /** Duration in days to store the data */\n durationDays: number;\n}\n\n/**\n * @deprecated Use {@link UploadParams} instead.\n */\nexport type DepositParams = UploadParams;\n\n/**\n * Solana Storage Client — simplified (no fee estimation)\n */\nexport class Client {\n private rpcUrl: string;\n\n constructor(options: ClientOptions) {\n this.rpcUrl = getRpcUrl(options.environment);\n }\n\n /**\n * Creates a deposit transaction ready to be signed & sent by user's wallet.\n *\n * @param {Object} params\n * @param {PublicKey} params.payer - The public key (wallet address) of the connected wallet.\n * @param {File} params.file - The file to be uploaded.\n * @param {number} params.durationDays - How long (in days) the file should be stored.\n * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction -\n * A callback function to authorize the transaction via the Solana wallet library.\n *\n * @example\n * const { publicKey, signTransaction } = useSolanaWallet();\n * const result = await createDeposit({\n * payer: publicKey,\n * file,\n * durationDays: 30,\n * signTransaction,\n * });\n *\n * @returns {Promise<UploadResult>} The upload result after transaction is processed.\n */\n async createDeposit({\n payer,\n file,\n durationDays,\n signTransaction,\n userEmail,\n }: UploadParams): Promise<UploadResult> {\n console.log('Creating deposit transaction with environment:', this.rpcUrl);\n const connection = new Connection(this.rpcUrl, 'confirmed');\n\n return await createDepositTxn({\n file,\n duration: durationDays * DAY_TIME_IN_SECONDS,\n payer,\n connection,\n signTransaction,\n userEmail,\n });\n }\n\n /**\n * estimates the cost for a file based on the amount of days it should be stored for\n * @param {File} file - a file to be uploaded\n * @param {number} duration - how long (in seconds) the file should be stored for\n */\n async estimateStorageCost(file: File[], duration: number) {\n const fileSizeInBytes = file.reduce((acc, f) => acc + f.size, 0);\n const durationInDays = Math.floor(duration / 86400); // convert seconds to day\n\n const response = await fetch(\n `${ENDPOINT}/api/user/get-quote?size=${fileSizeInBytes}&duration=${durationInDays}`\n );\n\n if (!response.ok) throw new Error('Failed to get storage cost estimate');\n\n const { quote } = await response.json();\n const totalLamports = quote.totalCost;\n const totalSOL = totalLamports / ONE_BILLION_LAMPORTS;\n\n return {\n sol: totalSOL,\n lamports: totalLamports,\n };\n }\n\n async getUserUploadHistory(userAddress: string) {\n const response = await getUserUploadHistory(userAddress);\n return response;\n }\n\n /**\n * Get cost estimate for renewing storage duration\n *\n * @param {string} cid - Content identifier of the file to renew\n * @param {number} duration - Number of additional days to extend storage\n *\n * @example\n * const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);\n * console.log(`Renewal cost: ${quote.costInSOL} SOL`);\n *\n * @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details\n */\n async getStorageRenewalCost(\n cid: string,\n duration: number\n ): Promise<StorageRenewalCost | null> {\n return await getStorageRenewalCost(cid, duration);\n }\n\n /**\n * Renew storage for an existing deposit\n *\n * @param {Object} params\n * @param {string} params.cid - Content identifier of the file to renew\n * @param {number} params.duration - Number of additional days to extend storage\n * @param {PublicKey} params.payer - Wallet public key paying for the renewal\n * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback\n *\n * @example\n * const { publicKey, signTransaction } = useSolanaWallet();\n * const result = await client.renewStorage({\n * cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',\n * duration: 30,\n * payer: publicKey,\n * signTransaction,\n * });\n *\n * @returns {Promise<UploadResult>} Result of the renewal transaction\n */\n async renewStorageDuration({\n cid,\n duration,\n payer,\n signTransaction,\n }: StorageRenewalParams): Promise<UploadResult> {\n const connection = new Connection(this.rpcUrl, 'confirmed');\n\n return await renewStorageTxn({\n cid,\n duration,\n payer,\n connection,\n signTransaction,\n });\n }\n\n /**\n * Gets the current SOL/USD price\n *\n * @example\n * const { price } = await client.getSolPrice();\n * console.log(`SOL price: $${price}`);\n *\n * @returns {Promise<{ price: number }>} Current SOL price in USD\n */\n async getSolPrice(): Promise<{ price: number }> {\n const request = await fetch(`${ENDPOINT}/api/user/sol-price`);\n if (!request.ok) throw new Error(\"Couldn't fetch SOL price\");\n const data = await request.json();\n return data.price;\n }\n}\n","export const ENDPOINT =\n typeof window !== 'undefined' && window.location.hostname === 'localhost'\n ? 'http://localhost:5040'\n : 'https://storacha-solana-sdk-bshc.onrender.com';\n\nexport const DAY_TIME_IN_SECONDS = 86400;\n\n/** 1 SOL in Lamports */\nexport const ONE_BILLION_LAMPORTS = 1_000_000_000;\n","import { Signature } from '@solana/kit';\nimport {\n PublicKey,\n SendTransactionError,\n Transaction,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { ENDPOINT } from './constants';\nimport {\n CreateDepositArgs,\n DepositResult,\n RenewStorageDurationArgs,\n StorageRenewalCost,\n StorageRenewalResult,\n UploadResult,\n} from './types';\n\n/**\n * Calls the deposit API for on-chain storage and returns a Transaction\n * which must be signed and sent externally by the user.\n *\n * @param params - {\n * cid: string;\n * file: File;\n * duration: number;\n * payer: PublicKey;\n * connection: Connection;\n * }\n * @returns Transaction\n */\nexport async function createDepositTxn({\n file,\n duration,\n payer,\n connection,\n signTransaction,\n userEmail,\n}: CreateDepositArgs): Promise<UploadResult> {\n try {\n const formData = new FormData();\n file.forEach((f) => formData.append('file', f));\n formData.append('duration', duration.toString());\n formData.append('publicKey', payer.toBase58());\n if (userEmail) {\n formData.append('userEmail', userEmail);\n }\n\n const isMultipleFiles = file.length > 1;\n\n let uploadErr;\n\n const depositReq = await fetch(`${ENDPOINT}/api/solana/deposit`, {\n method: 'POST',\n body: formData,\n });\n if (!depositReq.ok) throw new Error('Failed to get deposit instructions');\n\n const depositRes: DepositResult = await depositReq.json();\n if (!depositRes.instructions || !depositRes.instructions.length)\n throw new Error('No instructions from deposit API');\n\n const latestBlockhash = await connection.getLatestBlockhash('confirmed');\n const instructions = depositRes.instructions[0];\n\n const depositInstruction = new TransactionInstruction({\n programId: new PublicKey(instructions.programId),\n keys: instructions.keys.map((k) => ({\n pubkey: new PublicKey(k.pubkey),\n isSigner: k.isSigner,\n isWritable: k.isWritable,\n })),\n data: Buffer.from(instructions.data, 'base64'),\n });\n\n const tx = new Transaction();\n tx.recentBlockhash = latestBlockhash.blockhash;\n tx.feePayer = payer;\n tx.add(depositInstruction);\n\n const signedTx = await signTransaction(tx);\n let signature: string;\n\n try {\n signature = await connection.sendRawTransaction(signedTx.serialize(), {\n skipPreflight: false, // not sure we should be disabling this verification step\n preflightCommitment: 'confirmed',\n });\n } catch (err) {\n if (err instanceof SendTransactionError) {\n const logs = err.logs ?? [];\n\n const isDuplicateUpload = logs.some((log) =>\n log.includes('already in use')\n );\n\n if (isDuplicateUpload) {\n throw new Error(\n 'This file has already been uploaded. You can find it in your dashboard.'\n );\n }\n\n throw new Error(\n 'Transaction failed during simulation. Please try again.'\n );\n }\n\n throw err;\n }\n const confirmation = await connection.confirmTransaction(\n {\n signature,\n blockhash: latestBlockhash.blockhash,\n lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,\n },\n 'confirmed'\n );\n\n if (confirmation.value.err) {\n console.error(\n 'Failed to confirm this transaction:',\n confirmation.value.err\n );\n throw new Error(\n `Transaction failed: ${JSON.stringify(confirmation.value.err)}`\n );\n }\n\n try {\n await fetch(`${ENDPOINT}/api/user/update-transaction-hash`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n cid: depositRes.cid,\n transactionHash: signature,\n }),\n });\n } catch (err) {\n console.warn('Failed to update transaction hash:', err);\n }\n\n if (depositRes.error) {\n uploadErr = depositRes.error;\n }\n\n const uploadForm = new FormData();\n file.forEach((f) => uploadForm.append('file', f));\n\n let fileUploadReq;\n // calls the upload functionality on our server with the file when deposit is successful\n if (isMultipleFiles) {\n fileUploadReq = await fetch(\n `${ENDPOINT}/api/user/upload-files?cid=${encodeURIComponent(\n depositRes.cid\n )}`,\n {\n method: 'POST',\n body: uploadForm,\n }\n );\n } else {\n fileUploadReq = await fetch(\n `${ENDPOINT}/api/user/upload-file?cid=${encodeURIComponent(\n depositRes.cid\n )}`,\n {\n method: 'POST',\n body: uploadForm,\n }\n );\n }\n\n if (!fileUploadReq.ok) {\n let err = 'Unknown error';\n try {\n const data: DepositResult = await fileUploadReq.json();\n err = data.message || data.error || err;\n } catch {}\n throw new Error('Deposit API error: ' + err);\n }\n\n const fileUploadRes: Pick<DepositResult, 'object' | 'cid' | 'message'> =\n await fileUploadReq?.json();\n\n return {\n signature: signature as Signature,\n success: true,\n cid: depositRes.cid,\n url: fileUploadRes.object.url,\n message: fileUploadRes.object.message,\n fileInfo: fileUploadRes.object\n ? {\n filename: fileUploadRes.object.fileInfo?.filename || '',\n size: fileUploadRes?.object?.fileInfo?.size || 0,\n uploadedAt: fileUploadRes?.object?.fileInfo?.uploadedAt || '',\n type: fileUploadRes?.object?.fileInfo?.type || '',\n }\n : undefined,\n };\n } catch (error) {\n console.error(error);\n if (error instanceof Error) {\n console.error('Error name:', error.name);\n console.error('Error message:', error.message);\n console.error('Error stack:', error.stack);\n }\n\n return {\n signature: '' as Signature,\n success: false,\n cid: '',\n url: '',\n message: '',\n fileInfo: undefined,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n}\n\n/**\n * Get cost estimate for renewing storage duration\n *\n * @param {string} cid - Content identifier of the uploaded data to renew\n * @param {number} duration - Number of additional days to extend storage\n *\n * @example\n * const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);\n * console.log(`Renewal cost: ${quote.costInSOL} SOL`);\n *\n * @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details\n */\nexport async function getStorageRenewalCost(\n cid: string,\n duration: number\n): Promise<StorageRenewalCost | null> {\n try {\n const request = await fetch(\n `${ENDPOINT}/api/user/renewal-cost?cid=${encodeURIComponent(\n cid\n )}&duration=${duration}`,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n }\n );\n\n if (!request.ok) {\n const response = await request.json();\n throw new Error(response.message || 'Failed to get storage renewal cost');\n }\n\n return await request.json();\n } catch (error) {\n console.error('Failed to get storage renewal cost', error);\n return null;\n }\n}\n\n/**\n * Renew storage for an existing deposit\n *\n * @param {Object} params\n * @param {string} params.cid - Content identifier of the uploaded data to renew\n * @param {number} params.duration - Number of additional days to extend storage\n * @param {PublicKey} params.payer - Wallet public key paying for the renewal\n * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback\n *\n * @example\n * const { publicKey, signTransaction } = useSolanaWallet();\n * const result = await client.renewStorage({\n * cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',\n * additionalDays: 30,\n * payer: publicKey,\n * signTransaction,\n * });\n *\n * @returns {Promise<UploadResult>} Result of the renewal transaction\n */\nexport async function renewStorageTxn({\n cid,\n duration,\n payer,\n connection,\n signTransaction,\n}: RenewStorageDurationArgs): Promise<UploadResult> {\n const renewalTransactionIx = await fetch(\n `${ENDPOINT}/api/user/renew-storage`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n cid,\n duration,\n publicKey: payer.toString(),\n }),\n }\n );\n\n if (!renewalTransactionIx.ok) {\n const errorData = await renewalTransactionIx.json().catch(() => ({}));\n throw new Error(\n errorData.message || 'Failed to create renewal transaction'\n );\n }\n\n const renewalData: StorageRenewalResult = await renewalTransactionIx.json();\n const transaction = new Transaction();\n\n renewalData.instructions.forEach((ix) => {\n transaction.add({\n programId: new PublicKey(ix.programId),\n keys: ix.keys.map((key) => ({\n pubkey: new PublicKey(key.pubkey),\n isSigner: key.isSigner,\n isWritable: key.isWritable,\n })),\n data: Buffer.from(ix.data, 'base64'),\n });\n });\n\n const { blockhash } = await connection.getLatestBlockhash();\n transaction.recentBlockhash = blockhash;\n transaction.feePayer = payer;\n\n const signed = await signTransaction(transaction);\n const signature = await connection.sendRawTransaction(signed.serialize());\n await connection.confirmTransaction(signature, 'confirmed');\n\n const confirmRenewalTx = await fetch(`${ENDPOINT}/api/user/confirm-renewal`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n cid,\n duration,\n transactionHash: signature,\n }),\n });\n\n if (!confirmRenewalTx.ok) {\n console.error('Failed to confirm renewal');\n }\n\n return {\n success: true,\n cid,\n signature: signature as Signature,\n url: `https://w3s.link/ipfs/${cid}`,\n message: 'Storage renewed successfully',\n };\n}\n","import { ENDPOINT } from './constants';\nimport { ServerOptions, UploadHistoryResponse } from './types';\n\n/**\n * Get the upload history for a given user address from the server\n *\n * @param userAddress - The wallet address of the user to fetch upload history for\n * @param options - Optional server configuration\n * @returns Promise<UploadHistoryResponse> - The user's upload history\n *\n * @example\n * ```typescript\n * const history = await getUserUploadHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');\n * console.log('User upload history:', history.userHistory);\n * ```\n *\n * @throws {Error} When the user address is invalid or the request fails\n */\nexport async function getUserUploadHistory(\n userAddress: string,\n options: ServerOptions = {}\n): Promise<UploadHistoryResponse> {\n // Validate user address\n if (!userAddress || typeof userAddress !== 'string') {\n throw new Error('User address is required and must be a string');\n }\n\n // Use ENDPOINT constant, or allow override via options\n const baseUrl = options.url || ENDPOINT;\n\n try {\n const response = await fetch(\n `${baseUrl}/api/user/user-upload-history?userAddress=${encodeURIComponent(userAddress)}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new Error(\n errorData.message ||\n `Failed to fetch upload history: ${response.status} ${response.statusText}`\n );\n }\n\n const data: UploadHistoryResponse = await response.json();\n\n // Validate response structure\n if (typeof data !== 'object' || data === null) {\n throw new Error('Invalid response format from server');\n }\n\n if (typeof data.userAddress !== 'string') {\n throw new Error('Invalid userAddress in response');\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error) {\n throw error;\n }\n throw new Error('Unknown error occurred while fetching upload history');\n }\n}\n\n/**\n * @deprecated Use getUserUploadHistory instead\n */\nexport { getUserUploadHistory as fetchUserUploadHistory };\n\n/**\n * @deprecated Use getUserUploadHistory instead\n */\nexport { getUserUploadHistory as fetchUserDepositHistory };\n","import { Client, ClientOptions } from './client';\n\nexport const useUpload = (environment: ClientOptions['environment']) => {\n const client = new Client({ environment: environment || 'testnet' });\n return client;\n};\n\n/**\n * @deprecated Use {@link useUpload} instead.\n */\n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,EAE1D,OAAO,MAAMiB,EAAgB,CAC3B,IAAAF,EACA,SAAAZ,EACA,MAAAR,EACA,WAAAK,EACA,gBAAAF,CACF,CAAC,CACH,CAWA,MAAM,aAA0C,CAC9C,IAAMoB,EAAU,MAAM,MAAM,GAAGT,CAAQ,qBAAqB,EAC5D,GAAI,CAACS,EAAQ,GAAI,MAAM,IAAI,MAAM,0BAA0B,EAE3D,OADa,MAAMA,EAAQ,KAAK,GACpB,KACd,CACF,EIlNO,IAAMC,EAAaC,GACT,IAAIC,EAAO,CAAE,YAAaD,GAAe,SAAU,CAAC","names":["index_exports","__export","Client","Environment","createDepositTxn","getUserUploadHistory","getRpcUrl","getStorageRenewalCost","renewStorageTxn","useUpload","__toCommonJS","import_web3","ENDPOINT","DAY_TIME_IN_SECONDS","ONE_BILLION_LAMPORTS","import_web3","createDepositTxn","file","duration","payer","connection","signTransaction","userEmail","formData","f","isMultipleFiles","uploadErr","depositReq","ENDPOINT","depositRes","latestBlockhash","instructions","depositInstruction","k","tx","signedTx","signature","err","log","confirmation","uploadForm","fileUploadReq","data","fileUploadRes","error","getStorageRenewalCost","cid","request","response","renewStorageTxn","renewalTransactionIx","errorData","renewalData","transaction","ix","key","blockhash","signed","getUserUploadHistory","userAddress","options","baseUrl","ENDPOINT","response","errorData","data","error","Environment","getRpcUrl","env","Client","options","payer","file","durationDays","signTransaction","userEmail","connection","createDepositTxn","DAY_TIME_IN_SECONDS","duration","fileSizeInBytes","acc","f","durationInDays","response","ENDPOINT","quote","totalLamports","ONE_BILLION_LAMPORTS","userAddress","getUserUploadHistory","cid","getStorageRenewalCost","renewStorageTxn","request","useUpload","environment","Client"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Address, Signature } from '@solana/kit';
|
|
2
|
-
import { PublicKey, Connection, Transaction } from '@solana/web3.js';
|
|
2
|
+
import { PublicKey, Connection, Transaction as Transaction$1 } from '@solana/web3.js';
|
|
3
3
|
|
|
4
4
|
interface ServerOptions {
|
|
5
|
-
/** URL pointing to the
|
|
5
|
+
/** URL pointing to the server (mostly Storacha's) */
|
|
6
6
|
url?: string;
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
@@ -116,14 +116,49 @@ interface CreateDepositArgs extends Omit<OnChainDeposit, 'depositAmount' | 'depo
|
|
|
116
116
|
* const {publickKey, signTransaction} = useSolanaWallet()
|
|
117
117
|
* const signTransaction = await signTransaction(tx)
|
|
118
118
|
* */
|
|
119
|
-
signTransaction: (tx: Transaction) => Promise<Transaction>;
|
|
119
|
+
signTransaction: (tx: Transaction$1) => Promise<Transaction$1>;
|
|
120
120
|
/** Optional user email for expiration notifications */
|
|
121
121
|
userEmail?: string;
|
|
122
122
|
}
|
|
123
|
+
/** Arguments for renewing storage duration */
|
|
124
|
+
interface StorageRenewalParams extends Pick<CreateDepositArgs, 'payer' | 'signTransaction'> {
|
|
125
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
126
|
+
cid: string;
|
|
127
|
+
/** Duration in days to extend storage */
|
|
128
|
+
duration: number;
|
|
129
|
+
}
|
|
130
|
+
/** Internal arguments for renewStorageTxn */
|
|
131
|
+
interface RenewStorageDurationArgs extends Pick<CreateDepositArgs, 'payer' | 'signTransaction' | 'connection'> {
|
|
132
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
133
|
+
cid: string;
|
|
134
|
+
/** Duration in days to extend storage */
|
|
135
|
+
duration: number;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Transaction record for an upload (initial deposit or renewal)
|
|
139
|
+
*/
|
|
140
|
+
interface Transaction {
|
|
141
|
+
/** Unique identifier for the transaction */
|
|
142
|
+
id: number;
|
|
143
|
+
/** ID of the associated deposit */
|
|
144
|
+
depositId: number;
|
|
145
|
+
/** Content identifier of the upload */
|
|
146
|
+
contentCid: string;
|
|
147
|
+
/** Solana transaction hash */
|
|
148
|
+
transactionHash: string;
|
|
149
|
+
/** Type of transaction: 'initial_deposit' | 'renewal' */
|
|
150
|
+
transactionType: string;
|
|
151
|
+
/** Amount paid in lamports */
|
|
152
|
+
amountInLamports: number;
|
|
153
|
+
/** Duration in days purchased */
|
|
154
|
+
durationDays: number;
|
|
155
|
+
/** Timestamp when the transaction was created */
|
|
156
|
+
createdAt: string;
|
|
157
|
+
}
|
|
123
158
|
/**
|
|
124
|
-
* Individual
|
|
159
|
+
* Individual upload history entry from the server
|
|
125
160
|
*/
|
|
126
|
-
interface
|
|
161
|
+
interface UploadHistory {
|
|
127
162
|
/** Unique identifier for the deposit */
|
|
128
163
|
id: number;
|
|
129
164
|
/** User's wallet address (deposit key) */
|
|
@@ -156,16 +191,78 @@ interface DepositHistoryEntry {
|
|
|
156
191
|
deletionStatus?: string;
|
|
157
192
|
/** Timestamp when warning email was sent */
|
|
158
193
|
warningSentAt?: string;
|
|
194
|
+
/** Optional array of all transactions for this upload */
|
|
195
|
+
transactions?: Transaction[];
|
|
159
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* @deprecated Use UploadHistory instead
|
|
199
|
+
*/
|
|
200
|
+
type DepositHistoryEntry = UploadHistory;
|
|
160
201
|
/**
|
|
161
202
|
* Response from the getUserUploadHistory endpoint
|
|
162
203
|
*/
|
|
163
|
-
interface
|
|
164
|
-
/** Array of
|
|
165
|
-
userHistory:
|
|
204
|
+
interface UploadHistoryResponse {
|
|
205
|
+
/** Array of upload history entries */
|
|
206
|
+
userHistory: UploadHistory[] | null;
|
|
166
207
|
/** The user address that was queried */
|
|
167
208
|
userAddress: string;
|
|
168
209
|
}
|
|
210
|
+
/**
|
|
211
|
+
* @deprecated Use UploadHistoryResponse instead
|
|
212
|
+
*/
|
|
213
|
+
type DepositHistoryResponse = UploadHistoryResponse;
|
|
214
|
+
/**
|
|
215
|
+
* Storage renewal cost estimation
|
|
216
|
+
*/
|
|
217
|
+
type StorageRenewalCost = {
|
|
218
|
+
/** New expiration date after renewal */
|
|
219
|
+
newExpirationDate: string;
|
|
220
|
+
/** Current expiration date before renewal */
|
|
221
|
+
currentExpirationDate: string;
|
|
222
|
+
/** Number of additional days being added */
|
|
223
|
+
additionalDays: string;
|
|
224
|
+
/** Cost of renewal in lamports */
|
|
225
|
+
costInLamports: number;
|
|
226
|
+
/** Cost of renewal in SOL */
|
|
227
|
+
costInSOL: number;
|
|
228
|
+
/** Details about the file being renewed */
|
|
229
|
+
fileDetails: {
|
|
230
|
+
/** Content identifier */
|
|
231
|
+
cid: string;
|
|
232
|
+
/** Name of the file */
|
|
233
|
+
fileName: string;
|
|
234
|
+
/** Size of the file in bytes */
|
|
235
|
+
fileSize: number;
|
|
236
|
+
};
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Storage renewal transaction result
|
|
240
|
+
*/
|
|
241
|
+
type StorageRenewalResult = {
|
|
242
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
243
|
+
cid: string;
|
|
244
|
+
/** Status message about the renewal */
|
|
245
|
+
message: string;
|
|
246
|
+
/** Transaction instructions for the user to sign */
|
|
247
|
+
instructions: Array<{
|
|
248
|
+
programId: string;
|
|
249
|
+
keys: Array<{
|
|
250
|
+
pubkey: string;
|
|
251
|
+
isSigner: boolean;
|
|
252
|
+
isWritable: boolean;
|
|
253
|
+
}>;
|
|
254
|
+
data: string;
|
|
255
|
+
}>;
|
|
256
|
+
/** Number of additional days being added */
|
|
257
|
+
duration: number;
|
|
258
|
+
/** Cost breakdown for the renewal */
|
|
259
|
+
cost: {
|
|
260
|
+
/** Cost in lamports */
|
|
261
|
+
lamports: number;
|
|
262
|
+
/** Cost in SOL */
|
|
263
|
+
sol: number;
|
|
264
|
+
};
|
|
265
|
+
};
|
|
169
266
|
|
|
170
267
|
declare enum Environment {
|
|
171
268
|
mainnet = "mainnet-beta",
|
|
@@ -177,7 +274,7 @@ interface ClientOptions {
|
|
|
177
274
|
/** Solana RPC endpoint to use for chain interactions */
|
|
178
275
|
environment: Environment;
|
|
179
276
|
}
|
|
180
|
-
interface
|
|
277
|
+
interface UploadParams extends Pick<CreateDepositArgs, 'signTransaction' | 'userEmail'> {
|
|
181
278
|
/** Wallet public key of the payer */
|
|
182
279
|
payer: PublicKey;
|
|
183
280
|
/** File(s) to be stored */
|
|
@@ -185,6 +282,10 @@ interface DepositParams extends Pick<CreateDepositArgs, 'signTransaction' | 'use
|
|
|
185
282
|
/** Duration in days to store the data */
|
|
186
283
|
durationDays: number;
|
|
187
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* @deprecated Use {@link UploadParams} instead.
|
|
287
|
+
*/
|
|
288
|
+
type DepositParams = UploadParams;
|
|
188
289
|
/**
|
|
189
290
|
* Solana Storage Client — simplified (no fee estimation)
|
|
190
291
|
*/
|
|
@@ -212,19 +313,67 @@ declare class Client {
|
|
|
212
313
|
*
|
|
213
314
|
* @returns {Promise<UploadResult>} The upload result after transaction is processed.
|
|
214
315
|
*/
|
|
215
|
-
createDeposit({ payer, file, durationDays, signTransaction, userEmail, }:
|
|
316
|
+
createDeposit({ payer, file, durationDays, signTransaction, userEmail, }: UploadParams): Promise<UploadResult>;
|
|
216
317
|
/**
|
|
217
318
|
* estimates the cost for a file based on the amount of days it should be stored for
|
|
218
319
|
* @param {File} file - a file to be uploaded
|
|
219
320
|
* @param {number} duration - how long (in seconds) the file should be stored for
|
|
220
321
|
*/
|
|
221
|
-
estimateStorageCost
|
|
322
|
+
estimateStorageCost(file: File[], duration: number): Promise<{
|
|
222
323
|
sol: number;
|
|
223
|
-
lamports:
|
|
224
|
-
}
|
|
225
|
-
getUserUploadHistory(userAddress: string): Promise<
|
|
324
|
+
lamports: any;
|
|
325
|
+
}>;
|
|
326
|
+
getUserUploadHistory(userAddress: string): Promise<UploadHistoryResponse>;
|
|
327
|
+
/**
|
|
328
|
+
* Get cost estimate for renewing storage duration
|
|
329
|
+
*
|
|
330
|
+
* @param {string} cid - Content identifier of the file to renew
|
|
331
|
+
* @param {number} duration - Number of additional days to extend storage
|
|
332
|
+
*
|
|
333
|
+
* @example
|
|
334
|
+
* const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
|
|
335
|
+
* console.log(`Renewal cost: ${quote.costInSOL} SOL`);
|
|
336
|
+
*
|
|
337
|
+
* @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
|
|
338
|
+
*/
|
|
339
|
+
getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
|
|
340
|
+
/**
|
|
341
|
+
* Renew storage for an existing deposit
|
|
342
|
+
*
|
|
343
|
+
* @param {Object} params
|
|
344
|
+
* @param {string} params.cid - Content identifier of the file to renew
|
|
345
|
+
* @param {number} params.duration - Number of additional days to extend storage
|
|
346
|
+
* @param {PublicKey} params.payer - Wallet public key paying for the renewal
|
|
347
|
+
* @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* const { publicKey, signTransaction } = useSolanaWallet();
|
|
351
|
+
* const result = await client.renewStorage({
|
|
352
|
+
* cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
|
|
353
|
+
* duration: 30,
|
|
354
|
+
* payer: publicKey,
|
|
355
|
+
* signTransaction,
|
|
356
|
+
* });
|
|
357
|
+
*
|
|
358
|
+
* @returns {Promise<UploadResult>} Result of the renewal transaction
|
|
359
|
+
*/
|
|
360
|
+
renewStorageDuration({ cid, duration, payer, signTransaction, }: StorageRenewalParams): Promise<UploadResult>;
|
|
361
|
+
/**
|
|
362
|
+
* Gets the current SOL/USD price
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* const { price } = await client.getSolPrice();
|
|
366
|
+
* console.log(`SOL price: $${price}`);
|
|
367
|
+
*
|
|
368
|
+
* @returns {Promise<{ price: number }>} Current SOL price in USD
|
|
369
|
+
*/
|
|
370
|
+
getSolPrice(): Promise<{
|
|
371
|
+
price: number;
|
|
372
|
+
}>;
|
|
226
373
|
}
|
|
227
374
|
|
|
375
|
+
declare const useUpload: (environment: ClientOptions["environment"]) => Client;
|
|
376
|
+
|
|
228
377
|
/**
|
|
229
378
|
* Calls the deposit API for on-chain storage and returns a Transaction
|
|
230
379
|
* which must be signed and sent externally by the user.
|
|
@@ -239,24 +388,56 @@ declare class Client {
|
|
|
239
388
|
* @returns Transaction
|
|
240
389
|
*/
|
|
241
390
|
declare function createDepositTxn({ file, duration, payer, connection, signTransaction, userEmail, }: CreateDepositArgs): Promise<UploadResult>;
|
|
242
|
-
|
|
243
|
-
|
|
391
|
+
/**
|
|
392
|
+
* Get cost estimate for renewing storage duration
|
|
393
|
+
*
|
|
394
|
+
* @param {string} cid - Content identifier of the uploaded data to renew
|
|
395
|
+
* @param {number} duration - Number of additional days to extend storage
|
|
396
|
+
*
|
|
397
|
+
* @example
|
|
398
|
+
* const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
|
|
399
|
+
* console.log(`Renewal cost: ${quote.costInSOL} SOL`);
|
|
400
|
+
*
|
|
401
|
+
* @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
|
|
402
|
+
*/
|
|
403
|
+
declare function getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
|
|
404
|
+
/**
|
|
405
|
+
* Renew storage for an existing deposit
|
|
406
|
+
*
|
|
407
|
+
* @param {Object} params
|
|
408
|
+
* @param {string} params.cid - Content identifier of the uploaded data to renew
|
|
409
|
+
* @param {number} params.duration - Number of additional days to extend storage
|
|
410
|
+
* @param {PublicKey} params.payer - Wallet public key paying for the renewal
|
|
411
|
+
* @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
|
|
412
|
+
*
|
|
413
|
+
* @example
|
|
414
|
+
* const { publicKey, signTransaction } = useSolanaWallet();
|
|
415
|
+
* const result = await client.renewStorage({
|
|
416
|
+
* cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
|
|
417
|
+
* additionalDays: 30,
|
|
418
|
+
* payer: publicKey,
|
|
419
|
+
* signTransaction,
|
|
420
|
+
* });
|
|
421
|
+
*
|
|
422
|
+
* @returns {Promise<UploadResult>} Result of the renewal transaction
|
|
423
|
+
*/
|
|
424
|
+
declare function renewStorageTxn({ cid, duration, payer, connection, signTransaction, }: RenewStorageDurationArgs): Promise<UploadResult>;
|
|
244
425
|
|
|
245
426
|
/**
|
|
246
|
-
*
|
|
427
|
+
* Get the upload history for a given user address from the server
|
|
247
428
|
*
|
|
248
|
-
* @param userAddress - The wallet address of the user to fetch
|
|
429
|
+
* @param userAddress - The wallet address of the user to fetch upload history for
|
|
249
430
|
* @param options - Optional server configuration
|
|
250
|
-
* @returns Promise<
|
|
431
|
+
* @returns Promise<UploadHistoryResponse> - The user's upload history
|
|
251
432
|
*
|
|
252
433
|
* @example
|
|
253
434
|
* ```typescript
|
|
254
|
-
* const history = await
|
|
255
|
-
* console.log('User
|
|
435
|
+
* const history = await getUserUploadHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
|
|
436
|
+
* console.log('User upload history:', history.userHistory);
|
|
256
437
|
* ```
|
|
257
438
|
*
|
|
258
439
|
* @throws {Error} When the user address is invalid or the request fails
|
|
259
440
|
*/
|
|
260
|
-
declare function
|
|
441
|
+
declare function getUserUploadHistory(userAddress: string, options?: ServerOptions): Promise<UploadHistoryResponse>;
|
|
261
442
|
|
|
262
|
-
export { Client, type ClientOptions, type CreateDepositArgs, type DepositHistoryEntry, type DepositHistoryResponse, type DepositParams, type DepositResult, Environment, type OnChainConfig, type OnChainDeposit, type ServerOptions, type UploadOptions, type UploadResult, type WalletItem, createDepositTxn, fetchUserDepositHistory, getRpcUrl, useDeposit };
|
|
443
|
+
export { Client, type ClientOptions, type CreateDepositArgs, type DepositHistoryEntry, type DepositHistoryResponse, type DepositParams, type DepositResult, Environment, type OnChainConfig, type OnChainDeposit, type RenewStorageDurationArgs, type ServerOptions, type StorageRenewalCost, type StorageRenewalParams, type StorageRenewalResult, type Transaction, type UploadHistory, type UploadHistoryResponse, type UploadOptions, type UploadParams, type UploadResult, type WalletItem, createDepositTxn, getUserUploadHistory as fetchUserDepositHistory, getUserUploadHistory as fetchUserUploadHistory, getRpcUrl, getStorageRenewalCost, getUserUploadHistory, renewStorageTxn, useUpload as useDeposit, useUpload };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Address, Signature } from '@solana/kit';
|
|
2
|
-
import { PublicKey, Connection, Transaction } from '@solana/web3.js';
|
|
2
|
+
import { PublicKey, Connection, Transaction as Transaction$1 } from '@solana/web3.js';
|
|
3
3
|
|
|
4
4
|
interface ServerOptions {
|
|
5
|
-
/** URL pointing to the
|
|
5
|
+
/** URL pointing to the server (mostly Storacha's) */
|
|
6
6
|
url?: string;
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
@@ -116,14 +116,49 @@ interface CreateDepositArgs extends Omit<OnChainDeposit, 'depositAmount' | 'depo
|
|
|
116
116
|
* const {publickKey, signTransaction} = useSolanaWallet()
|
|
117
117
|
* const signTransaction = await signTransaction(tx)
|
|
118
118
|
* */
|
|
119
|
-
signTransaction: (tx: Transaction) => Promise<Transaction>;
|
|
119
|
+
signTransaction: (tx: Transaction$1) => Promise<Transaction$1>;
|
|
120
120
|
/** Optional user email for expiration notifications */
|
|
121
121
|
userEmail?: string;
|
|
122
122
|
}
|
|
123
|
+
/** Arguments for renewing storage duration */
|
|
124
|
+
interface StorageRenewalParams extends Pick<CreateDepositArgs, 'payer' | 'signTransaction'> {
|
|
125
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
126
|
+
cid: string;
|
|
127
|
+
/** Duration in days to extend storage */
|
|
128
|
+
duration: number;
|
|
129
|
+
}
|
|
130
|
+
/** Internal arguments for renewStorageTxn */
|
|
131
|
+
interface RenewStorageDurationArgs extends Pick<CreateDepositArgs, 'payer' | 'signTransaction' | 'connection'> {
|
|
132
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
133
|
+
cid: string;
|
|
134
|
+
/** Duration in days to extend storage */
|
|
135
|
+
duration: number;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Transaction record for an upload (initial deposit or renewal)
|
|
139
|
+
*/
|
|
140
|
+
interface Transaction {
|
|
141
|
+
/** Unique identifier for the transaction */
|
|
142
|
+
id: number;
|
|
143
|
+
/** ID of the associated deposit */
|
|
144
|
+
depositId: number;
|
|
145
|
+
/** Content identifier of the upload */
|
|
146
|
+
contentCid: string;
|
|
147
|
+
/** Solana transaction hash */
|
|
148
|
+
transactionHash: string;
|
|
149
|
+
/** Type of transaction: 'initial_deposit' | 'renewal' */
|
|
150
|
+
transactionType: string;
|
|
151
|
+
/** Amount paid in lamports */
|
|
152
|
+
amountInLamports: number;
|
|
153
|
+
/** Duration in days purchased */
|
|
154
|
+
durationDays: number;
|
|
155
|
+
/** Timestamp when the transaction was created */
|
|
156
|
+
createdAt: string;
|
|
157
|
+
}
|
|
123
158
|
/**
|
|
124
|
-
* Individual
|
|
159
|
+
* Individual upload history entry from the server
|
|
125
160
|
*/
|
|
126
|
-
interface
|
|
161
|
+
interface UploadHistory {
|
|
127
162
|
/** Unique identifier for the deposit */
|
|
128
163
|
id: number;
|
|
129
164
|
/** User's wallet address (deposit key) */
|
|
@@ -156,16 +191,78 @@ interface DepositHistoryEntry {
|
|
|
156
191
|
deletionStatus?: string;
|
|
157
192
|
/** Timestamp when warning email was sent */
|
|
158
193
|
warningSentAt?: string;
|
|
194
|
+
/** Optional array of all transactions for this upload */
|
|
195
|
+
transactions?: Transaction[];
|
|
159
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* @deprecated Use UploadHistory instead
|
|
199
|
+
*/
|
|
200
|
+
type DepositHistoryEntry = UploadHistory;
|
|
160
201
|
/**
|
|
161
202
|
* Response from the getUserUploadHistory endpoint
|
|
162
203
|
*/
|
|
163
|
-
interface
|
|
164
|
-
/** Array of
|
|
165
|
-
userHistory:
|
|
204
|
+
interface UploadHistoryResponse {
|
|
205
|
+
/** Array of upload history entries */
|
|
206
|
+
userHistory: UploadHistory[] | null;
|
|
166
207
|
/** The user address that was queried */
|
|
167
208
|
userAddress: string;
|
|
168
209
|
}
|
|
210
|
+
/**
|
|
211
|
+
* @deprecated Use UploadHistoryResponse instead
|
|
212
|
+
*/
|
|
213
|
+
type DepositHistoryResponse = UploadHistoryResponse;
|
|
214
|
+
/**
|
|
215
|
+
* Storage renewal cost estimation
|
|
216
|
+
*/
|
|
217
|
+
type StorageRenewalCost = {
|
|
218
|
+
/** New expiration date after renewal */
|
|
219
|
+
newExpirationDate: string;
|
|
220
|
+
/** Current expiration date before renewal */
|
|
221
|
+
currentExpirationDate: string;
|
|
222
|
+
/** Number of additional days being added */
|
|
223
|
+
additionalDays: string;
|
|
224
|
+
/** Cost of renewal in lamports */
|
|
225
|
+
costInLamports: number;
|
|
226
|
+
/** Cost of renewal in SOL */
|
|
227
|
+
costInSOL: number;
|
|
228
|
+
/** Details about the file being renewed */
|
|
229
|
+
fileDetails: {
|
|
230
|
+
/** Content identifier */
|
|
231
|
+
cid: string;
|
|
232
|
+
/** Name of the file */
|
|
233
|
+
fileName: string;
|
|
234
|
+
/** Size of the file in bytes */
|
|
235
|
+
fileSize: number;
|
|
236
|
+
};
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Storage renewal transaction result
|
|
240
|
+
*/
|
|
241
|
+
type StorageRenewalResult = {
|
|
242
|
+
/** Content identifier of the uploaded data to be renewed */
|
|
243
|
+
cid: string;
|
|
244
|
+
/** Status message about the renewal */
|
|
245
|
+
message: string;
|
|
246
|
+
/** Transaction instructions for the user to sign */
|
|
247
|
+
instructions: Array<{
|
|
248
|
+
programId: string;
|
|
249
|
+
keys: Array<{
|
|
250
|
+
pubkey: string;
|
|
251
|
+
isSigner: boolean;
|
|
252
|
+
isWritable: boolean;
|
|
253
|
+
}>;
|
|
254
|
+
data: string;
|
|
255
|
+
}>;
|
|
256
|
+
/** Number of additional days being added */
|
|
257
|
+
duration: number;
|
|
258
|
+
/** Cost breakdown for the renewal */
|
|
259
|
+
cost: {
|
|
260
|
+
/** Cost in lamports */
|
|
261
|
+
lamports: number;
|
|
262
|
+
/** Cost in SOL */
|
|
263
|
+
sol: number;
|
|
264
|
+
};
|
|
265
|
+
};
|
|
169
266
|
|
|
170
267
|
declare enum Environment {
|
|
171
268
|
mainnet = "mainnet-beta",
|
|
@@ -177,7 +274,7 @@ interface ClientOptions {
|
|
|
177
274
|
/** Solana RPC endpoint to use for chain interactions */
|
|
178
275
|
environment: Environment;
|
|
179
276
|
}
|
|
180
|
-
interface
|
|
277
|
+
interface UploadParams extends Pick<CreateDepositArgs, 'signTransaction' | 'userEmail'> {
|
|
181
278
|
/** Wallet public key of the payer */
|
|
182
279
|
payer: PublicKey;
|
|
183
280
|
/** File(s) to be stored */
|
|
@@ -185,6 +282,10 @@ interface DepositParams extends Pick<CreateDepositArgs, 'signTransaction' | 'use
|
|
|
185
282
|
/** Duration in days to store the data */
|
|
186
283
|
durationDays: number;
|
|
187
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* @deprecated Use {@link UploadParams} instead.
|
|
287
|
+
*/
|
|
288
|
+
type DepositParams = UploadParams;
|
|
188
289
|
/**
|
|
189
290
|
* Solana Storage Client — simplified (no fee estimation)
|
|
190
291
|
*/
|
|
@@ -212,19 +313,67 @@ declare class Client {
|
|
|
212
313
|
*
|
|
213
314
|
* @returns {Promise<UploadResult>} The upload result after transaction is processed.
|
|
214
315
|
*/
|
|
215
|
-
createDeposit({ payer, file, durationDays, signTransaction, userEmail, }:
|
|
316
|
+
createDeposit({ payer, file, durationDays, signTransaction, userEmail, }: UploadParams): Promise<UploadResult>;
|
|
216
317
|
/**
|
|
217
318
|
* estimates the cost for a file based on the amount of days it should be stored for
|
|
218
319
|
* @param {File} file - a file to be uploaded
|
|
219
320
|
* @param {number} duration - how long (in seconds) the file should be stored for
|
|
220
321
|
*/
|
|
221
|
-
estimateStorageCost
|
|
322
|
+
estimateStorageCost(file: File[], duration: number): Promise<{
|
|
222
323
|
sol: number;
|
|
223
|
-
lamports:
|
|
224
|
-
}
|
|
225
|
-
getUserUploadHistory(userAddress: string): Promise<
|
|
324
|
+
lamports: any;
|
|
325
|
+
}>;
|
|
326
|
+
getUserUploadHistory(userAddress: string): Promise<UploadHistoryResponse>;
|
|
327
|
+
/**
|
|
328
|
+
* Get cost estimate for renewing storage duration
|
|
329
|
+
*
|
|
330
|
+
* @param {string} cid - Content identifier of the file to renew
|
|
331
|
+
* @param {number} duration - Number of additional days to extend storage
|
|
332
|
+
*
|
|
333
|
+
* @example
|
|
334
|
+
* const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
|
|
335
|
+
* console.log(`Renewal cost: ${quote.costInSOL} SOL`);
|
|
336
|
+
*
|
|
337
|
+
* @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
|
|
338
|
+
*/
|
|
339
|
+
getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
|
|
340
|
+
/**
|
|
341
|
+
* Renew storage for an existing deposit
|
|
342
|
+
*
|
|
343
|
+
* @param {Object} params
|
|
344
|
+
* @param {string} params.cid - Content identifier of the file to renew
|
|
345
|
+
* @param {number} params.duration - Number of additional days to extend storage
|
|
346
|
+
* @param {PublicKey} params.payer - Wallet public key paying for the renewal
|
|
347
|
+
* @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* const { publicKey, signTransaction } = useSolanaWallet();
|
|
351
|
+
* const result = await client.renewStorage({
|
|
352
|
+
* cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
|
|
353
|
+
* duration: 30,
|
|
354
|
+
* payer: publicKey,
|
|
355
|
+
* signTransaction,
|
|
356
|
+
* });
|
|
357
|
+
*
|
|
358
|
+
* @returns {Promise<UploadResult>} Result of the renewal transaction
|
|
359
|
+
*/
|
|
360
|
+
renewStorageDuration({ cid, duration, payer, signTransaction, }: StorageRenewalParams): Promise<UploadResult>;
|
|
361
|
+
/**
|
|
362
|
+
* Gets the current SOL/USD price
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* const { price } = await client.getSolPrice();
|
|
366
|
+
* console.log(`SOL price: $${price}`);
|
|
367
|
+
*
|
|
368
|
+
* @returns {Promise<{ price: number }>} Current SOL price in USD
|
|
369
|
+
*/
|
|
370
|
+
getSolPrice(): Promise<{
|
|
371
|
+
price: number;
|
|
372
|
+
}>;
|
|
226
373
|
}
|
|
227
374
|
|
|
375
|
+
declare const useUpload: (environment: ClientOptions["environment"]) => Client;
|
|
376
|
+
|
|
228
377
|
/**
|
|
229
378
|
* Calls the deposit API for on-chain storage and returns a Transaction
|
|
230
379
|
* which must be signed and sent externally by the user.
|
|
@@ -239,24 +388,56 @@ declare class Client {
|
|
|
239
388
|
* @returns Transaction
|
|
240
389
|
*/
|
|
241
390
|
declare function createDepositTxn({ file, duration, payer, connection, signTransaction, userEmail, }: CreateDepositArgs): Promise<UploadResult>;
|
|
242
|
-
|
|
243
|
-
|
|
391
|
+
/**
|
|
392
|
+
* Get cost estimate for renewing storage duration
|
|
393
|
+
*
|
|
394
|
+
* @param {string} cid - Content identifier of the uploaded data to renew
|
|
395
|
+
* @param {number} duration - Number of additional days to extend storage
|
|
396
|
+
*
|
|
397
|
+
* @example
|
|
398
|
+
* const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
|
|
399
|
+
* console.log(`Renewal cost: ${quote.costInSOL} SOL`);
|
|
400
|
+
*
|
|
401
|
+
* @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
|
|
402
|
+
*/
|
|
403
|
+
declare function getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
|
|
404
|
+
/**
|
|
405
|
+
* Renew storage for an existing deposit
|
|
406
|
+
*
|
|
407
|
+
* @param {Object} params
|
|
408
|
+
* @param {string} params.cid - Content identifier of the uploaded data to renew
|
|
409
|
+
* @param {number} params.duration - Number of additional days to extend storage
|
|
410
|
+
* @param {PublicKey} params.payer - Wallet public key paying for the renewal
|
|
411
|
+
* @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
|
|
412
|
+
*
|
|
413
|
+
* @example
|
|
414
|
+
* const { publicKey, signTransaction } = useSolanaWallet();
|
|
415
|
+
* const result = await client.renewStorage({
|
|
416
|
+
* cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
|
|
417
|
+
* additionalDays: 30,
|
|
418
|
+
* payer: publicKey,
|
|
419
|
+
* signTransaction,
|
|
420
|
+
* });
|
|
421
|
+
*
|
|
422
|
+
* @returns {Promise<UploadResult>} Result of the renewal transaction
|
|
423
|
+
*/
|
|
424
|
+
declare function renewStorageTxn({ cid, duration, payer, connection, signTransaction, }: RenewStorageDurationArgs): Promise<UploadResult>;
|
|
244
425
|
|
|
245
426
|
/**
|
|
246
|
-
*
|
|
427
|
+
* Get the upload history for a given user address from the server
|
|
247
428
|
*
|
|
248
|
-
* @param userAddress - The wallet address of the user to fetch
|
|
429
|
+
* @param userAddress - The wallet address of the user to fetch upload history for
|
|
249
430
|
* @param options - Optional server configuration
|
|
250
|
-
* @returns Promise<
|
|
431
|
+
* @returns Promise<UploadHistoryResponse> - The user's upload history
|
|
251
432
|
*
|
|
252
433
|
* @example
|
|
253
434
|
* ```typescript
|
|
254
|
-
* const history = await
|
|
255
|
-
* console.log('User
|
|
435
|
+
* const history = await getUserUploadHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
|
|
436
|
+
* console.log('User upload history:', history.userHistory);
|
|
256
437
|
* ```
|
|
257
438
|
*
|
|
258
439
|
* @throws {Error} When the user address is invalid or the request fails
|
|
259
440
|
*/
|
|
260
|
-
declare function
|
|
441
|
+
declare function getUserUploadHistory(userAddress: string, options?: ServerOptions): Promise<UploadHistoryResponse>;
|
|
261
442
|
|
|
262
|
-
export { Client, type ClientOptions, type CreateDepositArgs, type DepositHistoryEntry, type DepositHistoryResponse, type DepositParams, type DepositResult, Environment, type OnChainConfig, type OnChainDeposit, type ServerOptions, type UploadOptions, type UploadResult, type WalletItem, createDepositTxn, fetchUserDepositHistory, getRpcUrl, useDeposit };
|
|
443
|
+
export { Client, type ClientOptions, type CreateDepositArgs, type DepositHistoryEntry, type DepositHistoryResponse, type DepositParams, type DepositResult, Environment, type OnChainConfig, type OnChainDeposit, type RenewStorageDurationArgs, type ServerOptions, type StorageRenewalCost, type StorageRenewalParams, type StorageRenewalResult, type Transaction, type UploadHistory, type UploadHistoryResponse, type UploadOptions, type UploadParams, type UploadResult, type WalletItem, createDepositTxn, getUserUploadHistory as fetchUserDepositHistory, getUserUploadHistory as fetchUserUploadHistory, getRpcUrl, getStorageRenewalCost, getUserUploadHistory, renewStorageTxn, useUpload as useDeposit, useUpload };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Connection as
|
|
1
|
+
import{Connection as j}from"@solana/web3.js";var l=typeof window<"u"&&window.location.hostname==="localhost"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",P=86400,D=1e9;import{PublicKey as b,SendTransactionError as v,Transaction as I,TransactionInstruction as A}from"@solana/web3.js";async function k({file:o,duration:t,payer:r,connection:e,signTransaction:c,userEmail:s}){try{let n=new FormData;o.forEach(a=>n.append("file",a)),n.append("duration",t.toString()),n.append("publicKey",r.toBase58()),s&&n.append("userEmail",s);let p=o.length>1,h,f=await fetch(`${l}/api/solana/deposit`,{method:"POST",body:n});if(!f.ok)throw new Error("Failed to get deposit instructions");let i=await f.json();if(!i.instructions||!i.instructions.length)throw new Error("No instructions from deposit API");let g=await e.getLatestBlockhash("confirmed"),d=i.instructions[0],m=new A({programId:new b(d.programId),keys:d.keys.map(a=>({pubkey:new b(a.pubkey),isSigner:a.isSigner,isWritable:a.isWritable})),data:Buffer.from(d.data,"base64")}),y=new I;y.recentBlockhash=g.blockhash,y.feePayer=r,y.add(m);let $=await c(y),S;try{S=await e.sendRawTransaction($.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"})}catch(a){throw a instanceof v?(a.logs??[]).some(N=>N.includes("already in use"))?new Error("This file has already been uploaded. You can find it in your dashboard."):new Error("Transaction failed during simulation. Please try again."):a}let E=await e.confirmTransaction({signature:S,blockhash:g.blockhash,lastValidBlockHeight:g.lastValidBlockHeight},"confirmed");if(E.value.err)throw console.error("Failed to confirm this transaction:",E.value.err),new Error(`Transaction failed: ${JSON.stringify(E.value.err)}`);try{await fetch(`${l}/api/user/update-transaction-hash`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:i.cid,transactionHash:S})})}catch(a){console.warn("Failed to update transaction hash:",a)}i.error&&(h=i.error);let U=new FormData;o.forEach(a=>U.append("file",a));let w;if(p?w=await fetch(`${l}/api/user/upload-files?cid=${encodeURIComponent(i.cid)}`,{method:"POST",body:U}):w=await fetch(`${l}/api/user/upload-file?cid=${encodeURIComponent(i.cid)}`,{method:"POST",body:U}),!w.ok){let a="Unknown error";try{let T=await w.json();a=T.message||T.error||a}catch{}throw new Error("Deposit API error: "+a)}let u=await w?.json();return{signature:S,success:!0,cid:i.cid,url:u.object.url,message:u.object.message,fileInfo:u.object?{filename:u.object.fileInfo?.filename||"",size:u?.object?.fileInfo?.size||0,uploadedAt:u?.object?.fileInfo?.uploadedAt||"",type:u?.object?.fileInfo?.type||""}:void 0}}catch(n){return console.error(n),n instanceof Error&&(console.error("Error name:",n.name),console.error("Error message:",n.message),console.error("Error stack:",n.stack)),{signature:"",success:!1,cid:"",url:"",message:"",fileInfo:void 0,error:n instanceof Error?n.message:"Unknown error occurred"}}}async function C(o,t){try{let r=await fetch(`${l}/api/user/renewal-cost?cid=${encodeURIComponent(o)}&duration=${t}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!r.ok){let e=await r.json();throw new Error(e.message||"Failed to get storage renewal cost")}return await r.json()}catch(r){return console.error("Failed to get storage renewal cost",r),null}}async function x({cid:o,duration:t,payer:r,connection:e,signTransaction:c}){let s=await fetch(`${l}/api/user/renew-storage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:o,duration:t,publicKey:r.toString()})});if(!s.ok){let d=await s.json().catch(()=>({}));throw new Error(d.message||"Failed to create renewal transaction")}let n=await s.json(),p=new I;n.instructions.forEach(d=>{p.add({programId:new b(d.programId),keys:d.keys.map(m=>({pubkey:new b(m.pubkey),isSigner:m.isSigner,isWritable:m.isWritable})),data:Buffer.from(d.data,"base64")})});let{blockhash:h}=await e.getLatestBlockhash();p.recentBlockhash=h,p.feePayer=r;let f=await c(p),i=await e.sendRawTransaction(f.serialize());return await e.confirmTransaction(i,"confirmed"),(await fetch(`${l}/api/user/confirm-renewal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:o,duration:t,transactionHash:i})})).ok||console.error("Failed to confirm renewal"),{success:!0,cid:o,signature:i,url:`https://w3s.link/ipfs/${o}`,message:"Storage renewed successfully"}}async function O(o,t={}){if(!o||typeof o!="string")throw new Error("User address is required and must be a string");let r=t.url||l;try{let e=await fetch(`${r}/api/user/user-upload-history?userAddress=${encodeURIComponent(o)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){let s=await e.json().catch(()=>({}));throw new Error(s.message||`Failed to fetch upload history: ${e.status} ${e.statusText}`)}let c=await e.json();if(typeof c!="object"||c===null)throw new Error("Invalid response format from server");if(typeof c.userAddress!="string")throw new Error("Invalid userAddress in response");return c}catch(e){throw e instanceof Error?e:new Error("Unknown error occurred while fetching upload history")}}var F=(e=>(e.mainnet="mainnet-beta",e.testnet="testnet",e.devnet="devnet",e))(F||{});function B(o){switch(o){case"mainnet-beta":return"https://api.mainnet-beta.solana.com";case"testnet":return"https://api.testnet.solana.com";case"devnet":return"https://api.devnet.solana.com";default:throw new Error(`Unsupported environment: ${o}`)}}var R=class{constructor(t){this.rpcUrl=B(t.environment)}async createDeposit({payer:t,file:r,durationDays:e,signTransaction:c,userEmail:s}){console.log("Creating deposit transaction with environment:",this.rpcUrl);let n=new j(this.rpcUrl,"confirmed");return await k({file:r,duration:e*P,payer:t,connection:n,signTransaction:c,userEmail:s})}async estimateStorageCost(t,r){let e=t.reduce((f,i)=>f+i.size,0),c=Math.floor(r/86400),s=await fetch(`${l}/api/user/get-quote?size=${e}&duration=${c}`);if(!s.ok)throw new Error("Failed to get storage cost estimate");let{quote:n}=await s.json(),p=n.totalCost;return{sol:p/D,lamports:p}}async getUserUploadHistory(t){return await O(t)}async getStorageRenewalCost(t,r){return await C(t,r)}async renewStorageDuration({cid:t,duration:r,payer:e,signTransaction:c}){let s=new j(this.rpcUrl,"confirmed");return await x({cid:t,duration:r,payer:e,connection:s,signTransaction:c})}async getSolPrice(){let t=await fetch(`${l}/api/user/sol-price`);if(!t.ok)throw new Error("Couldn't fetch SOL price");return(await t.json()).price}};var ee=o=>new R({environment:o||"testnet"});export{R as Client,F as Environment,k as createDepositTxn,O as fetchUserDepositHistory,O as fetchUserUploadHistory,B as getRpcUrl,C as getStorageRenewalCost,O as getUserUploadHistory,x as renewStorageTxn,ee as useDeposit,ee as useUpload};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "storacha-sol",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"main": "./dist/index.js",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "tsup src/index.ts --minify",
|
|
7
7
|
"dev": "pnpm build --watch",
|
|
8
|
-
"pack:local": "pnpm build && pnpm pack"
|
|
8
|
+
"pack:local": "pnpm build && pnpm pack",
|
|
9
|
+
"knip": "knip"
|
|
9
10
|
},
|
|
10
11
|
"exports": {
|
|
11
12
|
"import": {
|
|
@@ -21,7 +22,7 @@
|
|
|
21
22
|
],
|
|
22
23
|
"repository": {
|
|
23
24
|
"type": "git",
|
|
24
|
-
"url": "git+https://github.com/seetadev/storacha-solana-sdk"
|
|
25
|
+
"url": "git+https://github.com/seetadev/storacha-solana-sdk.git"
|
|
25
26
|
},
|
|
26
27
|
"types": "./dist/index.d.ts",
|
|
27
28
|
"type": "module",
|
|
@@ -43,7 +44,7 @@
|
|
|
43
44
|
"standard-version": "^9.5.0"
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|
|
46
|
-
"
|
|
47
|
+
"knip": "^5.72.0",
|
|
47
48
|
"tsup": "^8.5.0",
|
|
48
49
|
"typescript": "^5.8.3"
|
|
49
50
|
}
|