storacha-sol 0.0.4 → 0.0.5

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 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
 
@@ -163,6 +163,63 @@ Files that have expired are automatically deleted from Storacha storage. This ha
163
163
 
164
164
  Your upload history will show the deletion status, so you can track which files are still active, warned, or deleted.
165
165
 
166
+ ### Storage Renewal
167
+
168
+ Extend the storage duration for your existing uploads before they expire:
169
+
170
+ ```ts
171
+ const client = useDeposit('testnet' as Environment);
172
+ const { publicKey, signTransaction } = useSolanaWallet();
173
+
174
+ // First, get a quote to see what it'll cost
175
+ const quote = await client.getStorageRenewalCost(cid, 30); // 30 additional days
176
+
177
+ console.log(`Current expiration: ${quote.currentExpirationDate}`);
178
+ console.log(`New expiration: ${quote.newExpirationDate}`);
179
+ console.log(`Cost: ${quote.costInSOL} SOL`);
180
+
181
+ const result = await client.renewStorageDuration({
182
+ cid,
183
+ additionalDays: 30,
184
+ payer: publicKey,
185
+ signTransaction: async (tx) => {
186
+ const signed = await signTransaction(tx);
187
+ return signed;
188
+ },
189
+ });
190
+
191
+ if (result.success) {
192
+ console.log('Storage renewed! Transaction:', result.signature);
193
+ }
194
+ ```
195
+
196
+ **How it works:**
197
+ - `getStorageRenewalCost()` shows you the cost and new expiration date before committing
198
+ - `renewStorageDuration()` creates a payment transaction (same flow as initial upload)
199
+ - After payment confirms, your file's expiration date gets updated
200
+
201
+ ## Usage with Vite
202
+
203
+ 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.
204
+
205
+ To resolve this, you can define `process.env` as an empty object in your `vite.config.ts` file:
206
+
207
+ ```ts
208
+ // vite.config.ts
209
+ import { defineConfig } from 'vite'
210
+ import react from '@vitejs/plugin-react'
211
+
212
+ export default defineConfig({
213
+ plugins: [react()],
214
+ // ... other config
215
+ define: {
216
+ 'process.env': {},
217
+ },
218
+ })
219
+ ```
220
+
221
+ This will prevent the runtime error and allow the SDK to function correctly.
222
+
166
223
  ## Want to contribute?
167
224
 
