deploy-sdk-js 0.0.2 → 0.0.4
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 +12 -6
- package/dist/chunk-7DA3UKXC.mjs +1 -0
- package/dist/chunk-C52RGN2Q.mjs +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/wallet-adapters/index.d.mts +16 -12
- package/dist/wallet-adapters/index.d.ts +16 -12
- package/dist/wallet-adapters/index.js +1 -1
- package/dist/wallet-adapters/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,20 +16,26 @@ npm install deploy-sdk-js ethers
|
|
|
16
16
|
|
|
17
17
|
### 1. Initialize SDK with Privy
|
|
18
18
|
|
|
19
|
+
Pass a **connected wallet** from `useWallets()` (not the `usePrivy()` object). Ensure `ready` is true before initializing.
|
|
20
|
+
|
|
19
21
|
```typescript
|
|
20
|
-
import { DeploySDK, PrivyAdapter, COLLATERAL_ASSETS, STAKE_TOKENS } from 'deploy-sdk-js';
|
|
21
|
-
import {
|
|
22
|
+
import { DeploySDK, PrivyAdapter, PrivyConnectedWallet, COLLATERAL_ASSETS, STAKE_TOKENS } from 'deploy-sdk-js';
|
|
23
|
+
import { useWallets } from '@privy-io/react-auth';
|
|
22
24
|
|
|
23
25
|
function App() {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
+
const { wallets, ready } = useWallets();
|
|
26
27
|
const sdk = new DeploySDK({
|
|
27
28
|
apiUrl: 'https://your-api-url.com', // provide your backend API URL
|
|
28
29
|
chainId: 1, // Ethereum mainnet
|
|
29
30
|
});
|
|
30
31
|
|
|
31
32
|
const connectWallet = async () => {
|
|
32
|
-
|
|
33
|
+
if (!ready || !wallets.length) {
|
|
34
|
+
console.error('No wallet connected');
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const wallet = wallets[0]; // or pick by chain/address
|
|
38
|
+
const adapter = new PrivyAdapter(wallet as PrivyConnectedWallet);
|
|
33
39
|
await sdk.initialize(adapter);
|
|
34
40
|
console.log('Connected:', await sdk.getAddress());
|
|
35
41
|
};
|
|
@@ -314,4 +320,4 @@ Handles redeeming dUSD for collateral using EIP-712 signed orders.
|
|
|
314
320
|
|
|
315
321
|
## License
|
|
316
322
|
|
|
317
|
-
|
|
323
|
+
UNLICENSED
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ethers as o}from"ethers";var i=class{constructor(e){this.wallet=e;this.name="Privy"}async getProvider(){let e=await this.wallet.getEthereumProvider();if(!e||typeof e.request!="function")throw new Error("Privy wallet did not return a valid EIP-1193 provider");return new o.providers.Web3Provider(e)}async getSigner(){return(await this.getProvider()).getSigner()}async isConnected(){return!!this.wallet?.address}async switchChain(e){if(this.wallet.switchChain)await this.wallet.switchChain(e);else throw new Error("Privy wallet does not support switchChain")}};var a=class{constructor(e){this.ethereum=e;this.name="External"}async getProvider(){return this.ethereum}async getSigner(){return await this.ethereum.request({method:"eth_requestAccounts"}),this.ethereum}async isConnected(){try{return(await this.ethereum.request({method:"eth_accounts"})).length>0}catch{return!1}}async switchChain(e){let t=`0x${e.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:t}]})}catch(r){if(r.code===4902)await this.addChain(e);else throw r}}async addChain(e){let r={1:{chainId:"0x1",chainName:"Ethereum Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://eth.llamarpc.com"],blockExplorerUrls:["https://etherscan.io"]},42161:{chainId:"0xa4b1",chainName:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://arb1.arbitrum.io/rpc"],blockExplorerUrls:["https://arbiscan.io"]}}[e];if(!r)throw new Error(`Chain ${e} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[r]})}};export{i as a,a as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ethers as h}from"ethers";function a(i){return!!i&&typeof i.request=="function"}var s=class{constructor(e){this.wallet=e;this.name="Privy";this._provider=null;if(!e||typeof e.getEthereumProvider!="function")throw new Error("PrivyAdapter requires a connected wallet with getEthereumProvider (e.g. from useWallets().wallets[0])");if(!e.address||typeof e.address!="string")throw new Error("PrivyAdapter requires a wallet with an address")}async getProvider(){if(this._provider)return this._provider;let e=await this.wallet.getEthereumProvider();if(!a(e))throw new Error("Privy wallet did not return a valid EIP-1193 provider");return this._provider=new h.providers.Web3Provider(e),this._provider}async getSigner(){return(await this.getProvider()).getSigner()}async isConnected(){if(!this.wallet?.address)return!1;try{let e=await this.wallet.getEthereumProvider();if(!a(e))return!1;let t=await e.request({method:"eth_accounts"});if(!Array.isArray(t)||t.length===0)return!1;let r=this.wallet.address.toLowerCase();return t.some(o=>(o||"").toLowerCase()===r)}catch{return!1}}async switchChain(e){if(this.wallet.switchChain)await this.wallet.switchChain(e),this._provider=null;else throw new Error("Privy wallet does not support switchChain")}};var n=class{constructor(e){this.ethereum=e;this.name="External"}async getProvider(){return this.ethereum}async getSigner(){return await this.ethereum.request({method:"eth_requestAccounts"}),this.ethereum}async isConnected(){try{return(await this.ethereum.request({method:"eth_accounts"})).length>0}catch{return!1}}async switchChain(e){let t=`0x${e.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:t}]})}catch(r){if(r.code===4902)await this.addChain(e);else throw r}}async addChain(e){let r={1:{chainId:"0x1",chainName:"Ethereum Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://eth.llamarpc.com"],blockExplorerUrls:["https://etherscan.io"]},42161:{chainId:"0xa4b1",chainName:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://arb1.arbitrum.io/rpc"],blockExplorerUrls:["https://arbiscan.io"]}}[e];if(!r)throw new Error(`Chain ${e} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[r]})}};export{s as a,n as b};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { A as AllowanceService, B as BalanceService, C as CooldownResult, a as CooldownStatus, D as DeploySDK, M as MintModule, b as MintOptions, c as MintOrder, d as MintParams, e as MintResult, R as RedeemModule, f as RedeemOptions, g as RedeemOrder, h as RedeemResult, S as StakeModule, i as StakeParams, j as StakePreview, k as StakeResult, l as StakingPosition, U as UnstakeModule, m as UnstakeParams, n as UnstakeResult, D as default } from './index-B9tOEGVF.mjs';
|
|
2
2
|
import { C as CollateralAsset, S as StakeToken } from './base-DLLHDCZ5.mjs';
|
|
3
3
|
export { a as ChainId, D as DeploySDKConfig, b as SDKEvents, T as TransactionResult, W as WalletAdapter } from './base-DLLHDCZ5.mjs';
|
|
4
|
-
export { ExternalWalletAdapter, PrivyAdapter } from './wallet-adapters/index.mjs';
|
|
4
|
+
export { ExternalWalletAdapter, PrivyAdapter, PrivyConnectedWallet } from './wallet-adapters/index.mjs';
|
|
5
5
|
import 'ethers';
|
|
6
6
|
import 'eventemitter3';
|
|
7
7
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { A as AllowanceService, B as BalanceService, C as CooldownResult, a as CooldownStatus, D as DeploySDK, M as MintModule, b as MintOptions, c as MintOrder, d as MintParams, e as MintResult, R as RedeemModule, f as RedeemOptions, g as RedeemOrder, h as RedeemResult, S as StakeModule, i as StakeParams, j as StakePreview, k as StakeResult, l as StakingPosition, U as UnstakeModule, m as UnstakeParams, n as UnstakeResult, D as default } from './index-CY6ZN0n3.js';
|
|
2
2
|
import { C as CollateralAsset, S as StakeToken } from './base-DLLHDCZ5.js';
|
|
3
3
|
export { a as ChainId, D as DeploySDKConfig, b as SDKEvents, T as TransactionResult, W as WalletAdapter } from './base-DLLHDCZ5.js';
|
|
4
|
-
export { ExternalWalletAdapter, PrivyAdapter } from './wallet-adapters/index.js';
|
|
4
|
+
export { ExternalWalletAdapter, PrivyAdapter, PrivyConnectedWallet } from './wallet-adapters/index.js';
|
|
5
5
|
import 'ethers';
|
|
6
6
|
import 'eventemitter3';
|
|
7
7
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var V=Object.create;var N=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var $=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var j=(o,t)=>{for(var e in t)N(o,e,{get:t[e],enumerable:!0})},B=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of z(t))!G.call(o,n)&&n!==e&&N(o,n,{get:()=>t[n],enumerable:!(r=W(t,n))||r.enumerable});return o};var q=(o,t,e)=>(e=o!=null?V($(o)):{},B(t||!o||!o.__esModule?N(e,"default",{value:o,enumerable:!0}):e,o)),Y=o=>B(N({},"__esModule",{value:!0}),o);var J={};j(J,{AllowanceService:()=>k,BalanceService:()=>T,COLLATERAL_ASSETS:()=>O,CONTRACT_ADDRESSES:()=>h,ChainId:()=>f,DeploySDK:()=>v,DeploySDKError:()=>a,EIP712_TYPES_ORDER:()=>A,ERC20_ABI:()=>g,ERC4626_ABI:()=>m,ErrorCode:()=>p,ExternalWalletAdapter:()=>U,MINTER_ABI:()=>E,MintModule:()=>D,PrivyAdapter:()=>P,RedeemModule:()=>S,STAKE_TOKENS:()=>Z,StakeModule:()=>I,UnstakeModule:()=>b,default:()=>v});module.exports=Y(J);var K=q(require("eventemitter3"));var f=(e=>(e[e.ETHEREUM=1]="ETHEREUM",e[e.ARBITRUM=42161]="ARBITRUM",e))(f||{});var p=(l=>(l.NOT_INITIALIZED="NOT_INITIALIZED",l.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",l.INVALID_CHAIN="INVALID_CHAIN",l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",l.INSUFFICIENT_ALLOWANCE="INSUFFICIENT_ALLOWANCE",l.TRANSACTION_FAILED="TRANSACTION_FAILED",l.STAKE_FAILED="STAKE_FAILED",l.UNSTAKE_FAILED="UNSTAKE_FAILED",l.COOLDOWN_FAILED="COOLDOWN_FAILED",l.MINT_FAILED="MINT_FAILED",l.REDEEM_FAILED="REDEEM_FAILED",l.INVALID_ORDER="INVALID_ORDER",l.SIGNATURE_FAILED="SIGNATURE_FAILED",l.API_ERROR="API_ERROR",l.VALIDATION_ERROR="VALIDATION_ERROR",l))(p||{}),a=class o extends Error{constructor(t,e,r){super(e),this.name="DeploySDKError",this.code=t,this.originalError=r,Error.captureStackTrace&&Error.captureStackTrace(this,o)}toJSON(){return{name:this.name,code:this.code,message:this.message,originalError:this.originalError?.message||this.originalError}}};var F=require("ethers");var h={1:{USDC:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",USDT:"0xdac17f958d2ee523a2206206994597c13d831ec7",dUSD:"0xf42e0b98e32150fe02a370456e6479fcd94f5531",DUSD_MINTER:"0x1ee453Ea35f6EAbD9BFF126586322cbC906D4EB3",sDUSD_STAKING:"0x7f37B0133B1adC1D0647EE52eA38fA13caC4aA1B"},42161:{}},O={USDC:{key:"USDC",name:"USD Coin",symbol:"USDC",address:h[1].USDC,decimals:6,mintingContract:h[1].DUSD_MINTER},USDT:{key:"USDT",name:"Tether USD",symbol:"USDT",address:h[1].USDT,decimals:6,mintingContract:h[1].DUSD_MINTER}},Z={dUSD:{key:"dUSD",name:"Deploy USD",symbol:"dUSD",address:h[1].dUSD,decimals:18,supportedCollateral:[O.USDC,O.USDT],mintingContract:h[1].DUSD_MINTER,stakingContract:h[1].sDUSD_STAKING,stakingSymbol:"sDUSD",cooldownPeriod:2160*60*60*1e3}},A={Order:[{name:"order_id",type:"string"},{name:"order_type",type:"uint8"},{name:"expiry",type:"uint256"},{name:"nonce",type:"uint256"},{name:"benefactor",type:"address"},{name:"beneficiary",type:"address"},{name:"collateral_asset",type:"address"},{name:"collateral_amount",type:"uint256"},{name:"dAsset_amount",type:"uint256"}]},m=["function deposit(uint256 assets, address receiver) external returns (uint256 shares)","function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)","function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets)","function cooldownShares(uint256 shares) external","function cooldowns(address user) external view returns (uint256 cooldownEnd, uint256 underlyingAmount)","function balanceOf(address owner) external view returns (uint256)","function convertToShares(uint256 assets) external view returns (uint256)","function convertToAssets(uint256 shares) external view returns (uint256)","function totalAssets() external view returns (uint256)","function totalSupply() external view returns (uint256)","event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares)","event Withdraw(address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares)"],g=["function approve(address spender, uint256 amount) external returns (bool)","function allowance(address owner, address spender) external view returns (uint256)","function balanceOf(address account) external view returns (uint256)","function decimals() external view returns (uint8)","function symbol() external view returns (string)","function name() external view returns (string)","function transfer(address recipient, uint256 amount) external returns (bool)","function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)","event Approval(address indexed owner, address indexed spender, uint256 value)","event Transfer(address indexed from, address indexed to, uint256 value)"],E=["function mint(tuple(string order_id, uint8 order_type, uint256 expiry, uint256 nonce, address benefactor, address beneficiary, address collateral_asset, uint256 collateral_amount, uint256 dAsset_amount) order, tuple(address[] addresses, uint256[] ratios) route, tuple(uint8 signature_type, bytes signature_bytes) signature) external","function redeem(tuple(string order_id, uint8 order_type, uint256 expiry, uint256 nonce, address benefactor, address beneficiary, address collateral_asset, uint256 collateral_amount, uint256 dAsset_amount) order, tuple(uint8 signature_type, bytes signature_bytes) signature) external","function isWhitelistedBenefactor(address benefactor) external view returns (bool)","function addWhitelistedBenefactor(address benefactor) external","function removeWhitelistedBenefactor(address benefactor) external"];var D=class{constructor(t){this.sdk=t}async createOrder(t,e,r,n){let s=await this.sdk.getAddress(),i=crypto.randomUUID(),d=Math.floor(Date.now()/1e3)+(n?.expiryMinutes||5)*60,c=t.mintingContract;return{orderId:i,orderType:0,expiry:d,nonce:Date.now(),benefactor:n?.benefactor||s,beneficiary:n?.beneficiary||s,collateralAsset:t.address,collateralAmount:e.toString(),dAssetAmount:r.toString(),minterAddress:c}}async signOrder(t){let e=this.sdk.signer,r={name:"DeployMinting",version:"1",chainId:await this.sdk.getChainId(),verifyingContract:t.minterAddress},n={order_id:t.orderId,order_type:t.orderType,expiry:t.expiry,nonce:t.nonce,benefactor:t.benefactor,beneficiary:t.beneficiary,collateral_asset:t.collateralAsset,collateral_amount:t.collateralAmount,dAsset_amount:t.dAssetAmount};try{return await e._signTypedData(r,A,n)}catch(s){throw new a("SIGNATURE_FAILED","Failed to sign mint order",s)}}async submitOrder(t,e){try{let r=await fetch(`${this.sdk.config.apiUrl}/api/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:{order_id:t.orderId,order_type:t.orderType,expiry:t.expiry,nonce:t.nonce,benefactor:t.benefactor,beneficiary:t.beneficiary,collateral_asset:t.collateralAsset,collateral_amount:t.collateralAmount,dAsset_amount:t.dAssetAmount},signature:{signature_type:0,signature_bytes:e}})});if(!r.ok){let s=await r.json();throw new a("API_ERROR",s.message||"Failed to submit mint order")}let n=await r.json();return{success:!0,orderId:t.orderId,txHash:n.txHash,status:n.status}}catch(r){throw r instanceof a?r:new a("API_ERROR","Failed to submit mint order",r)}}async mint(t,e,r,n){try{let s=await this.createOrder(t,e,r,n),i=await this.signOrder(s);return await this.submitOrder(s,i)}catch(s){throw s instanceof a?s:new a("MINT_FAILED","Failed to mint tokens",s)}}async estimateGas(t,e,r,n){let s=new F.Contract(t.mintingContract,E,this.sdk.provider),i={order_id:crypto.randomUUID(),order_type:0,expiry:Math.floor(Date.now()/1e3)+300,nonce:Date.now(),benefactor:await this.sdk.getAddress(),beneficiary:await this.sdk.getAddress(),collateral_asset:t.address,collateral_amount:e.toString(),dAsset_amount:r.toString()};try{return(await s.estimateGas.mint(i,{addresses:[],ratios:[]},{signature_type:0,signature_bytes:n})).toBigInt()}catch(d){throw new a("TRANSACTION_FAILED","Failed to estimate gas for mint",d)}}};var u=require("ethers");var I=class{constructor(t){this.sdk=t}async stake(t){try{let{token:e,amount:r,receiver:n}=t;if(!e.stakingContract)throw new a("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let s=new u.Contract(e.stakingContract,m,this.sdk.signer),i=n||await this.sdk.getAddress(),c=await(await s.deposit(r,i)).wait(),w,y=c.events?.find(C=>C.event==="Deposit");return y&&(w=y.args?.shares?.toString()),{success:!0,txHash:c.transactionHash,sharesReceived:w}}catch(e){throw e instanceof a?e:new a("STAKE_FAILED","Failed to stake tokens",e)}}async getPosition(t,e){if(!t.stakingContract)throw new a("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let r=e||await this.sdk.getAddress(),n=new u.Contract(t.stakingContract,m,this.sdk.provider);try{let[s,i,d]=await Promise.all([n.balanceOf(r),n.convertToAssets(await n.balanceOf(r)),n.cooldowns(r).catch(()=>({cooldownEnd:u.BigNumber.from(0),underlyingAmount:u.BigNumber.from(0)}))]),c=d.cooldownEnd.toNumber()*1e3;return{tokenKey:t.key,stakedAmount:s.toString(),stakedValue:i.toString(),cooldownEnd:c>0?c:void 0,canUnstake:c===0||c<=Date.now()}}catch(s){throw new a("VALIDATION_ERROR","Failed to fetch staking position",s)}}async previewStake(t,e){if(!t.stakingContract)throw new a("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let r=new u.Contract(t.stakingContract,m,this.sdk.provider);try{return{shares:(await r.convertToShares(e)).toString(),assets:e.toString()}}catch(n){throw new a("VALIDATION_ERROR","Failed to preview stake",n)}}async getAPY(t){if(!t.stakingContract)return 0;let e=new u.Contract(t.stakingContract,m,this.sdk.provider);try{let[r,n]=await Promise.all([e.totalAssets(),e.totalSupply()]);if(n.isZero())return 0;let s=r.mul(u.BigNumber.from(10).pow(18)).div(n),i=u.BigNumber.from(10).pow(18);return s.lte(i)?0:s.sub(i).mul(365).mul(1e4).div(i).toNumber()/100}catch{return 0}}};var _=require("ethers");var b=class{constructor(t){this.sdk=t}async initiateCooldown(t,e){try{if(!t.stakingContract)throw new a("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let s=await(await new _.Contract(t.stakingContract,m,this.sdk.signer).cooldownShares(e)).wait(),i=Date.now()+(t.cooldownPeriod||2160*60*60*1e3);return{success:!0,txHash:s.transactionHash,cooldownEnd:i}}catch(r){throw r instanceof a?r:new a("COOLDOWN_FAILED","Failed to initiate cooldown",r)}}async unstake(t){try{let{token:e,sharesAmount:r,receiver:n}=t;if(!e.stakingContract)throw new a("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let s=await this.getCooldownStatus(e);if(!s.canUnstake)throw new a("VALIDATION_ERROR",`Cannot unstake. Cooldown ends at ${new Date(s.cooldownEnd).toLocaleString()}`);let i=new _.Contract(e.stakingContract,m,this.sdk.signer),d=n||await this.sdk.getAddress(),c=await this.sdk.getAddress(),y=await(await i.redeem(r,d,c)).wait(),C,L=y.events?.find(H=>H.event==="Withdraw");return L&&(C=L.args?.assets?.toString()),{success:!0,txHash:y.transactionHash,assetsWithdrawn:C}}catch(e){throw e instanceof a?e:new a("UNSTAKE_FAILED","Failed to unstake tokens",e)}}async getCooldownStatus(t,e){if(!t.stakingContract)throw new a("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let r=e||await this.sdk.getAddress(),n=new _.Contract(t.stakingContract,m,this.sdk.provider);try{let s=await n.cooldowns(r),i=s.cooldownEnd.toNumber()*1e3;return{cooldownEnd:i,sharesInCooldown:s.underlyingAmount.toString(),canUnstake:i>0&&i<=Date.now()}}catch(s){throw new a("VALIDATION_ERROR","Failed to fetch cooldown status",s)}}async previewUnstake(t,e){if(!t.stakingContract)throw new a("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let r=new _.Contract(t.stakingContract,m,this.sdk.provider);try{return(await r.convertToAssets(e)).toString()}catch(n){throw new a("VALIDATION_ERROR","Failed to preview unstake",n)}}};var M=require("ethers");var S=class{constructor(t){this.sdk=t}async createOrder(t,e,r,n,s){let i=await this.sdk.getAddress(),d=crypto.randomUUID(),c=Math.floor(Date.now()/1e3)+(s?.expiryMinutes||5)*60,w=t.mintingContract;return{orderId:d,orderType:1,expiry:c,nonce:Date.now(),benefactor:s?.benefactor||i,beneficiary:s?.beneficiary||i,collateralAsset:r,collateralAmount:n.toString(),dAssetAmount:e.toString(),minterAddress:w}}async signOrder(t){let e=this.sdk.signer,r={name:"DeployMinting",version:"1",chainId:await this.sdk.getChainId(),verifyingContract:t.minterAddress},n={order_id:t.orderId,order_type:t.orderType,expiry:t.expiry,nonce:t.nonce,benefactor:t.benefactor,beneficiary:t.beneficiary,collateral_asset:t.collateralAsset,collateral_amount:t.collateralAmount,dAsset_amount:t.dAssetAmount};try{return await e._signTypedData(r,A,n)}catch(s){throw new a("SIGNATURE_FAILED","Failed to sign redeem order",s)}}async submitOrder(t,e){try{let r=await fetch(`${this.sdk.config.apiUrl}/api/redeem`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:{order_id:t.orderId,order_type:t.orderType,expiry:t.expiry,nonce:t.nonce,benefactor:t.benefactor,beneficiary:t.beneficiary,collateral_asset:t.collateralAsset,collateral_amount:t.collateralAmount,dAsset_amount:t.dAssetAmount},signature:{signature_type:0,signature_bytes:e}})});if(!r.ok){let s=await r.json();throw new a("API_ERROR",s.message||"Failed to submit redeem order")}let n=await r.json();return{success:!0,orderId:t.orderId,txHash:n.txHash,status:n.status}}catch(r){throw r instanceof a?r:new a("API_ERROR","Failed to submit redeem order",r)}}async redeem(t,e,r,n,s){try{let i=await this.createOrder(t,e,r,n,s),d=await this.signOrder(i);return await this.submitOrder(i,d)}catch(i){throw i instanceof a?i:new a("REDEEM_FAILED","Failed to redeem tokens",i)}}async estimateGas(t,e,r,n,s){let i=new M.Contract(t.mintingContract,E,this.sdk.provider),d={order_id:crypto.randomUUID(),order_type:1,expiry:Math.floor(Date.now()/1e3)+300,nonce:Date.now(),benefactor:await this.sdk.getAddress(),beneficiary:await this.sdk.getAddress(),collateral_asset:r,collateral_amount:n.toString(),dAsset_amount:e.toString()};try{return(await i.estimateGas.redeem(d,{signature_type:0,signature_bytes:s})).toBigInt()}catch(c){throw new a("TRANSACTION_FAILED","Failed to estimate gas for redeem",c)}}};var R=require("ethers");var k=class{constructor(t){this.sdk=t}async getAllowance(t,e,r){try{let n=r||await this.sdk.getAddress();return await new R.Contract(t,g,this.sdk.provider).allowance(n,e)}catch(n){throw new a("VALIDATION_ERROR","Failed to get allowance",n)}}async approve(t,e,r){try{return await(await new R.Contract(t,g,this.sdk.signer).approve(e,r)).wait()}catch(n){throw new a("TRANSACTION_FAILED","Failed to approve allowance",n)}}async approveMax(t,e){let r=R.BigNumber.from(2).pow(256).sub(1);return this.approve(t,e,r)}async hasSufficientAllowance(t,e,r){try{return(await this.getAllowance(t,e)).gte(r)}catch{return!1}}async ensureAllowance(t,e,r,n){return await this.hasSufficientAllowance(t,e,r)||(n?.approveMax?await this.approveMax(t,e):await this.approve(t,e,r)),!0}};var x=require("ethers");var T=class{constructor(t){this.sdk=t}async getTokenBalance(t,e){try{let r=e||await this.sdk.getAddress();return await new x.Contract(t,g,this.sdk.provider).balanceOf(r)}catch(r){throw new a("VALIDATION_ERROR","Failed to get token balance",r)}}async getTokenDecimals(t){try{return await new x.Contract(t,g,this.sdk.provider).decimals()}catch{return 18}}async getTokenSymbol(t){try{return await new x.Contract(t,g,this.sdk.provider).symbol()}catch{return"UNKNOWN"}}async getNativeBalance(t){try{let e=t||await this.sdk.getAddress();return await this.sdk.provider.getBalance(e)}catch(e){throw new a("VALIDATION_ERROR","Failed to get native balance",e)}}async hasSufficientBalance(t,e){try{return(await this.getTokenBalance(t)).gte(e)}catch{return!1}}async hasSufficientNativeBalance(t){try{return(await this.getNativeBalance()).gte(t)}catch{return!1}}};var v=class extends K.default{constructor(e){super();this._provider=null;this._signer=null;this._walletAdapter=null;this._isInitialized=!1;if(!e?.apiUrl?.trim())throw new a("VALIDATION_ERROR","apiUrl is required. Provide the API base URL when creating DeploySDK.");this._config={chainId:1,...e},this.mint=new D(this),this.stake=new I(this),this.unstake=new b(this),this.redeem=new S(this),this.allowance=new k(this),this.balances=new T(this)}async initialize(e){try{if(this.emit("initializing"),this._walletAdapter=e,this._provider=await e.getProvider(),this._signer=await e.getSigner(),!await e.isConnected())throw new a("WALLET_NOT_CONNECTED","Wallet not connected");let n=await this.getAddress();this._isInitialized=!0,this.emit("initialized",{address:n})}catch(r){throw this.emit("error",r),r}}get provider(){if(!this._provider)throw new a("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._provider}get signer(){if(!this._signer)throw new a("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._signer}get config(){return{...this._config}}get isInitialized(){return this._isInitialized}async getAddress(){return this.signer.getAddress()}async getChainId(){return(await this.provider.getNetwork()).chainId}async switchChain(e){if(this._walletAdapter?.switchChain)await this._walletAdapter.switchChain(e),this._config.chainId=e,this.emit("chainChanged",{chainId:e});else throw new a("NOT_INITIALIZED","Wallet adapter does not support chain switching")}async disconnect(){this._walletAdapter?.disconnect&&await this._walletAdapter.disconnect(),this._provider=null,this._signer=null,this._walletAdapter=null,this._isInitialized=!1,this.emit("disconnected")}};var P=class{constructor(t){this.privy=t;this.name="Privy"}async getProvider(){return this.privy.getEthereumProvider()}async getSigner(){return(await this.getProvider()).getSigner()}async isConnected(){return!!this.privy.user?.wallet?.address}};var U=class{constructor(t){this.ethereum=t;this.name="External"}async getProvider(){return this.ethereum}async getSigner(){return await this.ethereum.request({method:"eth_requestAccounts"}),this.ethereum}async isConnected(){try{return(await this.ethereum.request({method:"eth_accounts"})).length>0}catch{return!1}}async switchChain(t){let e=`0x${t.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:e}]})}catch(r){if(r.code===4902)await this.addChain(t);else throw r}}async addChain(t){let r={1:{chainId:"0x1",chainName:"Ethereum Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://eth.llamarpc.com"],blockExplorerUrls:["https://etherscan.io"]},42161:{chainId:"0xa4b1",chainName:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://arb1.arbitrum.io/rpc"],blockExplorerUrls:["https://arbiscan.io"]}}[t];if(!r)throw new Error(`Chain ${t} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[r]})}};0&&(module.exports={AllowanceService,BalanceService,COLLATERAL_ASSETS,CONTRACT_ADDRESSES,ChainId,DeploySDK,DeploySDKError,EIP712_TYPES_ORDER,ERC20_ABI,ERC4626_ABI,ErrorCode,ExternalWalletAdapter,MINTER_ABI,MintModule,PrivyAdapter,RedeemModule,STAKE_TOKENS,StakeModule,UnstakeModule});
|
|
1
|
+
"use strict";var z=Object.create;var N=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var Y=(a,e)=>{for(var t in e)N(a,t,{get:e[t],enumerable:!0})},B=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!j.call(a,n)&&n!==t&&N(a,n,{get:()=>e[n],enumerable:!(r=$(e,n))||r.enumerable});return a};var Z=(a,e,t)=>(t=a!=null?z(G(a)):{},B(e||!a||!a.__esModule?N(t,"default",{value:a,enumerable:!0}):t,a)),J=a=>B(N({},"__esModule",{value:!0}),a);var X={};Y(X,{AllowanceService:()=>R,BalanceService:()=>k,COLLATERAL_ASSETS:()=>O,CONTRACT_ADDRESSES:()=>p,ChainId:()=>y,DeploySDK:()=>T,DeploySDKError:()=>i,EIP712_TYPES_ORDER:()=>A,ERC20_ABI:()=>g,ERC4626_ABI:()=>m,ErrorCode:()=>h,ExternalWalletAdapter:()=>U,MINTER_ABI:()=>E,MintModule:()=>D,PrivyAdapter:()=>P,RedeemModule:()=>v,STAKE_TOKENS:()=>Q,StakeModule:()=>I,UnstakeModule:()=>b,default:()=>T});module.exports=J(X);var K=Z(require("eventemitter3"));var y=(t=>(t[t.ETHEREUM=1]="ETHEREUM",t[t.ARBITRUM=42161]="ARBITRUM",t))(y||{});var h=(l=>(l.NOT_INITIALIZED="NOT_INITIALIZED",l.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",l.INVALID_CHAIN="INVALID_CHAIN",l.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",l.INSUFFICIENT_ALLOWANCE="INSUFFICIENT_ALLOWANCE",l.TRANSACTION_FAILED="TRANSACTION_FAILED",l.STAKE_FAILED="STAKE_FAILED",l.UNSTAKE_FAILED="UNSTAKE_FAILED",l.COOLDOWN_FAILED="COOLDOWN_FAILED",l.MINT_FAILED="MINT_FAILED",l.REDEEM_FAILED="REDEEM_FAILED",l.INVALID_ORDER="INVALID_ORDER",l.SIGNATURE_FAILED="SIGNATURE_FAILED",l.API_ERROR="API_ERROR",l.VALIDATION_ERROR="VALIDATION_ERROR",l))(h||{}),i=class a extends Error{constructor(e,t,r){super(t),this.name="DeploySDKError",this.code=e,this.originalError=r,Error.captureStackTrace&&Error.captureStackTrace(this,a)}toJSON(){return{name:this.name,code:this.code,message:this.message,originalError:this.originalError?.message||this.originalError}}};var F=require("ethers");var p={1:{USDC:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",USDT:"0xdac17f958d2ee523a2206206994597c13d831ec7",dUSD:"0xf42e0b98e32150fe02a370456e6479fcd94f5531",DUSD_MINTER:"0x1ee453Ea35f6EAbD9BFF126586322cbC906D4EB3",sDUSD_STAKING:"0x7f37B0133B1adC1D0647EE52eA38fA13caC4aA1B"},42161:{}},O={USDC:{key:"USDC",name:"USD Coin",symbol:"USDC",address:p[1].USDC,decimals:6,mintingContract:p[1].DUSD_MINTER},USDT:{key:"USDT",name:"Tether USD",symbol:"USDT",address:p[1].USDT,decimals:6,mintingContract:p[1].DUSD_MINTER}},Q={dUSD:{key:"dUSD",name:"Deploy USD",symbol:"dUSD",address:p[1].dUSD,decimals:18,supportedCollateral:[O.USDC,O.USDT],mintingContract:p[1].DUSD_MINTER,stakingContract:p[1].sDUSD_STAKING,stakingSymbol:"sDUSD",cooldownPeriod:2160*60*60*1e3}},A={Order:[{name:"order_id",type:"string"},{name:"order_type",type:"uint8"},{name:"expiry",type:"uint256"},{name:"nonce",type:"uint256"},{name:"benefactor",type:"address"},{name:"beneficiary",type:"address"},{name:"collateral_asset",type:"address"},{name:"collateral_amount",type:"uint256"},{name:"dAsset_amount",type:"uint256"}]},m=["function deposit(uint256 assets, address receiver) external returns (uint256 shares)","function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)","function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets)","function cooldownShares(uint256 shares) external","function cooldowns(address user) external view returns (uint256 cooldownEnd, uint256 underlyingAmount)","function balanceOf(address owner) external view returns (uint256)","function convertToShares(uint256 assets) external view returns (uint256)","function convertToAssets(uint256 shares) external view returns (uint256)","function totalAssets() external view returns (uint256)","function totalSupply() external view returns (uint256)","event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares)","event Withdraw(address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares)"],g=["function approve(address spender, uint256 amount) external returns (bool)","function allowance(address owner, address spender) external view returns (uint256)","function balanceOf(address account) external view returns (uint256)","function decimals() external view returns (uint8)","function symbol() external view returns (string)","function name() external view returns (string)","function transfer(address recipient, uint256 amount) external returns (bool)","function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)","event Approval(address indexed owner, address indexed spender, uint256 value)","event Transfer(address indexed from, address indexed to, uint256 value)"],E=["function mint(tuple(string order_id, uint8 order_type, uint256 expiry, uint256 nonce, address benefactor, address beneficiary, address collateral_asset, uint256 collateral_amount, uint256 dAsset_amount) order, tuple(address[] addresses, uint256[] ratios) route, tuple(uint8 signature_type, bytes signature_bytes) signature) external","function redeem(tuple(string order_id, uint8 order_type, uint256 expiry, uint256 nonce, address benefactor, address beneficiary, address collateral_asset, uint256 collateral_amount, uint256 dAsset_amount) order, tuple(uint8 signature_type, bytes signature_bytes) signature) external","function isWhitelistedBenefactor(address benefactor) external view returns (bool)","function addWhitelistedBenefactor(address benefactor) external","function removeWhitelistedBenefactor(address benefactor) external"];var D=class{constructor(e){this.sdk=e}async createOrder(e,t,r,n){let s=await this.sdk.getAddress(),o=crypto.randomUUID(),d=Math.floor(Date.now()/1e3)+(n?.expiryMinutes||5)*60,c=e.mintingContract;return{orderId:o,orderType:0,expiry:d,nonce:Date.now(),benefactor:n?.benefactor||s,beneficiary:n?.beneficiary||s,collateralAsset:e.address,collateralAmount:t.toString(),dAssetAmount:r.toString(),minterAddress:c}}async signOrder(e){let t=this.sdk.signer,r={name:"DeployMinting",version:"1",chainId:await this.sdk.getChainId(),verifyingContract:e.minterAddress},n={order_id:e.orderId,order_type:e.orderType,expiry:e.expiry,nonce:e.nonce,benefactor:e.benefactor,beneficiary:e.beneficiary,collateral_asset:e.collateralAsset,collateral_amount:e.collateralAmount,dAsset_amount:e.dAssetAmount};try{return await t._signTypedData(r,A,n)}catch(s){throw new i("SIGNATURE_FAILED","Failed to sign mint order",s)}}async submitOrder(e,t){try{let r=await fetch(`${this.sdk.config.apiUrl}/api/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:{order_id:e.orderId,order_type:e.orderType,expiry:e.expiry,nonce:e.nonce,benefactor:e.benefactor,beneficiary:e.beneficiary,collateral_asset:e.collateralAsset,collateral_amount:e.collateralAmount,dAsset_amount:e.dAssetAmount},signature:{signature_type:0,signature_bytes:t}})});if(!r.ok){let s=await r.json();throw new i("API_ERROR",s.message||"Failed to submit mint order")}let n=await r.json();return{success:!0,orderId:e.orderId,txHash:n.txHash,status:n.status}}catch(r){throw r instanceof i?r:new i("API_ERROR","Failed to submit mint order",r)}}async mint(e,t,r,n){try{let s=await this.createOrder(e,t,r,n),o=await this.signOrder(s);return await this.submitOrder(s,o)}catch(s){throw s instanceof i?s:new i("MINT_FAILED","Failed to mint tokens",s)}}async estimateGas(e,t,r,n){let s=new F.Contract(e.mintingContract,E,this.sdk.provider),o={order_id:crypto.randomUUID(),order_type:0,expiry:Math.floor(Date.now()/1e3)+300,nonce:Date.now(),benefactor:await this.sdk.getAddress(),beneficiary:await this.sdk.getAddress(),collateral_asset:e.address,collateral_amount:t.toString(),dAsset_amount:r.toString()};try{return(await s.estimateGas.mint(o,{addresses:[],ratios:[]},{signature_type:0,signature_bytes:n})).toBigInt()}catch(d){throw new i("TRANSACTION_FAILED","Failed to estimate gas for mint",d)}}};var u=require("ethers");var I=class{constructor(e){this.sdk=e}async stake(e){try{let{token:t,amount:r,receiver:n}=e;if(!t.stakingContract)throw new i("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let s=new u.Contract(t.stakingContract,m,this.sdk.signer),o=n||await this.sdk.getAddress(),c=await(await s.deposit(r,o)).wait(),w,f=c.events?.find(C=>C.event==="Deposit");return f&&(w=f.args?.shares?.toString()),{success:!0,txHash:c.transactionHash,sharesReceived:w}}catch(t){throw t instanceof i?t:new i("STAKE_FAILED","Failed to stake tokens",t)}}async getPosition(e,t){if(!e.stakingContract)throw new i("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let r=t||await this.sdk.getAddress(),n=new u.Contract(e.stakingContract,m,this.sdk.provider);try{let[s,o,d]=await Promise.all([n.balanceOf(r),n.convertToAssets(await n.balanceOf(r)),n.cooldowns(r).catch(()=>({cooldownEnd:u.BigNumber.from(0),underlyingAmount:u.BigNumber.from(0)}))]),c=d.cooldownEnd.toNumber()*1e3;return{tokenKey:e.key,stakedAmount:s.toString(),stakedValue:o.toString(),cooldownEnd:c>0?c:void 0,canUnstake:c===0||c<=Date.now()}}catch(s){throw new i("VALIDATION_ERROR","Failed to fetch staking position",s)}}async previewStake(e,t){if(!e.stakingContract)throw new i("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let r=new u.Contract(e.stakingContract,m,this.sdk.provider);try{return{shares:(await r.convertToShares(t)).toString(),assets:t.toString()}}catch(n){throw new i("VALIDATION_ERROR","Failed to preview stake",n)}}async getAPY(e){if(!e.stakingContract)return 0;let t=new u.Contract(e.stakingContract,m,this.sdk.provider);try{let[r,n]=await Promise.all([t.totalAssets(),t.totalSupply()]);if(n.isZero())return 0;let s=r.mul(u.BigNumber.from(10).pow(18)).div(n),o=u.BigNumber.from(10).pow(18);return s.lte(o)?0:s.sub(o).mul(365).mul(1e4).div(o).toNumber()/100}catch{return 0}}};var _=require("ethers");var b=class{constructor(e){this.sdk=e}async initiateCooldown(e,t){try{if(!e.stakingContract)throw new i("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let s=await(await new _.Contract(e.stakingContract,m,this.sdk.signer).cooldownShares(t)).wait(),o=Date.now()+(e.cooldownPeriod||2160*60*60*1e3);return{success:!0,txHash:s.transactionHash,cooldownEnd:o}}catch(r){throw r instanceof i?r:new i("COOLDOWN_FAILED","Failed to initiate cooldown",r)}}async unstake(e){try{let{token:t,sharesAmount:r,receiver:n}=e;if(!t.stakingContract)throw new i("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let s=await this.getCooldownStatus(t);if(!s.canUnstake)throw new i("VALIDATION_ERROR",`Cannot unstake. Cooldown ends at ${new Date(s.cooldownEnd).toLocaleString()}`);let o=new _.Contract(t.stakingContract,m,this.sdk.signer),d=n||await this.sdk.getAddress(),c=await this.sdk.getAddress(),f=await(await o.redeem(r,d,c)).wait(),C,L=f.events?.find(V=>V.event==="Withdraw");return L&&(C=L.args?.assets?.toString()),{success:!0,txHash:f.transactionHash,assetsWithdrawn:C}}catch(t){throw t instanceof i?t:new i("UNSTAKE_FAILED","Failed to unstake tokens",t)}}async getCooldownStatus(e,t){if(!e.stakingContract)throw new i("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let r=t||await this.sdk.getAddress(),n=new _.Contract(e.stakingContract,m,this.sdk.provider);try{let s=await n.cooldowns(r),o=s.cooldownEnd.toNumber()*1e3;return{cooldownEnd:o,sharesInCooldown:s.underlyingAmount.toString(),canUnstake:o>0&&o<=Date.now()}}catch(s){throw new i("VALIDATION_ERROR","Failed to fetch cooldown status",s)}}async previewUnstake(e,t){if(!e.stakingContract)throw new i("VALIDATION_ERROR",`Token ${e.symbol} does not support staking`);let r=new _.Contract(e.stakingContract,m,this.sdk.provider);try{return(await r.convertToAssets(t)).toString()}catch(n){throw new i("VALIDATION_ERROR","Failed to preview unstake",n)}}};var M=require("ethers");var v=class{constructor(e){this.sdk=e}async createOrder(e,t,r,n,s){let o=await this.sdk.getAddress(),d=crypto.randomUUID(),c=Math.floor(Date.now()/1e3)+(s?.expiryMinutes||5)*60,w=e.mintingContract;return{orderId:d,orderType:1,expiry:c,nonce:Date.now(),benefactor:s?.benefactor||o,beneficiary:s?.beneficiary||o,collateralAsset:r,collateralAmount:n.toString(),dAssetAmount:t.toString(),minterAddress:w}}async signOrder(e){let t=this.sdk.signer,r={name:"DeployMinting",version:"1",chainId:await this.sdk.getChainId(),verifyingContract:e.minterAddress},n={order_id:e.orderId,order_type:e.orderType,expiry:e.expiry,nonce:e.nonce,benefactor:e.benefactor,beneficiary:e.beneficiary,collateral_asset:e.collateralAsset,collateral_amount:e.collateralAmount,dAsset_amount:e.dAssetAmount};try{return await t._signTypedData(r,A,n)}catch(s){throw new i("SIGNATURE_FAILED","Failed to sign redeem order",s)}}async submitOrder(e,t){try{let r=await fetch(`${this.sdk.config.apiUrl}/api/redeem`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:{order_id:e.orderId,order_type:e.orderType,expiry:e.expiry,nonce:e.nonce,benefactor:e.benefactor,beneficiary:e.beneficiary,collateral_asset:e.collateralAsset,collateral_amount:e.collateralAmount,dAsset_amount:e.dAssetAmount},signature:{signature_type:0,signature_bytes:t}})});if(!r.ok){let s=await r.json();throw new i("API_ERROR",s.message||"Failed to submit redeem order")}let n=await r.json();return{success:!0,orderId:e.orderId,txHash:n.txHash,status:n.status}}catch(r){throw r instanceof i?r:new i("API_ERROR","Failed to submit redeem order",r)}}async redeem(e,t,r,n,s){try{let o=await this.createOrder(e,t,r,n,s),d=await this.signOrder(o);return await this.submitOrder(o,d)}catch(o){throw o instanceof i?o:new i("REDEEM_FAILED","Failed to redeem tokens",o)}}async estimateGas(e,t,r,n,s){let o=new M.Contract(e.mintingContract,E,this.sdk.provider),d={order_id:crypto.randomUUID(),order_type:1,expiry:Math.floor(Date.now()/1e3)+300,nonce:Date.now(),benefactor:await this.sdk.getAddress(),beneficiary:await this.sdk.getAddress(),collateral_asset:r,collateral_amount:n.toString(),dAsset_amount:t.toString()};try{return(await o.estimateGas.redeem(d,{signature_type:0,signature_bytes:s})).toBigInt()}catch(c){throw new i("TRANSACTION_FAILED","Failed to estimate gas for redeem",c)}}};var S=require("ethers");var R=class{constructor(e){this.sdk=e}async getAllowance(e,t,r){try{let n=r||await this.sdk.getAddress();return await new S.Contract(e,g,this.sdk.provider).allowance(n,t)}catch(n){throw new i("VALIDATION_ERROR","Failed to get allowance",n)}}async approve(e,t,r){try{return await(await new S.Contract(e,g,this.sdk.signer).approve(t,r)).wait()}catch(n){throw new i("TRANSACTION_FAILED","Failed to approve allowance",n)}}async approveMax(e,t){let r=S.BigNumber.from(2).pow(256).sub(1);return this.approve(e,t,r)}async hasSufficientAllowance(e,t,r){try{return(await this.getAllowance(e,t)).gte(r)}catch{return!1}}async ensureAllowance(e,t,r,n){return await this.hasSufficientAllowance(e,t,r)||(n?.approveMax?await this.approveMax(e,t):await this.approve(e,t,r)),!0}};var x=require("ethers");var k=class{constructor(e){this.sdk=e}async getTokenBalance(e,t){try{let r=t||await this.sdk.getAddress();return await new x.Contract(e,g,this.sdk.provider).balanceOf(r)}catch(r){throw new i("VALIDATION_ERROR","Failed to get token balance",r)}}async getTokenDecimals(e){try{return await new x.Contract(e,g,this.sdk.provider).decimals()}catch{return 18}}async getTokenSymbol(e){try{return await new x.Contract(e,g,this.sdk.provider).symbol()}catch{return"UNKNOWN"}}async getNativeBalance(e){try{let t=e||await this.sdk.getAddress();return await this.sdk.provider.getBalance(t)}catch(t){throw new i("VALIDATION_ERROR","Failed to get native balance",t)}}async hasSufficientBalance(e,t){try{return(await this.getTokenBalance(e)).gte(t)}catch{return!1}}async hasSufficientNativeBalance(e){try{return(await this.getNativeBalance()).gte(e)}catch{return!1}}};var T=class extends K.default{constructor(t){super();this._provider=null;this._signer=null;this._walletAdapter=null;this._isInitialized=!1;if(!t?.apiUrl?.trim())throw new i("VALIDATION_ERROR","apiUrl is required. Provide the API base URL when creating DeploySDK.");this._config={chainId:1,...t},this.mint=new D(this),this.stake=new I(this),this.unstake=new b(this),this.redeem=new v(this),this.allowance=new R(this),this.balances=new k(this)}async initialize(t){try{if(this.emit("initializing"),this._walletAdapter=t,this._provider=await t.getProvider(),this._signer=await t.getSigner(),!await t.isConnected())throw new i("WALLET_NOT_CONNECTED","Wallet not connected");let n=await this.getAddress();this._isInitialized=!0,this.emit("initialized",{address:n})}catch(r){throw this.emit("error",r),r}}get provider(){if(!this._provider)throw new i("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._provider}get signer(){if(!this._signer)throw new i("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._signer}get config(){return{...this._config}}get isInitialized(){return this._isInitialized}async getAddress(){return this.signer.getAddress()}async getChainId(){return(await this.provider.getNetwork()).chainId}async switchChain(t){if(this._walletAdapter?.switchChain)await this._walletAdapter.switchChain(t),this._config.chainId=t,this.emit("chainChanged",{chainId:t});else throw new i("NOT_INITIALIZED","Wallet adapter does not support chain switching")}async disconnect(){this._walletAdapter?.disconnect&&await this._walletAdapter.disconnect(),this._provider=null,this._signer=null,this._walletAdapter=null,this._isInitialized=!1,this.emit("disconnected")}};var H=require("ethers");function W(a){return!!a&&typeof a.request=="function"}var P=class{constructor(e){this.wallet=e;this.name="Privy";this._provider=null;if(!e||typeof e.getEthereumProvider!="function")throw new Error("PrivyAdapter requires a connected wallet with getEthereumProvider (e.g. from useWallets().wallets[0])");if(!e.address||typeof e.address!="string")throw new Error("PrivyAdapter requires a wallet with an address")}async getProvider(){if(this._provider)return this._provider;let e=await this.wallet.getEthereumProvider();if(!W(e))throw new Error("Privy wallet did not return a valid EIP-1193 provider");return this._provider=new H.ethers.providers.Web3Provider(e),this._provider}async getSigner(){return(await this.getProvider()).getSigner()}async isConnected(){if(!this.wallet?.address)return!1;try{let e=await this.wallet.getEthereumProvider();if(!W(e))return!1;let t=await e.request({method:"eth_accounts"});if(!Array.isArray(t)||t.length===0)return!1;let r=this.wallet.address.toLowerCase();return t.some(n=>(n||"").toLowerCase()===r)}catch{return!1}}async switchChain(e){if(this.wallet.switchChain)await this.wallet.switchChain(e),this._provider=null;else throw new Error("Privy wallet does not support switchChain")}};var U=class{constructor(e){this.ethereum=e;this.name="External"}async getProvider(){return this.ethereum}async getSigner(){return await this.ethereum.request({method:"eth_requestAccounts"}),this.ethereum}async isConnected(){try{return(await this.ethereum.request({method:"eth_accounts"})).length>0}catch{return!1}}async switchChain(e){let t=`0x${e.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:t}]})}catch(r){if(r.code===4902)await this.addChain(e);else throw r}}async addChain(e){let r={1:{chainId:"0x1",chainName:"Ethereum Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://eth.llamarpc.com"],blockExplorerUrls:["https://etherscan.io"]},42161:{chainId:"0xa4b1",chainName:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://arb1.arbitrum.io/rpc"],blockExplorerUrls:["https://arbiscan.io"]}}[e];if(!r)throw new Error(`Chain ${e} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[r]})}};0&&(module.exports={AllowanceService,BalanceService,COLLATERAL_ASSETS,CONTRACT_ADDRESSES,ChainId,DeploySDK,DeploySDKError,EIP712_TYPES_ORDER,ERC20_ABI,ERC4626_ABI,ErrorCode,ExternalWalletAdapter,MINTER_ABI,MintModule,PrivyAdapter,RedeemModule,STAKE_TOKENS,StakeModule,UnstakeModule});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,b as a,c as b,d as A,e as _,f as I,g as N,h as o,i as S,j as m,k as w,l as g,m as u}from"./chunk-QZGD3DFS.mjs";import{a as C,b as E}from"./chunk-
|
|
1
|
+
import{a as c,b as a,c as b,d as A,e as _,f as I,g as N,h as o,i as S,j as m,k as w,l as g,m as u}from"./chunk-QZGD3DFS.mjs";import{a as C,b as E}from"./chunk-C52RGN2Q.mjs";import{a as y}from"./chunk-XSAEU2QV.mjs";import D from"eventemitter3";import{BigNumber as v,Contract as f}from"ethers";var n=class{constructor(e){this.sdk=e}async getAllowance(e,t,r){try{let i=r||await this.sdk.getAddress();return await new f(e,o,this.sdk.provider).allowance(i,t)}catch(i){throw new a("VALIDATION_ERROR","Failed to get allowance",i)}}async approve(e,t,r){try{return await(await new f(e,o,this.sdk.signer).approve(t,r)).wait()}catch(i){throw new a("TRANSACTION_FAILED","Failed to approve allowance",i)}}async approveMax(e,t){let r=v.from(2).pow(256).sub(1);return this.approve(e,t,r)}async hasSufficientAllowance(e,t,r){try{return(await this.getAllowance(e,t)).gte(r)}catch{return!1}}async ensureAllowance(e,t,r,i){return await this.hasSufficientAllowance(e,t,r)||(i?.approveMax?await this.approveMax(e,t):await this.approve(e,t,r)),!0}};import{Contract as h}from"ethers";var s=class{constructor(e){this.sdk=e}async getTokenBalance(e,t){try{let r=t||await this.sdk.getAddress();return await new h(e,o,this.sdk.provider).balanceOf(r)}catch(r){throw new a("VALIDATION_ERROR","Failed to get token balance",r)}}async getTokenDecimals(e){try{return await new h(e,o,this.sdk.provider).decimals()}catch{return 18}}async getTokenSymbol(e){try{return await new h(e,o,this.sdk.provider).symbol()}catch{return"UNKNOWN"}}async getNativeBalance(e){try{let t=e||await this.sdk.getAddress();return await this.sdk.provider.getBalance(t)}catch(t){throw new a("VALIDATION_ERROR","Failed to get native balance",t)}}async hasSufficientBalance(e,t){try{return(await this.getTokenBalance(e)).gte(t)}catch{return!1}}async hasSufficientNativeBalance(e){try{return(await this.getNativeBalance()).gte(e)}catch{return!1}}};var l=class extends D{constructor(t){super();this._provider=null;this._signer=null;this._walletAdapter=null;this._isInitialized=!1;if(!t?.apiUrl?.trim())throw new a("VALIDATION_ERROR","apiUrl is required. Provide the API base URL when creating DeploySDK.");this._config={chainId:1,...t},this.mint=new m(this),this.stake=new w(this),this.unstake=new g(this),this.redeem=new u(this),this.allowance=new n(this),this.balances=new s(this)}async initialize(t){try{if(this.emit("initializing"),this._walletAdapter=t,this._provider=await t.getProvider(),this._signer=await t.getSigner(),!await t.isConnected())throw new a("WALLET_NOT_CONNECTED","Wallet not connected");let i=await this.getAddress();this._isInitialized=!0,this.emit("initialized",{address:i})}catch(r){throw this.emit("error",r),r}}get provider(){if(!this._provider)throw new a("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._provider}get signer(){if(!this._signer)throw new a("NOT_INITIALIZED","SDK not initialized. Call initialize() first.");return this._signer}get config(){return{...this._config}}get isInitialized(){return this._isInitialized}async getAddress(){return this.signer.getAddress()}async getChainId(){return(await this.provider.getNetwork()).chainId}async switchChain(t){if(this._walletAdapter?.switchChain)await this._walletAdapter.switchChain(t),this._config.chainId=t,this.emit("chainChanged",{chainId:t});else throw new a("NOT_INITIALIZED","Wallet adapter does not support chain switching")}async disconnect(){this._walletAdapter?.disconnect&&await this._walletAdapter.disconnect(),this._provider=null,this._signer=null,this._walletAdapter=null,this._isInitialized=!1,this.emit("disconnected")}};export{n as AllowanceService,s as BalanceService,A as COLLATERAL_ASSETS,b as CONTRACT_ADDRESSES,y as ChainId,l as DeploySDK,a as DeploySDKError,I as EIP712_TYPES_ORDER,o as ERC20_ABI,N as ERC4626_ABI,c as ErrorCode,E as ExternalWalletAdapter,S as MINTER_ABI,m as MintModule,C as PrivyAdapter,u as RedeemModule,_ as STAKE_TOKENS,w as StakeModule,g as UnstakeModule,l as default};
|
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
import { W as WalletAdapter, a as ChainId } from '../base-DLLHDCZ5.mjs';
|
|
2
|
+
import { ethers } from 'ethers';
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Privy ConnectedWallet from useWallets() (e.g. wallets[0]).
|
|
6
|
+
* Use: import { useWallets } from '@privy-io/react-auth'; const { wallets } = useWallets(); adapter = new PrivyAdapter(wallets[0]);
|
|
7
|
+
*/
|
|
8
|
+
interface PrivyConnectedWallet {
|
|
9
|
+
getEthereumProvider(): Promise<unknown>;
|
|
10
|
+
address: string;
|
|
11
|
+
switchChain?(chainId: number): Promise<void>;
|
|
10
12
|
}
|
|
11
13
|
declare class PrivyAdapter implements WalletAdapter {
|
|
12
|
-
private
|
|
14
|
+
private wallet;
|
|
13
15
|
name: string;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
private _provider;
|
|
17
|
+
constructor(wallet: PrivyConnectedWallet);
|
|
18
|
+
getProvider(): Promise<ethers.providers.Web3Provider>;
|
|
19
|
+
getSigner(): Promise<ethers.Signer>;
|
|
17
20
|
isConnected(): Promise<boolean>;
|
|
21
|
+
switchChain(chainId: ChainId): Promise<void>;
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
interface EthereumProvider {
|
|
@@ -35,4 +39,4 @@ declare class ExternalWalletAdapter implements WalletAdapter {
|
|
|
35
39
|
private addChain;
|
|
36
40
|
}
|
|
37
41
|
|
|
38
|
-
export { ExternalWalletAdapter, PrivyAdapter, WalletAdapter };
|
|
42
|
+
export { ExternalWalletAdapter, PrivyAdapter, type PrivyConnectedWallet, WalletAdapter };
|
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
import { W as WalletAdapter, a as ChainId } from '../base-DLLHDCZ5.js';
|
|
2
|
+
import { ethers } from 'ethers';
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Privy ConnectedWallet from useWallets() (e.g. wallets[0]).
|
|
6
|
+
* Use: import { useWallets } from '@privy-io/react-auth'; const { wallets } = useWallets(); adapter = new PrivyAdapter(wallets[0]);
|
|
7
|
+
*/
|
|
8
|
+
interface PrivyConnectedWallet {
|
|
9
|
+
getEthereumProvider(): Promise<unknown>;
|
|
10
|
+
address: string;
|
|
11
|
+
switchChain?(chainId: number): Promise<void>;
|
|
10
12
|
}
|
|
11
13
|
declare class PrivyAdapter implements WalletAdapter {
|
|
12
|
-
private
|
|
14
|
+
private wallet;
|
|
13
15
|
name: string;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
private _provider;
|
|
17
|
+
constructor(wallet: PrivyConnectedWallet);
|
|
18
|
+
getProvider(): Promise<ethers.providers.Web3Provider>;
|
|
19
|
+
getSigner(): Promise<ethers.Signer>;
|
|
17
20
|
isConnected(): Promise<boolean>;
|
|
21
|
+
switchChain(chainId: ChainId): Promise<void>;
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
interface EthereumProvider {
|
|
@@ -35,4 +39,4 @@ declare class ExternalWalletAdapter implements WalletAdapter {
|
|
|
35
39
|
private addChain;
|
|
36
40
|
}
|
|
37
41
|
|
|
38
|
-
export { ExternalWalletAdapter, PrivyAdapter, WalletAdapter };
|
|
42
|
+
export { ExternalWalletAdapter, PrivyAdapter, type PrivyConnectedWallet, WalletAdapter };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var u=(r,e)=>{for(var t in e)s(r,t,{get:e[t],enumerable:!0})},p=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of l(e))!m.call(r,n)&&n!==t&&s(r,n,{get:()=>e[n],enumerable:!(i=c(e,n))||i.enumerable});return r};var v=r=>p(s({},"__esModule",{value:!0}),r);var g={};u(g,{ExternalWalletAdapter:()=>o,PrivyAdapter:()=>a});module.exports=v(g);var h=require("ethers");function d(r){return!!r&&typeof r.request=="function"}var a=class{constructor(e){this.wallet=e;this.name="Privy";this._provider=null;if(!e||typeof e.getEthereumProvider!="function")throw new Error("PrivyAdapter requires a connected wallet with getEthereumProvider (e.g. from useWallets().wallets[0])");if(!e.address||typeof e.address!="string")throw new Error("PrivyAdapter requires a wallet with an address")}async getProvider(){if(this._provider)return this._provider;let e=await this.wallet.getEthereumProvider();if(!d(e))throw new Error("Privy wallet did not return a valid EIP-1193 provider");return this._provider=new h.ethers.providers.Web3Provider(e),this._provider}async getSigner(){return(await this.getProvider()).getSigner()}async isConnected(){if(!this.wallet?.address)return!1;try{let e=await this.wallet.getEthereumProvider();if(!d(e))return!1;let t=await e.request({method:"eth_accounts"});if(!Array.isArray(t)||t.length===0)return!1;let i=this.wallet.address.toLowerCase();return t.some(n=>(n||"").toLowerCase()===i)}catch{return!1}}async switchChain(e){if(this.wallet.switchChain)await this.wallet.switchChain(e),this._provider=null;else throw new Error("Privy wallet does not support switchChain")}};var o=class{constructor(e){this.ethereum=e;this.name="External"}async getProvider(){return this.ethereum}async getSigner(){return await this.ethereum.request({method:"eth_requestAccounts"}),this.ethereum}async isConnected(){try{return(await this.ethereum.request({method:"eth_accounts"})).length>0}catch{return!1}}async switchChain(e){let t=`0x${e.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:t}]})}catch(i){if(i.code===4902)await this.addChain(e);else throw i}}async addChain(e){let i={1:{chainId:"0x1",chainName:"Ethereum Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://eth.llamarpc.com"],blockExplorerUrls:["https://etherscan.io"]},42161:{chainId:"0xa4b1",chainName:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:["https://arb1.arbitrum.io/rpc"],blockExplorerUrls:["https://arbiscan.io"]}}[e];if(!i)throw new Error(`Chain ${e} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[i]})}};0&&(module.exports={ExternalWalletAdapter,PrivyAdapter});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-C52RGN2Q.mjs";import"../chunk-XSAEU2QV.mjs";export{b as ExternalWalletAdapter,a as PrivyAdapter};
|
package/package.json
CHANGED