UNPKG

revshare-sdk

Version:

JavaScript SDK for RevShare Public API - Create bonding curve tokens with distribution features

2 lines (1 loc) 9.12 kB
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("@solana/web3.js")):"function"==typeof define&&define.amd?define(["exports","@solana/web3.js"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).RevShareSDK={},e.SolanaWeb3)}(this,function(e,n){"use strict";class o extends Error{constructor(e,n=0,o=null,t=null){super(e),this.name="RevShareError",this.status=n,this.details=o,this.originalError=t}}class t{constructor(e={}){this.baseUrl="https://public-api.revshare.dev",this.timeout=e.timeout||3e4,this.headers={"Content-Type":"application/json",...e.headers}}async _request(e,n={}){const t=`${this.baseUrl}${e}`,s={method:"GET",headers:this.headers,timeout:this.timeout,...n};if("GET"===s.method&&n.params){const e=new URLSearchParams;Object.entries(n.params).forEach(([n,o])=>{null!=o&&e.append(n,o)});const o=e.toString();s.url=o?`${t}?${o}`:t}else s.url=t;try{const e=await fetch(s.url,s),n=await e.json();if(!e.ok)throw new o(n.error||`HTTP ${e.status}`,e.status,n);return n}catch(e){if(e instanceof o)throw e;throw new o(e.message||"Network error",0,null,e)}}_checkSolanaWeb3(){if("undefined"!=typeof window&&window.solana)return window.solana;try{return{Connection:n.Connection,PublicKey:n.PublicKey,Transaction:n.Transaction,SystemProgram:n.SystemProgram,LAMPORTS_PER_SOL:n.LAMPORTS_PER_SOL}}catch(e){throw new o("Solana web3.js is required. Please install: npm install @solana/web3.js",0)}}_getConnection(){const{Connection:e}=this._checkSolanaWeb3();return new e("https://api.mainnet-beta.solana.com","confirmed")}async _handleFunding(e,n,t){const{Connection:s,PublicKey:r,Transaction:a,SystemProgram:i,LAMPORTS_PER_SOL:l}=this._checkSolanaWeb3(),c=new s("https://api.mainnet-beta.solana.com","confirmed"),u=e.publicKey,d=new r(n),g=Math.round(t*l),p=await c.getBalance(u),m=Math.round(g+5e-6*l);if(p<m)throw new o(`Insufficient balance. Required: ${m/l} SOL, Available: ${p/l} SOL`,400);const h=(new a).add(i.transfer({fromPubkey:u,toPubkey:d,lamports:g})),b=await c.sendTransaction(h,[e]);return await c.confirmTransaction(b),b}async createBondingToken(e){const{keypair:n,developerWallet:t,name:s,ticker:r,description:a,imageUrl:i,website:l="",twitter:c="",telegram:u="",visible:d=0,decimals:g=9,taxTier:p=0,initialBuy:m=0,reward_ca:h="So11111111111111111111111111111111111111112",mode:b=0,dev_fee_percentage:y=50,bondingCurveType:w=1,ref:f}=e;if(!(n&&t&&s&&r&&a&&i))throw new o("Missing required parameters. Required: keypair, developerWallet, name, ticker, description, imageUrl",400);try{console.log("🚀 Starting all-in-one token creation..."),console.log("📋 Step 1: Preparing token creation...");const e=await this._request("/prepare",{method:"POST"});console.log("✅ Preparation successful!"),console.log("Request ID:",e.request_id),console.log("Funding wallet:",e.funding_wallet),console.log("Amount to fund:",e.amount_to_fund,"SOL"),console.log("💰 Step 2: Handling funding...");const o=e.amount_to_fund+m;m>0&&(console.log("📊 Funding breakdown:"),console.log(` - Service fees: ${e.amount_to_fund} SOL`),console.log(` - Initial buy: ${m} SOL`),console.log(` - Total: ${o} SOL`));const S=await this._handleFunding(n,e.funding_wallet,o);console.log("✅ Funding successful!"),console.log("Funding transaction:",S),console.log("🎯 Step 3: Creating token...");const _=await this._request("/create",{method:"POST",body:JSON.stringify({request_id:e.request_id,name:s,ticker:r,description:a,imageUrl:i,developerWallet:t,website:l,twitter:c,telegram:u,visible:d,decimals:g,taxTier:p,buyAmount:m,reward_ca:h,mode:b,dev_fee_percentage:y,bondingCurveType:w,ref:f})});return console.log("✅ Token creation successful!"),{success:!0,prepare:e,funding:{signature:S,amount:o,serviceFees:e.amount_to_fund,initialBuy:m,wallet:e.funding_wallet},create:_,summary:{request_id:e.request_id,mintAddress:_.mintAddress,txSignature:_.txSignature,fundingSignature:S,developerWallet:t}}}catch(e){throw console.error("❌ Token creation failed:",e.message),e}}async prepare(){return this._request("/prepare",{method:"POST"})}async create(e){const{request_id:n,name:t,ticker:s,description:r,imageUrl:a,developerWallet:i,website:l="",twitter:c="",telegram:u="",visible:d=0,decimals:g=9,taxTier:p=0,initialBuy:m=0,reward_ca:h="So11111111111111111111111111111111111111112",mode:b=0,dev_fee_percentage:y=50,bondingCurveType:w=1,ref:f}=e;if(!(n&&t&&s&&r&&a&&i))throw new o("Missing required parameters. Required: request_id, name, ticker, description, imageUrl, developerWallet",400);return this._request("/create",{method:"POST",body:JSON.stringify({request_id:n,name:t,ticker:s,description:r,imageUrl:a,developerWallet:i,website:l,twitter:c,telegram:u,visible:d,decimals:g,taxTier:p,buyAmount:m,reward_ca:h,mode:b,dev_fee_percentage:y,bondingCurveType:w,ref:f})})}async health(){return this._request("/health")}async docs(){return this._request("/docs")}async getBondingCurveProgress(e){const{tokenAddress:n,rpcUrl:t}=e;if(!n)throw new o("Missing required parameters. Required: tokenAddress",400);try{console.log("📊 Getting bonding curve progress..."),console.log(`Token: ${n}`),t&&console.log(`RPC: ${t}`);const e={tokenAddress:n};t&&(e.rpcUrl=t);const o=await this._request("/bonding-curve-progress",{method:"GET",params:e});return console.log("✅ Bonding curve progress retrieved successfully!"),{success:!0,tokenAddress:n,poolId:o.poolId,progress:o.progress,migrationThreshold:o.migrationThreshold,message:o.message}}catch(e){throw console.error("❌ Failed to get bonding curve progress:",e.message),e}}async buildBondingCurveBuyTransaction(e){const{tokenAddress:n,amount:t,buyerWallet:s,slippageBps:r=500,rpcUrl:a}=e;if(!n||!t||!s)throw new o("Missing required parameters. Required: tokenAddress, amount, buyerWallet",400);try{console.log("🛒 Building bonding curve buy transaction..."),console.log(`Bonding Token: ${n}`),console.log(`Amount: ${t} SOL`),console.log(`Buyer: ${s}`),console.log(`Slippage: ${r} bps`),a&&console.log(`RPC: ${a}`);const e={tokenAddress:n,action:"buy",amount:t,buyerWallet:s,slippageBps:r};a&&(e.rpcUrl=a);const o=await this._request("/swap-bonding-curve",{method:"POST",body:JSON.stringify(e)});return console.log("✅ Bonding curve buy transaction built successfully!"),{success:!0,action:"buy",tokenType:"bonding-curve",tokenAddress:n,amount:t,buyerWallet:s,slippageBps:r,poolId:o.poolId,quote:o.quote,transaction:o.transaction,expectedTokens:o.quote?.amountOutFormatted,transactionBase64:o.transaction}}catch(e){throw console.error("❌ Bonding curve buy transaction build failed:",e.message),e}}async buildBondingCurveSellTransaction(e){const{tokenAddress:n,amount:t,sellerWallet:s,slippageBps:r=500,rpcUrl:a}=e;if(!n||!t||!s)throw new o("Missing required parameters. Required: tokenAddress, amount, sellerWallet",400);try{console.log("💸 Building bonding curve sell transaction..."),console.log(`Bonding Token: ${n}`),console.log(`Amount: ${t} tokens`),console.log(`Seller: ${s}`),console.log(`Slippage: ${r} bps`),a&&console.log(`RPC: ${a}`);const e={tokenAddress:n,action:"sell",amount:t,buyerWallet:s,slippageBps:r};a&&(e.rpcUrl=a);const o=await this._request("/swap-bonding-curve",{method:"POST",body:JSON.stringify(e)});return console.log("✅ Bonding curve sell transaction built successfully!"),{success:!0,action:"sell",tokenType:"bonding-curve",tokenAddress:n,amount:t,sellerWallet:s,slippageBps:r,poolId:o.poolId,quote:o.quote,transaction:o.transaction,expectedSOL:o.quote?.amountOutFormatted,transactionBase64:o.transaction}}catch(e){throw console.error("❌ Bonding curve sell transaction build failed:",e.message),e}}async executeBondingCurveSwap(e){const{tokenAddress:n,action:t,amount:s,keypair:r,slippageBps:a=500,rpcUrl:i}=e;if(!(n&&t&&s&&r))throw new o("Missing required parameters. Required: tokenAddress, action, amount, keypair",400);if(!["buy","sell"].includes(t))throw new o('Action must be either "buy" or "sell"',400);try{console.log(`🔄 Executing bonding curve ${t} swap...`),console.log(`Bonding Token: ${n}`),console.log(`Amount: ${s} ${"buy"===t?"SOL":"tokens"}`),console.log(`Wallet: ${r.publicKey.toString()}`),i&&console.log(`RPC: ${i}`);const e={tokenAddress:n,amount:s,slippageBps:a,["buy"===t?"buyerWallet":"sellerWallet"]:r.publicKey.toString()};i&&(e.rpcUrl=i);const o="buy"===t?await this.buildBondingCurveBuyTransaction(e):await this.buildBondingCurveSellTransaction(e),{Transaction:l}=this._checkSolanaWeb3(),c=this._getConnection(),u=l.from(Buffer.from(o.transactionBase64,"base64"));u.sign(r);const d=await c.sendTransaction(u,[r]);return await c.confirmTransaction(d),console.log("✅ Bonding curve swap executed successfully!"),console.log(`Transaction signature: ${d}`),{success:!0,action:t,tokenType:"bonding-curve",tokenAddress:n,amount:s,wallet:r.publicKey.toString(),slippageBps:a,poolId:o.poolId,quote:o.quote,transactionSignature:d,expectedOutput:"buy"===t?o.expectedTokens:o.expectedSOL}}catch(e){throw console.error(`❌ Bonding curve ${t} swap failed:`,e.message),e}}}e.RevShareError=o,e.RevShareSDK=t,e.default=t,Object.defineProperty(e,"__esModule",{value:!0})});