168
225
  Read the [Contributing guide](CONTRIBUTING.md)
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var I=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var A=(r,e)=>{for(var n in e)I(r,n,{get:e[n],enumerable:!0})},B=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of N(e))!$.call(r,s)&&s!==n&&I(r,s,{get:()=>e[s],enumerable:!(t=j(e,s))||t.enumerable});return r};var F=r=>B(I({},"__esModule",{value:!0}),r);var z={};A(z,{Client:()=>f,Environment:()=>x,createDepositTxn:()=>U,fetchUserDepositHistory:()=>P,getRpcUrl:()=>O,useDeposit:()=>H});module.exports=F(z);var T=require("@solana/web3.js");var{NODE_ENV:_}=process.env,l=_==="development"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",v=86400;async function P(r,e={}){if(!r||typeof r!="string")throw new Error("User address is required and must be a string");let n=e.url||l;try{let t=await fetch(`${n}/api/user/user-upload-history?userAddress=${encodeURIComponent(r)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok){let a=await t.json().catch(()=>({}));throw new Error(a.message||`Failed to fetch deposit history: ${t.status} ${t.statusText}`)}let s=await t.json();if(typeof s!="object"||s===null)throw new Error("Invalid response format from server");if(typeof s.userAddress!="string")throw new Error("Invalid userAddress in response");return s}catch(t){throw t instanceof Error?t:new Error("Unknown error occurred while fetching deposit history")}}var d=require("@solana/web3.js");async function U({file:r,duration:e,payer:n,connection:t,signTransaction:s,userEmail:a}){try{let o=new FormData;r.forEach(i=>o.append("file",i)),o.append("duration",e.toString()),o.append("publicKey",n.toBase58()),a&&o.append("userEmail",a);let h=r.length>1,w,S=await fetch(`${l}/api/solana/deposit`,{method:"POST",body:o});if(!S.ok)throw new Error("Failed to get deposit instructions");let c=await S.json();if(!c.instructions||!c.instructions.length)throw new Error("No instructions from deposit API");let g=await t.getLatestBlockhash("confirmed"),y=c.instructions[0],R=new d.TransactionInstruction({programId:new d.PublicKey(y.programId),keys:y.keys.map(i=>({pubkey:new d.PublicKey(i.pubkey),isSigner:i.isSigner,isWritable:i.isWritable})),data:Buffer.from(y.data,"base64")}),u=new d.Transaction;u.recentBlockhash=g.blockhash,u.feePayer=n,u.add(R);let C=await s(u),D=await t.sendRawTransaction(C.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"}),b=await t.confirmTransaction({signature:D,blockhash:g.blockhash,lastValidBlockHeight:g.lastValidBlockHeight},"confirmed");if(b.value.err)throw console.error("Failed to confirm this transaction:",b.value.err),new Error(`Transaction failed: ${JSON.stringify(b.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:D})})}catch(i){console.warn("Failed to update transaction hash:",i)}c.error&&(w=c.error);let E=new FormData;r.forEach(i=>E.append("file",i));let m;if(h?m=await fetch(`${l}/api/user/upload-files?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}):m=await fetch(`${l}/api/user/upload-file?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}),!m.ok){let i="Unknown error";try{let k=await m.json();i=k.message||k.error||i}catch{}throw new Error("Deposit API error: "+i)}let p=await m?.json();return{signature:D,success:!0,cid:c.cid,url:p.object.url,message:p.object.message,fileInfo:p.object?{filename:p.object.fileInfo?.filename||"",size:p?.object?.fileInfo?.size||0,uploadedAt:p?.object?.fileInfo?.uploadedAt||"",type:p?.object?.fileInfo?.type||""}:void 0}}catch(o){return console.error(o),o instanceof Error&&(console.error("Error name:",o.name),console.error("Error message:",o.message),console.error("Error stack:",o.stack)),{signature:"",success:!1,cid:"",url:"",message:"",fileInfo:void 0,error:o instanceof Error?o.message:"Unknown error occurred"}}}var x=(t=>(t.mainnet="mainnet-beta",t.testnet="testnet",t.devnet="devnet",t))(x||{});function O(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 f=class{constructor(e){this.estimateStorageCost=(e,n)=>{let a=e.reduce((h,w)=>h+w.size,0)*n*1e3;return{sol:a/1e9,lamports:a}};this.rpcUrl=O(e.environment)}async createDeposit({payer:e,file:n,durationDays:t,signTransaction:s,userEmail:a}){console.log("Creating deposit transaction with environment:",this.rpcUrl);let o=new T.Connection(this.rpcUrl,"confirmed");return await U({file:n,duration:t*v,payer:e,connection:o,signTransaction:s,userEmail:a})}async getUserUploadHistory(e){return await P(e)}};var H=r=>new f({environment:r||"testnet"});0&&(module.exports={Client,Environment,createDepositTxn,fetchUserDepositHistory,getRpcUrl,useDeposit});
1
+ "use strict";var P=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var H=(r,e)=>{for(var o in e)P(r,o,{get:e[o],enumerable:!0})},z=(r,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of F(e))!_.call(r,n)&&n!==o&&P(r,n,{get:()=>e[n],enumerable:!(t=L(e,n))||t.enumerable});return r};var K=r=>z(P({},"__esModule",{value:!0}),r);var J={};H(J,{Client:()=>g,Environment:()=>N,createDepositTxn:()=>D,fetchUserDepositHistory:()=>x,fetchUserUploadHistory:()=>x,getRpcUrl:()=>$,getStorageRenewalCost:()=>I,getUserUploadHistory:()=>x,renewStorageTxn:()=>k,useDeposit:()=>q,useUpload:()=>q});module.exports=K(J);var C=require("@solana/web3.js");var{NODE_ENV:M}=process.env,p=M==="development"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",O=86400,j=1e9,v=(r,e,o)=>r*o*e;var l=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 u=r.length>1,f,y=await fetch(`${p}/api/solana/deposit`,{method:"POST",body:a});if(!y.ok)throw new Error("Failed to get deposit instructions");let c=await y.json();if(!c.instructions||!c.instructions.length)throw new Error("No instructions from deposit API");let b=await t.getLatestBlockhash("confirmed"),d=c.instructions[0],w=new l.TransactionInstruction({programId:new l.PublicKey(d.programId),keys:d.keys.map(s=>({pubkey:new l.PublicKey(s.pubkey),isSigner:s.isSigner,isWritable:s.isWritable})),data:Buffer.from(d.data,"base64")}),S=new l.Transaction;S.recentBlockhash=b.blockhash,S.feePayer=o,S.add(w);let A=await n(S),R;try{R=await t.sendRawTransaction(A.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"})}catch(s){throw s instanceof l.SendTransactionError?(s.logs??[]).some(B=>B.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 U=await t.confirmTransaction({signature:R,blockhash:b.blockhash,lastValidBlockHeight:b.lastValidBlockHeight},"confirmed");if(U.value.err)throw console.error("Failed to confirm this transaction:",U.value.err),new Error(`Transaction failed: ${JSON.stringify(U.value.err)}`);try{await fetch(`${p}/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&&(f=c.error);let E=new FormData;r.forEach(s=>E.append("file",s));let h;if(u?h=await fetch(`${p}/api/user/upload-files?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}):h=await fetch(`${p}/api/user/upload-file?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}),!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 m=await h?.json();return{signature:R,success:!0,cid:c.cid,url:m.object.url,message:m.object.message,fileInfo:m.object?{filename:m.object.fileInfo?.filename||"",size:m?.object?.fileInfo?.size||0,uploadedAt:m?.object?.fileInfo?.uploadedAt||"",type:m?.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(`${p}/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(`${p}/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 d=await i.json().catch(()=>({}));throw new Error(d.message||"Failed to create renewal transaction")}let a=await i.json(),u=new l.Transaction;a.instructions.forEach(d=>{u.add({programId:new l.PublicKey(d.programId),keys:d.keys.map(w=>({pubkey:new l.PublicKey(w.pubkey),isSigner:w.isSigner,isWritable:w.isWritable})),data:Buffer.from(d.data,"base64")})});let{blockhash:f}=await t.getLatestBlockhash();u.recentBlockhash=f,u.feePayer=o;let y=await n(u),c=await t.sendRawTransaction(y.serialize());return await t.confirmTransaction(c,"confirmed"),(await fetch(`${p}/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 on backend"),{success:!0,cid:r,signature:c,url:`https://w3s.link/ipfs/${r}`,message:"Storage renewed successfully"}}async function x(r,e={}){if(!r||typeof r!="string")throw new Error("User address is required and must be a string");let o=e.url||p;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 N=(t=>(t.mainnet="mainnet-beta",t.testnet="testnet",t.devnet="devnet",t))(N||{});function $(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.estimateStorageCost=(e,o)=>{let n=e.reduce((u,f)=>u+f.size,0),i=v(n,1e3,o);return{sol:i/j,lamports:i}};this.rpcUrl=$(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 C.Connection(this.rpcUrl,"confirmed");return await D({file:o,duration:t*O,payer:e,connection:a,signTransaction:n,userEmail:i})}async getUserUploadHistory(e){return await x(e)}async getStorageRenewalCost(e,o){return await I(e,o)}async renewStorageDuration({cid:e,duration:o,payer:t,signTransaction:n}){let i=new C.Connection(this.rpcUrl,"confirmed");return await k({cid:e,duration:o,payer:t,connection:i,signTransaction:n})}};var q=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
@@ -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,eAAsBC,EACpBC,EACAC,EAAyB,CAAC,EACO,CAEjC,GAAI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AHCA,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, Transaction } from '@solana/web3.js';\nimport {\n DAY_TIME_IN_SECONDS,\n getAmountInLamports,\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\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 * @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 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 = getAmountInLamports(\n fileSizeInBytes,\n ratePerBytePerDay,\n duration\n );\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","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\n/** 1 SOL in Lamports */\nexport const ONE_BILLION_LAMPORTS = 1_000_000_000;\n\n/**\n * Get amount in Lamports\n * @param fileSize - size of the file\n * @param rate - rate per byte of a file per day\n * @param duration - storage duration\n * @returns\n */\nexport const getAmountInLamports = (\n fileSize: number,\n rate: number,\n duration: number\n): number => {\n const amountInLamports = fileSize * duration * rate;\n return amountInLamports;\n};\n","import { Signature } from '@solana/kit';\nimport {\n PublicKey,\n Transaction,\n TransactionInstruction,\n SendTransactionError,\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 on backend');\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 backend\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 */\nexport { useUpload as useDeposit };\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,4BAAAC,EAAA,2BAAAA,EAAA,cAAAC,EAAA,0BAAAC,EAAA,yBAAAF,EAAA,oBAAAG,EAAA,eAA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Aa,CAGlB,YAAYC,EAAwB,CAkDpC,yBAAsB,CAACC,EAAcC,IAAqB,CAExD,IAAMC,EAAkBF,EAAK,OAAO,CAACG,EAAK,IAAMA,EAAM,EAAE,KAAM,CAAC,EACzDC,EAAgBC,EACpBH,EACA,IACAD,CACF,EAGA,MAAO,CACL,IAHeG,EAAgBE,EAI/B,SAAUF,CACZ,CACF,EA/DE,KAAK,OAASR,EAAUG,EAAQ,WAAW,CAC7C,CAuBA,MAAM,cAAc,CAClB,MAAAQ,EACA,KAAAP,EACA,aAAAQ,EACA,gBAAAC,EACA,UAAAC,CACF,EAAwC,CACtC,QAAQ,IAAI,iDAAkD,KAAK,MAAM,EACzE,IAAMC,EAAa,IAAI,aAAW,KAAK,OAAQ,WAAW,EAE1D,OAAO,MAAMC,EAAiB,CAC5B,KAAAZ,EACA,SAAUQ,EAAeK,EACzB,MAAAN,EACA,WAAAI,EACA,gBAAAF,EACA,UAAAC,CACF,CAAC,CACH,CAuBA,MAAM,qBAAqBI,EAAqB,CAE9C,OADiB,MAAMC,EAAqBD,CAAW,CAEzD,CAcA,MAAM,sBACJE,EACAf,EACoC,CACpC,OAAO,MAAMgB,EAAsBD,EAAKf,CAAQ,CAClD,CAsBA,MAAM,qBAAqB,CACzB,IAAAe,EACA,SAAAf,EACA,MAAAM,EACA,gBAAAE,CACF,EAAgD,CAC9C,IAAME,EAAa,IAAI,aAAW,KAAK,OAAQ,WAAW,EAE1D,OAAO,MAAMO,EAAgB,CAC3B,IAAAF,EACA,SAAAf,EACA,MAAAM,EACA,WAAAI,EACA,gBAAAF,CACF,CAAC,CACH,CACF,EI5LO,IAAMU,EAAaC,GACT,IAAIC,EAAO,CAAE,YAAaD,GAAe,SAAU,CAAC","names":["index_exports","__export","Client","Environment","createDepositTxn","getUserUploadHistory","getRpcUrl","getStorageRenewalCost","renewStorageTxn","useUpload","__toCommonJS","import_web3","NODE_ENV","ENDPOINT","DAY_TIME_IN_SECONDS","ONE_BILLION_LAMPORTS","getAmountInLamports","fileSize","rate","duration","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","file","duration","fileSizeInBytes","acc","totalLamports","getAmountInLamports","ONE_BILLION_LAMPORTS","payer","durationDays","signTransaction","userEmail","connection","createDepositTxn","DAY_TIME_IN_SECONDS","userAddress","getUserUploadHistory","cid","getStorageRenewalCost","renewStorageTxn","useUpload","environment","Client"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
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
5
  /** URL pointing to the backend (mostly Storacha's) */
@@ -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 deposit history entry from the backend
159
+ * Individual upload history entry from the server
125
160
  */
126
- interface DepositHistoryEntry {
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 DepositHistoryResponse {
164
- /** Array of deposit history entries */
165
- userHistory: DepositHistoryEntry[] | null;
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 DepositParams extends Pick<CreateDepositArgs, 'signTransaction' | 'userEmail'> {
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,7 +313,7 @@ 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, }: DepositParams): Promise<UploadResult>;
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
@@ -222,9 +323,45 @@ declare class Client {
222
323
  sol: number;
223
324
  lamports: number;
224
325
  };
225
- getUserUploadHistory(userAddress: string): Promise<DepositHistoryResponse>;
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>;
226
361
  }
227
362
 
363
+ declare const useUpload: (environment: ClientOptions["environment"]) => Client;
364
+
228
365
  /**
229
366
  * Calls the deposit API for on-chain storage and returns a Transaction
230
367
  * which must be signed and sent externally by the user.
@@ -239,24 +376,56 @@ declare class Client {
239
376
  * @returns Transaction
240
377
  */
241
378
  declare function createDepositTxn({ file, duration, payer, connection, signTransaction, userEmail, }: CreateDepositArgs): Promise<UploadResult>;
242
-
243
- declare const useDeposit: (environment: ClientOptions["environment"]) => Client;
379
+ /**
380
+ * Get cost estimate for renewing storage duration
381
+ *
382
+ * @param {string} cid - Content identifier of the uploaded data to renew
383
+ * @param {number} duration - Number of additional days to extend storage
384
+ *
385
+ * @example
386
+ * const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
387
+ * console.log(`Renewal cost: ${quote.costInSOL} SOL`);
388
+ *
389
+ * @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
390
+ */
391
+ declare function getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
392
+ /**
393
+ * Renew storage for an existing deposit
394
+ *
395
+ * @param {Object} params
396
+ * @param {string} params.cid - Content identifier of the uploaded data to renew
397
+ * @param {number} params.duration - Number of additional days to extend storage
398
+ * @param {PublicKey} params.payer - Wallet public key paying for the renewal
399
+ * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
400
+ *
401
+ * @example
402
+ * const { publicKey, signTransaction } = useSolanaWallet();
403
+ * const result = await client.renewStorage({
404
+ * cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
405
+ * additionalDays: 30,
406
+ * payer: publicKey,
407
+ * signTransaction,
408
+ * });
409
+ *
410
+ * @returns {Promise<UploadResult>} Result of the renewal transaction
411
+ */
412
+ declare function renewStorageTxn({ cid, duration, payer, connection, signTransaction, }: RenewStorageDurationArgs): Promise<UploadResult>;
244
413
 
245
414
  /**
246
- * Fetches the deposit history for a given user address from the backend
415
+ * Get the upload history for a given user address from the backend
247
416
  *
248
- * @param userAddress - The wallet address of the user to fetch deposit history for
417
+ * @param userAddress - The wallet address of the user to fetch upload history for
249
418
  * @param options - Optional server configuration
250
- * @returns Promise<DepositHistoryResponse> - The user's deposit history
419
+ * @returns Promise<UploadHistoryResponse> - The user's upload history
251
420
  *
252
421
  * @example
253
422
  * ```typescript
254
- * const history = await fetchUserDepositHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
255
- * console.log('User deposit history:', history.userHistory);
423
+ * const history = await getUserUploadHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
424
+ * console.log('User upload history:', history.userHistory);
256
425
  * ```
257
426
  *
258
427
  * @throws {Error} When the user address is invalid or the request fails
259
428
  */
260
- declare function fetchUserDepositHistory(userAddress: string, options?: ServerOptions): Promise<DepositHistoryResponse>;
429
+ declare function getUserUploadHistory(userAddress: string, options?: ServerOptions): Promise<UploadHistoryResponse>;
261
430
 
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 };
431
+ 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,5 +1,5 @@
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
5
  /** URL pointing to the backend (mostly Storacha's) */
@@ -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 deposit history entry from the backend
159
+ * Individual upload history entry from the server
125
160
  */
126
- interface DepositHistoryEntry {
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 DepositHistoryResponse {
164
- /** Array of deposit history entries */
165
- userHistory: DepositHistoryEntry[] | null;
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 DepositParams extends Pick<CreateDepositArgs, 'signTransaction' | 'userEmail'> {
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,7 +313,7 @@ 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, }: DepositParams): Promise<UploadResult>;
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
@@ -222,9 +323,45 @@ declare class Client {
222
323
  sol: number;
223
324
  lamports: number;
224
325
  };
225
- getUserUploadHistory(userAddress: string): Promise<DepositHistoryResponse>;
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>;
226
361
  }
227
362
 
363
+ declare const useUpload: (environment: ClientOptions["environment"]) => Client;
364
+
228
365
  /**
229
366
  * Calls the deposit API for on-chain storage and returns a Transaction
230
367
  * which must be signed and sent externally by the user.
@@ -239,24 +376,56 @@ declare class Client {
239
376
  * @returns Transaction
240
377
  */
241
378
  declare function createDepositTxn({ file, duration, payer, connection, signTransaction, userEmail, }: CreateDepositArgs): Promise<UploadResult>;
242
-
243
- declare const useDeposit: (environment: ClientOptions["environment"]) => Client;
379
+ /**
380
+ * Get cost estimate for renewing storage duration
381
+ *
382
+ * @param {string} cid - Content identifier of the uploaded data to renew
383
+ * @param {number} duration - Number of additional days to extend storage
384
+ *
385
+ * @example
386
+ * const quote = await client.getRenewalQuote('bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', 30);
387
+ * console.log(`Renewal cost: ${quote.costInSOL} SOL`);
388
+ *
389
+ * @returns {Promise<StorageRenewalCost | null>} Cost breakdown and expiration details
390
+ */
391
+ declare function getStorageRenewalCost(cid: string, duration: number): Promise<StorageRenewalCost | null>;
392
+ /**
393
+ * Renew storage for an existing deposit
394
+ *
395
+ * @param {Object} params
396
+ * @param {string} params.cid - Content identifier of the uploaded data to renew
397
+ * @param {number} params.duration - Number of additional days to extend storage
398
+ * @param {PublicKey} params.payer - Wallet public key paying for the renewal
399
+ * @param {(tx: Transaction) => Promise<Transaction>} params.signTransaction - Transaction signing callback
400
+ *
401
+ * @example
402
+ * const { publicKey, signTransaction } = useSolanaWallet();
403
+ * const result = await client.renewStorage({
404
+ * cid: 'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
405
+ * additionalDays: 30,
406
+ * payer: publicKey,
407
+ * signTransaction,
408
+ * });
409
+ *
410
+ * @returns {Promise<UploadResult>} Result of the renewal transaction
411
+ */
412
+ declare function renewStorageTxn({ cid, duration, payer, connection, signTransaction, }: RenewStorageDurationArgs): Promise<UploadResult>;
244
413
 
245
414
  /**
246
- * Fetches the deposit history for a given user address from the backend
415
+ * Get the upload history for a given user address from the backend
247
416
  *
248
- * @param userAddress - The wallet address of the user to fetch deposit history for
417
+ * @param userAddress - The wallet address of the user to fetch upload history for
249
418
  * @param options - Optional server configuration
250
- * @returns Promise<DepositHistoryResponse> - The user's deposit history
419
+ * @returns Promise<UploadHistoryResponse> - The user's upload history
251
420
  *
252
421
  * @example
253
422
  * ```typescript
254
- * const history = await fetchUserDepositHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
255
- * console.log('User deposit history:', history.userHistory);
423
+ * const history = await getUserUploadHistory('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM');
424
+ * console.log('User upload history:', history.userHistory);
256
425
  * ```
257
426
  *
258
427
  * @throws {Error} When the user address is invalid or the request fails
259
428
  */
260
- declare function fetchUserDepositHistory(userAddress: string, options?: ServerOptions): Promise<DepositHistoryResponse>;
429
+ declare function getUserUploadHistory(userAddress: string, options?: ServerOptions): Promise<UploadHistoryResponse>;
261
430
 
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 };
431
+ 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 C}from"@solana/web3.js";var{NODE_ENV:x}=process.env,l=x==="development"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",P=86400;async function U(r,s={}){if(!r||typeof r!="string")throw new Error("User address is required and must be a string");let n=s.url||l;try{let e=await fetch(`${n}/api/user/user-upload-history?userAddress=${encodeURIComponent(r)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok){let a=await e.json().catch(()=>({}));throw new Error(a.message||`Failed to fetch deposit history: ${e.status} ${e.statusText}`)}let i=await e.json();if(typeof i!="object"||i===null)throw new Error("Invalid response format from server");if(typeof i.userAddress!="string")throw new Error("Invalid userAddress in response");return i}catch(e){throw e instanceof Error?e:new Error("Unknown error occurred while fetching deposit history")}}import{PublicKey as S,Transaction as O,TransactionInstruction as R}from"@solana/web3.js";async function k({file:r,duration:s,payer:n,connection:e,signTransaction:i,userEmail:a}){try{let t=new FormData;r.forEach(o=>t.append("file",o)),t.append("duration",s.toString()),t.append("publicKey",n.toBase58()),a&&t.append("userEmail",a);let u=r.length>1,h,E=await fetch(`${l}/api/solana/deposit`,{method:"POST",body:t});if(!E.ok)throw new Error("Failed to get deposit instructions");let c=await E.json();if(!c.instructions||!c.instructions.length)throw new Error("No instructions from deposit API");let w=await e.getLatestBlockhash("confirmed"),g=c.instructions[0],v=new R({programId:new S(g.programId),keys:g.keys.map(o=>({pubkey:new S(o.pubkey),isSigner:o.isSigner,isWritable:o.isWritable})),data:Buffer.from(g.data,"base64")}),m=new O;m.recentBlockhash=w.blockhash,m.feePayer=n,m.add(v);let T=await i(m),y=await e.sendRawTransaction(T.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"}),D=await e.confirmTransaction({signature:y,blockhash:w.blockhash,lastValidBlockHeight:w.lastValidBlockHeight},"confirmed");if(D.value.err)throw console.error("Failed to confirm this transaction:",D.value.err),new Error(`Transaction failed: ${JSON.stringify(D.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:y})})}catch(o){console.warn("Failed to update transaction hash:",o)}c.error&&(h=c.error);let b=new FormData;r.forEach(o=>b.append("file",o));let d;if(u?d=await fetch(`${l}/api/user/upload-files?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:b}):d=await fetch(`${l}/api/user/upload-file?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:b}),!d.ok){let o="Unknown error";try{let I=await d.json();o=I.message||I.error||o}catch{}throw new Error("Deposit API error: "+o)}let p=await d?.json();return{signature:y,success:!0,cid:c.cid,url:p.object.url,message:p.object.message,fileInfo:p.object?{filename:p.object.fileInfo?.filename||"",size:p?.object?.fileInfo?.size||0,uploadedAt:p?.object?.fileInfo?.uploadedAt||"",type:p?.object?.fileInfo?.type||""}:void 0}}catch(t){return console.error(t),t instanceof Error&&(console.error("Error name:",t.name),console.error("Error message:",t.message),console.error("Error stack:",t.stack)),{signature:"",success:!1,cid:"",url:"",message:"",fileInfo:void 0,error:t instanceof Error?t.message:"Unknown error occurred"}}}var j=(e=>(e.mainnet="mainnet-beta",e.testnet="testnet",e.devnet="devnet",e))(j||{});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 f=class{constructor(s){this.estimateStorageCost=(s,n)=>{let a=s.reduce((u,h)=>u+h.size,0)*n*1e3;return{sol:a/1e9,lamports:a}};this.rpcUrl=N(s.environment)}async createDeposit({payer:s,file:n,durationDays:e,signTransaction:i,userEmail:a}){console.log("Creating deposit transaction with environment:",this.rpcUrl);let t=new C(this.rpcUrl,"confirmed");return await k({file:n,duration:e*P,payer:s,connection:t,signTransaction:i,userEmail:a})}async getUserUploadHistory(s){return await U(s)}};var Y=r=>new f({environment:r||"testnet"});export{f as Client,j as Environment,k as createDepositTxn,U as fetchUserDepositHistory,N as getRpcUrl,Y as useDeposit};
1
+ import{Connection as v}from"@solana/web3.js";var{NODE_ENV:A}=process.env,l=A==="development"?"http://localhost:5040":"https://storacha-solana-sdk-bshc.onrender.com",P=86400,D=1e9,I=(o,r,t)=>o*t*r;import{PublicKey as S,Transaction as k,TransactionInstruction as B,SendTransactionError as L}from"@solana/web3.js";async function x({file:o,duration:r,payer:t,connection:e,signTransaction:i,userEmail:s}){try{let n=new FormData;o.forEach(a=>n.append("file",a)),n.append("duration",r.toString()),n.append("publicKey",t.toBase58()),s&&n.append("userEmail",s);let d=o.length>1,m,h=await fetch(`${l}/api/solana/deposit`,{method:"POST",body:n});if(!h.ok)throw new Error("Failed to get deposit instructions");let c=await h.json();if(!c.instructions||!c.instructions.length)throw new Error("No instructions from deposit API");let g=await e.getLatestBlockhash("confirmed"),p=c.instructions[0],f=new B({programId:new S(p.programId),keys:p.keys.map(a=>({pubkey:new S(a.pubkey),isSigner:a.isSigner,isWritable:a.isWritable})),data:Buffer.from(p.data,"base64")}),y=new k;y.recentBlockhash=g.blockhash,y.feePayer=t,y.add(f);let N=await i(y),b;try{b=await e.sendRawTransaction(N.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"})}catch(a){throw a instanceof L?(a.logs??[]).some($=>$.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 U=await e.confirmTransaction({signature:b,blockhash:g.blockhash,lastValidBlockHeight:g.lastValidBlockHeight},"confirmed");if(U.value.err)throw console.error("Failed to confirm this transaction:",U.value.err),new Error(`Transaction failed: ${JSON.stringify(U.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:b})})}catch(a){console.warn("Failed to update transaction hash:",a)}c.error&&(m=c.error);let E=new FormData;o.forEach(a=>E.append("file",a));let w;if(d?w=await fetch(`${l}/api/user/upload-files?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}):w=await fetch(`${l}/api/user/upload-file?cid=${encodeURIComponent(c.cid)}`,{method:"POST",body:E}),!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:b,success:!0,cid:c.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,r){try{let t=await fetch(`${l}/api/user/renewal-cost?cid=${encodeURIComponent(o)}&duration=${r}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok){let e=await t.json();throw new Error(e.message||"Failed to get storage renewal cost")}return await t.json()}catch(t){return console.error("Failed to get storage renewal cost",t),null}}async function O({cid:o,duration:r,payer:t,connection:e,signTransaction:i}){let s=await fetch(`${l}/api/user/renew-storage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:o,duration:r,publicKey:t.toString()})});if(!s.ok){let p=await s.json().catch(()=>({}));throw new Error(p.message||"Failed to create renewal transaction")}let n=await s.json(),d=new k;n.instructions.forEach(p=>{d.add({programId:new S(p.programId),keys:p.keys.map(f=>({pubkey:new S(f.pubkey),isSigner:f.isSigner,isWritable:f.isWritable})),data:Buffer.from(p.data,"base64")})});let{blockhash:m}=await e.getLatestBlockhash();d.recentBlockhash=m,d.feePayer=t;let h=await i(d),c=await e.sendRawTransaction(h.serialize());return await e.confirmTransaction(c,"confirmed"),(await fetch(`${l}/api/user/confirm-renewal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:o,duration:r,transactionHash:c})})).ok||console.error("Failed to confirm renewal on backend"),{success:!0,cid:o,signature:c,url:`https://w3s.link/ipfs/${o}`,message:"Storage renewed successfully"}}async function j(o,r={}){if(!o||typeof o!="string")throw new Error("User address is required and must be a string");let t=r.url||l;try{let e=await fetch(`${t}/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 i=await e.json();if(typeof i!="object"||i===null)throw new Error("Invalid response format from server");if(typeof i.userAddress!="string")throw new Error("Invalid userAddress in response");return i}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 _(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(r){this.estimateStorageCost=(r,t)=>{let i=r.reduce((d,m)=>d+m.size,0),s=I(i,1e3,t);return{sol:s/D,lamports:s}};this.rpcUrl=_(r.environment)}async createDeposit({payer:r,file:t,durationDays:e,signTransaction:i,userEmail:s}){console.log("Creating deposit transaction with environment:",this.rpcUrl);let n=new v(this.rpcUrl,"confirmed");return await x({file:t,duration:e*P,payer:r,connection:n,signTransaction:i,userEmail:s})}async getUserUploadHistory(r){return await j(r)}async getStorageRenewalCost(r,t){return await C(r,t)}async renewStorageDuration({cid:r,duration:t,payer:e,signTransaction:i}){let s=new v(this.rpcUrl,"confirmed");return await O({cid:r,duration:t,payer:e,connection:s,signTransaction:i})}};var oe=o=>new R({environment:o||"testnet"});export{R as Client,F as Environment,x as createDepositTxn,j as fetchUserDepositHistory,j as fetchUserUploadHistory,_ as getRpcUrl,C as getStorageRenewalCost,j as getUserUploadHistory,O as renewStorageTxn,oe as useDeposit,oe 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.4",
3
+ "version": "0.0.5",
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
- "esbuild": "^0.21.4",
47
+ "knip": "^5.72.0",
47
48
  "tsup": "^8.5.0",
48
49
  "typescript": "^5.8.3"
49
50
  }