deploy-sdk 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ import { BigNumberish, BigNumber } from 'ethers';
2
+ import EventEmitter from 'eventemitter3';
3
+ import { C as CollateralAsset, S as StakeToken, b as SDKEvents, D as DeploySDKConfig, W as WalletAdapter, a as ChainId } from './base-01mNzZ7A.js';
4
+
5
+ interface MintOrder {
6
+ orderId: string;
7
+ orderType: number;
8
+ expiry: number;
9
+ nonce: number;
10
+ benefactor: string;
11
+ beneficiary: string;
12
+ collateralAsset: string;
13
+ collateralAmount: string;
14
+ dAssetAmount: string;
15
+ minterAddress: string;
16
+ }
17
+ interface MintResult {
18
+ success: boolean;
19
+ orderId: string;
20
+ txHash?: string;
21
+ status?: string;
22
+ error?: string;
23
+ }
24
+ interface MintOptions {
25
+ expiryMinutes?: number;
26
+ benefactor?: string;
27
+ beneficiary?: string;
28
+ }
29
+ interface MintParams {
30
+ collateralAsset: CollateralAsset;
31
+ collateralAmount: BigNumberish;
32
+ dAssetAmount: BigNumberish;
33
+ options?: MintOptions;
34
+ }
35
+
36
+ declare class MintModule {
37
+ private sdk;
38
+ constructor(sdk: DeploySDK);
39
+ createOrder(collateralAsset: CollateralAsset, collateralAmount: BigNumberish, dAssetAmount: BigNumberish, options?: MintOptions): Promise<MintOrder>;
40
+ signOrder(order: MintOrder): Promise<string>;
41
+ submitOrder(order: MintOrder, signature: string): Promise<MintResult>;
42
+ mint(collateralAsset: CollateralAsset, collateralAmount: BigNumberish, dAssetAmount: BigNumberish, options?: MintOptions): Promise<MintResult>;
43
+ estimateGas(collateralAsset: CollateralAsset, collateralAmount: BigNumberish, dAssetAmount: BigNumberish, signature: string): Promise<bigint>;
44
+ }
45
+
46
+ interface StakeParams {
47
+ token: StakeToken;
48
+ amount: BigNumberish;
49
+ receiver?: string;
50
+ }
51
+ interface StakeResult {
52
+ success: boolean;
53
+ txHash?: string;
54
+ sharesReceived?: string;
55
+ error?: string;
56
+ }
57
+ interface StakingPosition {
58
+ tokenKey: string;
59
+ stakedAmount: string;
60
+ stakedValue: string;
61
+ cooldownEnd?: number;
62
+ canUnstake: boolean;
63
+ }
64
+ interface StakePreview {
65
+ shares: string;
66
+ assets: string;
67
+ }
68
+
69
+ declare class StakeModule {
70
+ private sdk;
71
+ constructor(sdk: DeploySDK);
72
+ stake(params: StakeParams): Promise<StakeResult>;
73
+ getPosition(token: StakeToken, userAddress?: string): Promise<StakingPosition>;
74
+ previewStake(token: StakeToken, amount: BigNumberish): Promise<StakePreview>;
75
+ getAPY(token: StakeToken): Promise<number>;
76
+ }
77
+
78
+ interface UnstakeParams {
79
+ token: StakeToken;
80
+ sharesAmount: BigNumberish;
81
+ receiver?: string;
82
+ }
83
+ interface UnstakeResult {
84
+ success: boolean;
85
+ txHash?: string;
86
+ assetsWithdrawn?: string;
87
+ error?: string;
88
+ }
89
+ interface CooldownResult {
90
+ success: boolean;
91
+ txHash?: string;
92
+ cooldownEnd?: number;
93
+ error?: string;
94
+ }
95
+ interface CooldownStatus {
96
+ cooldownEnd: number;
97
+ sharesInCooldown: string;
98
+ canUnstake: boolean;
99
+ }
100
+
101
+ declare class UnstakeModule {
102
+ private sdk;
103
+ constructor(sdk: DeploySDK);
104
+ initiateCooldown(token: StakeToken, sharesAmount: BigNumberish): Promise<CooldownResult>;
105
+ unstake(params: UnstakeParams): Promise<UnstakeResult>;
106
+ getCooldownStatus(token: StakeToken, userAddress?: string): Promise<CooldownStatus>;
107
+ previewUnstake(token: StakeToken, sharesAmount: BigNumberish): Promise<string>;
108
+ }
109
+
110
+ interface RedeemOrder {
111
+ orderId: string;
112
+ orderType: number;
113
+ expiry: number;
114
+ nonce: number;
115
+ benefactor: string;
116
+ beneficiary: string;
117
+ collateralAsset: string;
118
+ collateralAmount: string;
119
+ dAssetAmount: string;
120
+ minterAddress: string;
121
+ }
122
+ interface RedeemResult {
123
+ success: boolean;
124
+ orderId: string;
125
+ txHash?: string;
126
+ status?: string;
127
+ error?: string;
128
+ }
129
+ interface RedeemOptions {
130
+ expiryMinutes?: number;
131
+ benefactor?: string;
132
+ beneficiary?: string;
133
+ }
134
+
135
+ declare class RedeemModule {
136
+ private sdk;
137
+ constructor(sdk: DeploySDK);
138
+ createOrder(token: StakeToken, redeemAmount: BigNumberish, collateralAsset: string, collateralAmount: BigNumberish, options?: RedeemOptions): Promise<RedeemOrder>;
139
+ signOrder(order: RedeemOrder): Promise<string>;
140
+ submitOrder(order: RedeemOrder, signature: string): Promise<RedeemResult>;
141
+ redeem(token: StakeToken, redeemAmount: BigNumberish, collateralAsset: string, collateralAmount: BigNumberish, options?: RedeemOptions): Promise<RedeemResult>;
142
+ estimateGas(token: StakeToken, redeemAmount: BigNumberish, collateralAsset: string, collateralAmount: BigNumberish, signature: string): Promise<bigint>;
143
+ }
144
+
145
+ declare class AllowanceService {
146
+ private sdk;
147
+ constructor(sdk: DeploySDK);
148
+ getAllowance(tokenAddress: string, spenderAddress: string, ownerAddress?: string): Promise<BigNumber>;
149
+ approve(tokenAddress: string, spenderAddress: string, amount: BigNumberish): Promise<any>;
150
+ approveMax(tokenAddress: string, spenderAddress: string): Promise<any>;
151
+ hasSufficientAllowance(tokenAddress: string, spenderAddress: string, requiredAmount: BigNumberish): Promise<boolean>;
152
+ ensureAllowance(tokenAddress: string, spenderAddress: string, requiredAmount: BigNumberish, options?: {
153
+ approveMax?: boolean;
154
+ }): Promise<boolean>;
155
+ }
156
+
157
+ declare class BalanceService {
158
+ private sdk;
159
+ constructor(sdk: DeploySDK);
160
+ getTokenBalance(tokenAddress: string, userAddress?: string): Promise<BigNumber>;
161
+ getTokenDecimals(tokenAddress: string): Promise<number>;
162
+ getTokenSymbol(tokenAddress: string): Promise<string>;
163
+ getNativeBalance(userAddress?: string): Promise<BigNumber>;
164
+ hasSufficientBalance(tokenAddress: string, requiredAmount: BigNumberish): Promise<boolean>;
165
+ hasSufficientNativeBalance(requiredAmount: BigNumberish): Promise<boolean>;
166
+ }
167
+
168
+ declare class DeploySDK extends EventEmitter<SDKEvents> {
169
+ private _provider;
170
+ private _signer;
171
+ private _walletAdapter;
172
+ private _config;
173
+ private _isInitialized;
174
+ readonly mint: MintModule;
175
+ readonly stake: StakeModule;
176
+ readonly unstake: UnstakeModule;
177
+ readonly redeem: RedeemModule;
178
+ readonly allowance: AllowanceService;
179
+ readonly balances: BalanceService;
180
+ constructor(config?: DeploySDKConfig);
181
+ initialize(adapter: WalletAdapter): Promise<void>;
182
+ get provider(): any;
183
+ get signer(): any;
184
+ get config(): DeploySDKConfig;
185
+ get isInitialized(): boolean;
186
+ getAddress(): Promise<string>;
187
+ getChainId(): Promise<number>;
188
+ switchChain(chainId: ChainId): Promise<void>;
189
+ disconnect(): Promise<void>;
190
+ }
191
+
192
+ export { AllowanceService as A, BalanceService as B, type CooldownResult as C, DeploySDK as D, MintModule as M, RedeemModule as R, StakeModule as S, UnstakeModule as U, type CooldownStatus as a, type MintOptions as b, type MintOrder as c, type MintParams as d, type MintResult as e, type RedeemOptions as f, type RedeemOrder as g, type RedeemResult as h, type StakeParams as i, type StakePreview as j, type StakeResult as k, type StakingPosition as l, type UnstakeParams as m, type UnstakeResult as n };
@@ -0,0 +1,50 @@
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
+ import { C as CollateralAsset, S as StakeToken } from './base-DLLHDCZ5.mjs';
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';
5
+ import 'ethers';
6
+ import 'eventemitter3';
7
+
8
+ declare enum ErrorCode {
9
+ NOT_INITIALIZED = "NOT_INITIALIZED",
10
+ WALLET_NOT_CONNECTED = "WALLET_NOT_CONNECTED",
11
+ INVALID_CHAIN = "INVALID_CHAIN",
12
+ INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE",
13
+ INSUFFICIENT_ALLOWANCE = "INSUFFICIENT_ALLOWANCE",
14
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
15
+ STAKE_FAILED = "STAKE_FAILED",
16
+ UNSTAKE_FAILED = "UNSTAKE_FAILED",
17
+ COOLDOWN_FAILED = "COOLDOWN_FAILED",
18
+ MINT_FAILED = "MINT_FAILED",
19
+ REDEEM_FAILED = "REDEEM_FAILED",
20
+ INVALID_ORDER = "INVALID_ORDER",
21
+ SIGNATURE_FAILED = "SIGNATURE_FAILED",
22
+ API_ERROR = "API_ERROR",
23
+ VALIDATION_ERROR = "VALIDATION_ERROR"
24
+ }
25
+ declare class DeploySDKError extends Error {
26
+ readonly code: ErrorCode;
27
+ readonly originalError?: any;
28
+ constructor(code: ErrorCode, message: string, originalError?: any);
29
+ toJSON(): {
30
+ name: string;
31
+ code: ErrorCode;
32
+ message: string;
33
+ originalError: any;
34
+ };
35
+ }
36
+
37
+ declare const CONTRACT_ADDRESSES: Record<number, Record<string, string>>;
38
+ declare const COLLATERAL_ASSETS: Record<string, CollateralAsset>;
39
+ declare const STAKE_TOKENS: Record<string, StakeToken>;
40
+ declare const EIP712_TYPES_ORDER: {
41
+ Order: {
42
+ name: string;
43
+ type: string;
44
+ }[];
45
+ };
46
+ declare const ERC4626_ABI: string[];
47
+ declare const ERC20_ABI: string[];
48
+ declare const MINTER_ABI: string[];
49
+
50
+ export { COLLATERAL_ASSETS, CONTRACT_ADDRESSES, CollateralAsset, DeploySDKError, EIP712_TYPES_ORDER, ERC20_ABI, ERC4626_ABI, ErrorCode, MINTER_ABI, STAKE_TOKENS, StakeToken };
@@ -0,0 +1,50 @@
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
+ import { C as CollateralAsset, S as StakeToken } from './base-DLLHDCZ5.js';
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';
5
+ import 'ethers';
6
+ import 'eventemitter3';
7
+
8
+ declare enum ErrorCode {
9
+ NOT_INITIALIZED = "NOT_INITIALIZED",
10
+ WALLET_NOT_CONNECTED = "WALLET_NOT_CONNECTED",
11
+ INVALID_CHAIN = "INVALID_CHAIN",
12
+ INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE",
13
+ INSUFFICIENT_ALLOWANCE = "INSUFFICIENT_ALLOWANCE",
14
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
15
+ STAKE_FAILED = "STAKE_FAILED",
16
+ UNSTAKE_FAILED = "UNSTAKE_FAILED",
17
+ COOLDOWN_FAILED = "COOLDOWN_FAILED",
18
+ MINT_FAILED = "MINT_FAILED",
19
+ REDEEM_FAILED = "REDEEM_FAILED",
20
+ INVALID_ORDER = "INVALID_ORDER",
21
+ SIGNATURE_FAILED = "SIGNATURE_FAILED",
22
+ API_ERROR = "API_ERROR",
23
+ VALIDATION_ERROR = "VALIDATION_ERROR"
24
+ }
25
+ declare class DeploySDKError extends Error {
26
+ readonly code: ErrorCode;
27
+ readonly originalError?: any;
28
+ constructor(code: ErrorCode, message: string, originalError?: any);
29
+ toJSON(): {
30
+ name: string;
31
+ code: ErrorCode;
32
+ message: string;
33
+ originalError: any;
34
+ };
35
+ }
36
+
37
+ declare const CONTRACT_ADDRESSES: Record<number, Record<string, string>>;
38
+ declare const COLLATERAL_ASSETS: Record<string, CollateralAsset>;
39
+ declare const STAKE_TOKENS: Record<string, StakeToken>;
40
+ declare const EIP712_TYPES_ORDER: {
41
+ Order: {
42
+ name: string;
43
+ type: string;
44
+ }[];
45
+ };
46
+ declare const ERC4626_ABI: string[];
47
+ declare const ERC20_ABI: string[];
48
+ declare const MINTER_ABI: string[];
49
+
50
+ export { COLLATERAL_ASSETS, CONTRACT_ADDRESSES, CollateralAsset, DeploySDKError, EIP712_TYPES_ORDER, ERC20_ABI, ERC4626_ABI, ErrorCode, MINTER_ABI, STAKE_TOKENS, StakeToken };
package/dist/index.js ADDED
@@ -0,0 +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});
package/dist/index.mjs ADDED
@@ -0,0 +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-YEI5UNBO.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};
@@ -0,0 +1,4 @@
1
+ export { C as CooldownResult, a as CooldownStatus, 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 } from '../index-B9tOEGVF.mjs';
2
+ import 'ethers';
3
+ import 'eventemitter3';
4
+ import '../base-DLLHDCZ5.mjs';
@@ -0,0 +1,4 @@
1
+ export { C as CooldownResult, a as CooldownStatus, 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 } from '../index-CY6ZN0n3.js';
2
+ import 'ethers';
3
+ import 'eventemitter3';
4
+ import '../base-DLLHDCZ5.js';
@@ -0,0 +1 @@
1
+ "use strict";var h=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var v=(c,t)=>{for(var r in t)h(c,r,{get:t[r],enumerable:!0})},U=(c,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of x(t))!C.call(c,n)&&n!==r&&h(c,n,{get:()=>t[n],enumerable:!(e=N(t,n))||e.enumerable});return c};var L=c=>U(h({},"__esModule",{value:!0}),c);var F={};v(F,{MintModule:()=>E,RedeemModule:()=>R,StakeModule:()=>I,UnstakeModule:()=>_});module.exports=L(F);var k=require("ethers");var o=class c extends Error{constructor(t,r,e){super(r),this.name="DeploySDKError",this.code=t,this.originalError=e,Error.captureStackTrace&&Error.captureStackTrace(this,c)}toJSON(){return{name:this.name,code:this.code,message:this.message,originalError:this.originalError?.message||this.originalError}}};var g={1:{USDC:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",USDT:"0xdac17f958d2ee523a2206206994597c13d831ec7",dUSD:"0xf42e0b98e32150fe02a370456e6479fcd94f5531",DUSD_MINTER:"0x1ee453Ea35f6EAbD9BFF126586322cbC906D4EB3",sDUSD_STAKING:"0x7f37B0133B1adC1D0647EE52eA38fA13caC4aA1B"},42161:{}},T={USDC:{key:"USDC",name:"USD Coin",symbol:"USDC",address:g[1].USDC,decimals:6,mintingContract:g[1].DUSD_MINTER},USDT:{key:"USDT",name:"Tether USD",symbol:"USDT",address:g[1].USDT,decimals:6,mintingContract:g[1].DUSD_MINTER}},G={dUSD:{key:"dUSD",name:"Deploy USD",symbol:"dUSD",address:g[1].dUSD,decimals:18,supportedCollateral:[T.USDC,T.USDT],mintingContract:g[1].DUSD_MINTER,stakingContract:g[1].sDUSD_STAKING,stakingSymbol:"sDUSD",cooldownPeriod:2160*60*60*1e3}},y={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"}]},l=["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)"];var f=["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 E=class{constructor(t){this.sdk=t}async createOrder(t,r,e,n){let s=await this.sdk.getAddress(),a=crypto.randomUUID(),d=Math.floor(Date.now()/1e3)+(n?.expiryMinutes||5)*60,i=t.mintingContract;return{orderId:a,orderType:0,expiry:d,nonce:Date.now(),benefactor:n?.benefactor||s,beneficiary:n?.beneficiary||s,collateralAsset:t.address,collateralAmount:r.toString(),dAssetAmount:e.toString(),minterAddress:i}}async signOrder(t){let r=this.sdk.signer,e={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 r._signTypedData(e,y,n)}catch(s){throw new o("SIGNATURE_FAILED","Failed to sign mint order",s)}}async submitOrder(t,r){try{let e=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:r}})});if(!e.ok){let s=await e.json();throw new o("API_ERROR",s.message||"Failed to submit mint order")}let n=await e.json();return{success:!0,orderId:t.orderId,txHash:n.txHash,status:n.status}}catch(e){throw e instanceof o?e:new o("API_ERROR","Failed to submit mint order",e)}}async mint(t,r,e,n){try{let s=await this.createOrder(t,r,e,n),a=await this.signOrder(s);return await this.submitOrder(s,a)}catch(s){throw s instanceof o?s:new o("MINT_FAILED","Failed to mint tokens",s)}}async estimateGas(t,r,e,n){let s=new k.Contract(t.mintingContract,f,this.sdk.provider),a={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:r.toString(),dAsset_amount:e.toString()};try{return(await s.estimateGas.mint(a,{addresses:[],ratios:[]},{signature_type:0,signature_bytes:n})).toBigInt()}catch(d){throw new o("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:r,amount:e,receiver:n}=t;if(!r.stakingContract)throw new o("VALIDATION_ERROR",`Token ${r.symbol} does not support staking`);let s=new u.Contract(r.stakingContract,l,this.sdk.signer),a=n||await this.sdk.getAddress(),i=await(await s.deposit(e,a)).wait(),m,p=i.events?.find(A=>A.event==="Deposit");return p&&(m=p.args?.shares?.toString()),{success:!0,txHash:i.transactionHash,sharesReceived:m}}catch(r){throw r instanceof o?r:new o("STAKE_FAILED","Failed to stake tokens",r)}}async getPosition(t,r){if(!t.stakingContract)throw new o("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let e=r||await this.sdk.getAddress(),n=new u.Contract(t.stakingContract,l,this.sdk.provider);try{let[s,a,d]=await Promise.all([n.balanceOf(e),n.convertToAssets(await n.balanceOf(e)),n.cooldowns(e).catch(()=>({cooldownEnd:u.BigNumber.from(0),underlyingAmount:u.BigNumber.from(0)}))]),i=d.cooldownEnd.toNumber()*1e3;return{tokenKey:t.key,stakedAmount:s.toString(),stakedValue:a.toString(),cooldownEnd:i>0?i:void 0,canUnstake:i===0||i<=Date.now()}}catch(s){throw new o("VALIDATION_ERROR","Failed to fetch staking position",s)}}async previewStake(t,r){if(!t.stakingContract)throw new o("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let e=new u.Contract(t.stakingContract,l,this.sdk.provider);try{return{shares:(await e.convertToShares(r)).toString(),assets:r.toString()}}catch(n){throw new o("VALIDATION_ERROR","Failed to preview stake",n)}}async getAPY(t){if(!t.stakingContract)return 0;let r=new u.Contract(t.stakingContract,l,this.sdk.provider);try{let[e,n]=await Promise.all([r.totalAssets(),r.totalSupply()]);if(n.isZero())return 0;let s=e.mul(u.BigNumber.from(10).pow(18)).div(n),a=u.BigNumber.from(10).pow(18);return s.lte(a)?0:s.sub(a).mul(365).mul(1e4).div(a).toNumber()/100}catch{return 0}}};var w=require("ethers");var _=class{constructor(t){this.sdk=t}async initiateCooldown(t,r){try{if(!t.stakingContract)throw new o("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let s=await(await new w.Contract(t.stakingContract,l,this.sdk.signer).cooldownShares(r)).wait(),a=Date.now()+(t.cooldownPeriod||2160*60*60*1e3);return{success:!0,txHash:s.transactionHash,cooldownEnd:a}}catch(e){throw e instanceof o?e:new o("COOLDOWN_FAILED","Failed to initiate cooldown",e)}}async unstake(t){try{let{token:r,sharesAmount:e,receiver:n}=t;if(!r.stakingContract)throw new o("VALIDATION_ERROR",`Token ${r.symbol} does not support staking`);let s=await this.getCooldownStatus(r);if(!s.canUnstake)throw new o("VALIDATION_ERROR",`Cannot unstake. Cooldown ends at ${new Date(s.cooldownEnd).toLocaleString()}`);let a=new w.Contract(r.stakingContract,l,this.sdk.signer),d=n||await this.sdk.getAddress(),i=await this.sdk.getAddress(),p=await(await a.redeem(e,d,i)).wait(),A,S=p.events?.find(O=>O.event==="Withdraw");return S&&(A=S.args?.assets?.toString()),{success:!0,txHash:p.transactionHash,assetsWithdrawn:A}}catch(r){throw r instanceof o?r:new o("UNSTAKE_FAILED","Failed to unstake tokens",r)}}async getCooldownStatus(t,r){if(!t.stakingContract)throw new o("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let e=r||await this.sdk.getAddress(),n=new w.Contract(t.stakingContract,l,this.sdk.provider);try{let s=await n.cooldowns(e),a=s.cooldownEnd.toNumber()*1e3;return{cooldownEnd:a,sharesInCooldown:s.underlyingAmount.toString(),canUnstake:a>0&&a<=Date.now()}}catch(s){throw new o("VALIDATION_ERROR","Failed to fetch cooldown status",s)}}async previewUnstake(t,r){if(!t.stakingContract)throw new o("VALIDATION_ERROR",`Token ${t.symbol} does not support staking`);let e=new w.Contract(t.stakingContract,l,this.sdk.provider);try{return(await e.convertToAssets(r)).toString()}catch(n){throw new o("VALIDATION_ERROR","Failed to preview unstake",n)}}};var b=require("ethers");var R=class{constructor(t){this.sdk=t}async createOrder(t,r,e,n,s){let a=await this.sdk.getAddress(),d=crypto.randomUUID(),i=Math.floor(Date.now()/1e3)+(s?.expiryMinutes||5)*60,m=t.mintingContract;return{orderId:d,orderType:1,expiry:i,nonce:Date.now(),benefactor:s?.benefactor||a,beneficiary:s?.beneficiary||a,collateralAsset:e,collateralAmount:n.toString(),dAssetAmount:r.toString(),minterAddress:m}}async signOrder(t){let r=this.sdk.signer,e={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 r._signTypedData(e,y,n)}catch(s){throw new o("SIGNATURE_FAILED","Failed to sign redeem order",s)}}async submitOrder(t,r){try{let e=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:r}})});if(!e.ok){let s=await e.json();throw new o("API_ERROR",s.message||"Failed to submit redeem order")}let n=await e.json();return{success:!0,orderId:t.orderId,txHash:n.txHash,status:n.status}}catch(e){throw e instanceof o?e:new o("API_ERROR","Failed to submit redeem order",e)}}async redeem(t,r,e,n,s){try{let a=await this.createOrder(t,r,e,n,s),d=await this.signOrder(a);return await this.submitOrder(a,d)}catch(a){throw a instanceof o?a:new o("REDEEM_FAILED","Failed to redeem tokens",a)}}async estimateGas(t,r,e,n,s){let a=new b.Contract(t.mintingContract,f,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:e,collateral_amount:n.toString(),dAsset_amount:r.toString()};try{return(await a.estimateGas.redeem(d,{signature_type:0,signature_bytes:s})).toBigInt()}catch(i){throw new o("TRANSACTION_FAILED","Failed to estimate gas for redeem",i)}}};0&&(module.exports={MintModule,RedeemModule,StakeModule,UnstakeModule});
@@ -0,0 +1 @@
1
+ import{j as a,k as b,l as c,m as d}from"../chunk-QZGD3DFS.mjs";import"../chunk-XSAEU2QV.mjs";export{a as MintModule,d as RedeemModule,b as StakeModule,c as UnstakeModule};
@@ -0,0 +1,38 @@
1
+ import { W as WalletAdapter, a as ChainId } from '../base-DLLHDCZ5.mjs';
2
+
3
+ interface PrivyInterface {
4
+ getEthereumProvider(): Promise<any>;
5
+ user?: {
6
+ wallet?: {
7
+ address: string;
8
+ };
9
+ };
10
+ }
11
+ declare class PrivyAdapter implements WalletAdapter {
12
+ private privy;
13
+ name: string;
14
+ constructor(privy: PrivyInterface);
15
+ getProvider(): Promise<any>;
16
+ getSigner(): Promise<any>;
17
+ isConnected(): Promise<boolean>;
18
+ }
19
+
20
+ interface EthereumProvider {
21
+ request: (args: {
22
+ method: string;
23
+ params?: any[];
24
+ }) => Promise<any>;
25
+ on?: (event: string, callback: (...args: any[]) => void) => void;
26
+ }
27
+ declare class ExternalWalletAdapter implements WalletAdapter {
28
+ private ethereum;
29
+ name: string;
30
+ constructor(ethereum: EthereumProvider);
31
+ getProvider(): Promise<any>;
32
+ getSigner(): Promise<any>;
33
+ isConnected(): Promise<boolean>;
34
+ switchChain(chainId: ChainId): Promise<void>;
35
+ private addChain;
36
+ }
37
+
38
+ export { ExternalWalletAdapter, PrivyAdapter, WalletAdapter };
@@ -0,0 +1,38 @@
1
+ import { W as WalletAdapter, a as ChainId } from '../base-DLLHDCZ5.js';
2
+
3
+ interface PrivyInterface {
4
+ getEthereumProvider(): Promise<any>;
5
+ user?: {
6
+ wallet?: {
7
+ address: string;
8
+ };
9
+ };
10
+ }
11
+ declare class PrivyAdapter implements WalletAdapter {
12
+ private privy;
13
+ name: string;
14
+ constructor(privy: PrivyInterface);
15
+ getProvider(): Promise<any>;
16
+ getSigner(): Promise<any>;
17
+ isConnected(): Promise<boolean>;
18
+ }
19
+
20
+ interface EthereumProvider {
21
+ request: (args: {
22
+ method: string;
23
+ params?: any[];
24
+ }) => Promise<any>;
25
+ on?: (event: string, callback: (...args: any[]) => void) => void;
26
+ }
27
+ declare class ExternalWalletAdapter implements WalletAdapter {
28
+ private ethereum;
29
+ name: string;
30
+ constructor(ethereum: EthereumProvider);
31
+ getProvider(): Promise<any>;
32
+ getSigner(): Promise<any>;
33
+ isConnected(): Promise<boolean>;
34
+ switchChain(chainId: ChainId): Promise<void>;
35
+ private addChain;
36
+ }
37
+
38
+ export { ExternalWalletAdapter, PrivyAdapter, WalletAdapter };
@@ -0,0 +1 @@
1
+ "use strict";var a=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var d=(r,e)=>{for(var i in e)a(r,i,{get:e[i],enumerable:!0})},l=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of m(e))!h.call(r,n)&&n!==i&&a(r,n,{get:()=>e[n],enumerable:!(t=c(e,n))||t.enumerable});return r};var u=r=>l(a({},"__esModule",{value:!0}),r);var p={};d(p,{ExternalWalletAdapter:()=>o,PrivyAdapter:()=>s});module.exports=u(p);var s=class{constructor(e){this.privy=e;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 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 i=`0x${e.toString(16)}`;try{await this.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]})}catch(t){if(t.code===4902)await this.addChain(e);else throw t}}async addChain(e){let t={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(!t)throw new Error(`Chain ${e} not supported`);await this.ethereum.request({method:"wallet_addEthereumChain",params:[t]})}};0&&(module.exports={ExternalWalletAdapter,PrivyAdapter});
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunk-YEI5UNBO.mjs";import"../chunk-XSAEU2QV.mjs";export{b as ExternalWalletAdapter,a as PrivyAdapter};
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "deploy-sdk",
3
+ "version": "0.0.1",
4
+ "description": "Deploy SDK - Complete DeFi interaction library with support for mint, stake, unstake, and redeem operations",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./wallet-adapters": {
15
+ "types": "./dist/wallet-adapters/index.d.ts",
16
+ "import": "./dist/wallet-adapters/index.mjs",
17
+ "require": "./dist/wallet-adapters/index.js"
18
+ },
19
+ "./modules": {
20
+ "types": "./dist/modules/index.d.ts",
21
+ "import": "./dist/modules/index.mjs",
22
+ "require": "./dist/modules/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsup src/index.ts src/wallet-adapters/index.ts src/modules/index.ts --format cjs,esm --dts --minify",
30
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
31
+ "lint": "eslint src --ext .ts",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest",
34
+ "prepublishOnly": "npm run build"
35
+ },
36
+ "keywords": [
37
+ "defi",
38
+ "staking",
39
+ "ethereum",
40
+ "web3",
41
+ "sdk",
42
+ "erc4626",
43
+ "eip712"
44
+ ],
45
+ "author": "Deploy Team",
46
+ "license": "MIT",
47
+ "peerDependencies": {
48
+ "ethers": ">=5.0.0"
49
+ },
50
+ "dependencies": {
51
+ "eventemitter3": "^5.0.1"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^20.0.0",
55
+ "@typescript-eslint/eslint-plugin": "^7.0.0",
56
+ "@typescript-eslint/parser": "^7.0.0",
57
+ "eslint": "^8.57.0",
58
+ "ethers": "^5.8.0",
59
+ "tsup": "^8.0.0",
60
+ "typescript": "^5.3.0",
61
+ "vitest": "^1.0.0"
62
+ },
63
+ "engines": {
64
+ "node": ">=18.0.0"
65
+ }
66
+ }