Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@avalabs/bitcoin-module

Package Overview
Dependencies
Maintainers
0
Versions
360
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@avalabs/bitcoin-module - npm Package Compare versions

Comparing version 0.0.0-feat-p-dynamic-fees-ray-20241107155908 to 0.0.0-feat-p-dynamic-fees-ray-20241108142637

4

dist/index.js

@@ -9,6 +9,6 @@ import { parseManifest, RpcMethod, Environment, TokenType, WalletType, NetworkVMType, TransactionType, DetailItemType, RawSimplePriceResponseSchema, SimplePriceResponseSchema } from '@avalabs/vm-module-types';

var Ae=Object.defineProperty;var De=(t,e,r)=>e in t?Ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var ne=(t,e,r)=>(De(t,typeof e!="symbol"?e+"":e,r),r),oe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var l=(t,e,r)=>(oe(t,e,"read from private field"),r?r.call(t):e.get(t)),D=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r);},C=(t,e,r,n)=>(oe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);var Ce={glacierApiUrl:"https://glacier-api.avax.network",proxyApiUrl:"https://proxy-api.avax.network"},_e={glacierApiUrl:"https://glacier-api-dev.avax.network",proxyApiUrl:"https://proxy-api-dev.avax.network"},se=t=>{switch(t){case Environment.PRODUCTION:return Ce;case Environment.DEV:return _e}};var ie={name:"Bitcoin",description:"",version:"0.0.1",sources:{module:{checksum:"",location:{npm:{filePath:"dist/bundle.js",packageName:"@avalabs/bitcoin-module",registry:"https://registry.npmjs.org"}}},provider:{checksum:"",location:{npm:{filePath:"dist/provider.js",packageName:"@avalabs/bitcoin-module",registry:"https://registry.npmjs.org"}}}},network:{chainIds:["bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],namespaces:["bip122"]},cointype:"0",permissions:{rpc:{dapps:!0,methods:["bitcoin_sendTransaction","bitcoin_signTransaction"]}},manifestVersion:"0.0"};var f=async({isTestnet:t,proxyApiUrl:e})=>new BitcoinProvider(!t,void 0,`${e}/proxy/nownodes/${t?"btcbook-testnet":"btcbook"}`,`${e}/proxy/nownodes/${t?"btc-testnet":"btc"}`,process.env.GLACIER_API_KEY?{token:process.env.GLACIER_API_KEY}:{});async function ce({isTestnet:t,proxyApiUrl:e}){let r=await f({isTestnet:t,proxyApiUrl:e}),{high:n,low:o,medium:a}=await r.getFeeRates();return {low:{maxFeePerGas:BigInt(o)},medium:{maxFeePerGas:BigInt(a)},high:{maxFeePerGas:BigInt(n)},isFixedFee:!1}}var me=(t,{address:e,network:r})=>{let{explorerUrl:n,networkToken:o}=r,a=t.addresses[0]??"";return {chainId:r.chainId.toString(),explorerLink:`${n}/tx/${t.hash}`,from:t.isSender?e:a,gasUsed:t.fee.toString(),hash:t.hash,isContractCall:!1,isIncoming:!t.isSender,isOutgoing:t.isSender,isSender:t.isSender,timestamp:t.receivedTime*1e3,to:t.isSender?a:e,tokens:[{amount:(Math.abs(t.amount)/10**o.decimals).toString(),decimal:o.decimals.toString(),name:o.name,symbol:o.symbol,type:TokenType.NATIVE}],txType:t.isSender?TransactionType.SEND:TransactionType.RECEIVE}};var le=async({address:t,network:e,proxyApiUrl:r})=>(await(await f({isTestnet:!!e.isTestnet,proxyApiUrl:r})).getTxHistory(t)).map(a=>me(a,{address:t,network:e}));var ee=async({operation:t,isSuccess:e,maxRetries:r=10,backoffPolicy:n=O.exponential()})=>{let o=0,a=0,s;for(;a<r;){a>0&&await Oe(o);try{let i=await t(a);if(e(i))return i}catch(i){s=i;}o=n(a),a++;}let c=s?`Max retry exceeded. ${s}`:"Max retry exceeded.";throw new Error(c)},O=class{static exponential(){return e=>Math.pow(2,e)*1e3}static constant(e){return r=>e*1e3}static constantMs(e){return r=>e}};function Oe(t){return new Promise(e=>setTimeout(e,t))}var te=t=>ee({operation:e=>t(e>0),maxRetries:2,backoffPolicy:O.constant(1),isSuccess:e=>e?.status?.error_code!==429});function de(t){let e,r=0;for(e=0;e<t.length;e++)r+=t.charCodeAt(e)*(e+1);return r}function re(t){let e,r=0;for(e=0;e<t.length;e++){let n=de(t[e]??"");r=r+65027/n;}return (""+r).slice(0,16)}async function V(t,e){let r=await fetch(...t);if(!r.ok)throw new Error(`Request failed with status ${r.status}`);let n=await r.json();return e.parse(n)}var H=class{constructor(e){this.proxyApiUrl=e;}simplePrice(e){let r=new URLSearchParams(e);return V([`${this.proxyApiUrl}/proxy/coingecko/simple/price?${r}`,{method:"POST",headers:{"Content-Type":"application/json"}}],RawSimplePriceResponseSchema)}simplePriceByContractAddresses(e){let{id:r,...n}=e,o=new URLSearchParams(n);return V([`${this.proxyApiUrl}/proxy/coingecko/simple/token_price/${r}?${o}`,{method:"POST",headers:{"Content-Type":"application/json"}}],SimplePriceResponseSchema)}};var ue=getBasicCoingeckoHttp(),S,_,G=class{constructor({storage:e,proxyApiUrl:r}){D(this,S,void 0);D(this,_,void 0);ne(this,"transformSimplePriceResponse",(e,r=[VsCurrencyType.USD])=>{let n={};return Object.keys(e).forEach(o=>{let a=e[o];n[o]={},r.forEach(s=>{n[o]={[s]:{price:a?.[s],change24:a?.[`${s}_24h_change`],vol24:a?.[`${s}_24h_vol`],marketCap:a?.[`${s}_market_cap`]}};});}),n});C(this,S,e),C(this,_,r);}async getSimplePrice({coinIds:e=[],currencies:r=[VsCurrencyType.USD]}){let n,a=`getSimplePrice-${e?`${re(e)}-${r.toString()}`:`${r.toString()}`}`;if(n=l(this,S)?.get?.(a),n)return n;try{n=await te(s=>this.simplePrice({coinIds:e,currencies:r,marketCap:!0,vol24:!0,change24:!0,useCoingeckoProxy:s}));}catch{n=void 0;}return l(this,S)?.set?.(a,n),n}async getPricesByAddresses(e,r,n=VsCurrencyType.USD){let o,s=`getPricesWithMarketDataByAddresses-${`${re(e)}-${r}-${n}`}`;if(o=l(this,S)?.get?.(s),o)return o;try{o=await te(c=>this.fetchPricesByAddresses({assetPlatformId:r,tokenAddresses:e,currency:n,useCoingeckoProxy:c}));}catch{o=void 0;}return l(this,S)?.set?.(s,o),o}async fetchPricesByAddresses({assetPlatformId:e,tokenAddresses:r,currency:n=VsCurrencyType.USD,useCoingeckoProxy:o=!1}){return o?new H(l(this,_)).simplePriceByContractAddresses({id:e,contract_addresses:r,vs_currencies:[n],include_market_cap:!0,include_24hr_vol:!0,include_24hr_change:!0}):simpleTokenPrice(ue,{assetPlatformId:e,tokenAddresses:r,currencies:[n],marketCap:!0,vol24:!0,change24:!0})}async simplePrice({coinIds:e=[],currencies:r=[VsCurrencyType.USD],marketCap:n=!1,vol24:o=!1,change24:a=!1,lastUpdated:s=!1,useCoingeckoProxy:c=!1,shouldThrow:i=!0}){if(c){let p=await new H(l(this,_)).simplePrice({ids:e,vs_currencies:r,include_market_cap:n,include_24hr_vol:o,include_24hr_change:a,include_last_updated_at:s});return this.transformSimplePriceResponse(p,r)}return simplePrice(ue,{coinIds:e,currencies:r,marketCap:n,vol24:o,change24:a,lastUpdated:s,shouldThrow:i})}};S=new WeakMap,_=new WeakMap;object({date:string(),usd:record(number())});var ye=(t,e,r,n)=>({type:DetailItemType.FUNDS_RECIPIENT,label:t,amount:e,maxDecimals:r,symbol:n}),E=(t,e,r,n)=>({label:t,type:DetailItemType.CURRENCY,value:e,maxDecimals:r,symbol:n});var X=(t,e)=>({label:t,value:e,type:DetailItemType.LINK}),N=(t,e)=>({label:t,type:DetailItemType.ADDRESS,value:e});var fe=(t,e,r)=>{let n=r?.[t]?.[e??""]??{};return {priceInCurrency:n.price??void 0,marketCap:n.marketCap??void 0,vol24:n.vol24??void 0,change24:n.change24??void 0}};var j=async({addresses:t,currency:e,network:r,withScripts:n=!1,proxyApiUrl:o,storage:a})=>{let s=await f({isTestnet:!!r.isTestnet,proxyApiUrl:o}),c=new G({proxyApiUrl:o,storage:a}),i=r.pricingProviders?.coingecko.nativeTokenId,d=typeof e=="string"&&typeof i=="string"?await c.getSimplePrice({coinIds:[i],currencies:[e]}):void 0,{priceInCurrency:m,change24:h,marketCap:g,vol24:P}=fe(i??"",e,d);return (await Promise.allSettled(t.map(async y=>{let{balance:T,utxos:w,balanceUnconfirmed:A,utxosUnconfirmed:k}=await s.getUtxoBalance(y,n),b=new TokenUnit(T,r.networkToken.decimals,r.networkToken.symbol),I=m!==void 0?b.mul(m):void 0,R=b.toDisplay(),B=new TokenUnit(A,r.networkToken.decimals,r.networkToken.symbol),$=m!==void 0?B.mul(m):void 0,we=r.networkToken.symbol;return {[y]:{[we]:{...r.networkToken,utxos:w,utxosUnconfirmed:k,coingeckoId:i??"",type:TokenType.NATIVE,balance:b.toSubUnit(),balanceDisplayValue:R,balanceInCurrency:I?.toDisplay({fixedDp:2,asNumber:!0}),balanceCurrencyDisplayValue:I?.toDisplay({fixedDp:2}),priceInCurrency:m,marketCap:g,vol24:P,change24:h,unconfirmedBalance:B.toSubUnit(),unconfirmedBalanceDisplayValue:B.toDisplay(),unconfirmedBalanceInCurrency:$?.toDisplay({fixedDp:2,asNumber:!0}),unconfirmedBalanceCurrencyDisplayValue:$?.toDisplay({fixedDp:2})}}}}))).reduce((y,T)=>T.status==="rejected"?y:{...y,...T.value},{})};var he=async({accountIndex:t,xpub:e,isTestnet:r,walletType:n})=>{switch(n){case WalletType.Mnemonic:case WalletType.Ledger:case WalletType.Keystone:return {[NetworkVMType.BITCOIN]:getBech32AddressFromXPub(e,t,r?networks.testnet:networks.bitcoin)};case WalletType.LedgerLive:case WalletType.Seedless:{let o=Buffer.from(e,"hex");return {[NetworkVMType.BITCOIN]:getBtcAddressFromPubKey(o,r?networks.testnet:networks.bitcoin)}}default:throw rpcErrors.invalidParams(`Unsupported wallet type: ${n}`)}};var Ye=z$1.object({from:z$1.string(),to:z$1.string(),amount:z$1.number(),feeRate:z$1.number()}),xe=t=>Ye.safeParse(t);var Pe=t=>{if(!t)return !1;let e="utxos"in t,r="locked"in t,n="unlockedUnstaked"in t;return e&&!n&&!r};var z=(t,e)=>t/e;var K=new Map,be=(t,e,r,n)=>(K.set(t,{signingData:e,displayData:r}),{updateTx:({feeRate:o})=>{let a=K.get(t);if(!a)throw rpcErrors.resourceNotFound();let{signingData:s}=a;if(typeof o>"u"||o===s.data.feeRate)return a;let{account:c,data:{to:i,amount:p,balance:d}}=s,{inputs:m,outputs:h,fee:g}=createTransferTx(i,c,p,o,d.utxos,n.getNetwork());if(!m||!h)throw rpcErrors.internal("Unable to create transaction");let P={...s,data:{...s.data,fee:g,feeRate:o,gasLimit:z(g,o),inputs:m,outputs:h}},v={...a,signingData:P};return K.set(t,v),v},cleanup:()=>K.delete(t)});var Y=async({provider:t,txHash:e,onTransactionConfirmed:r,onTransactionReverted:n,requestId:o})=>{try{await t.waitForTx(e),r(e,o);}catch(a){console.error(a),n(e,o);}};var J=async(t,e)=>"txHash"in e?e.txHash:t.issueRawTx(e.signedData);var ke=async({request:t,network:e,approvalController:r,proxyApiUrl:n})=>{let{dappInfo:o,params:a}=t,{success:s,data:c,error:i}=xe(a);if(!s)return console.error("invalid params",i),{error:rpcErrors.invalidParams({message:"Transaction params are invalid",data:{cause:i}})};let d=(await j({addresses:[c.from],network:e,proxyApiUrl:n,withScripts:!0}))?.[c.from]?.[e.networkToken.symbol];if(!Pe(d))return {error:rpcErrors.internal("Balance for the source account is not available")};let m=await f({isTestnet:!!e.isTestnet,proxyApiUrl:n}),{to:h,from:g,amount:P,feeRate:v}=c,{inputs:y,outputs:T,fee:w}=createTransferTx(h,g,P,v,d.utxos,m.getNetwork());if(!y||!T)return {error:rpcErrors.internal("Unable to create transaction")};let A={title:"Approve Transaction",network:{chainId:e.chainId,name:e.chainName,logoUri:e.logoUri},details:[{title:"Transaction Details",items:[X("Website",o),N("From",g),N("To",h),E("Amount",BigInt(P),e.networkToken.decimals,e.networkToken.symbol)]}],networkFeeSelector:!0},k={type:RpcMethod.BITCOIN_SEND_TRANSACTION,account:g,data:{to:h,amount:P,fee:w,feeRate:v,gasLimit:z(w,v),inputs:y,outputs:T,balance:d}},{updateTx:b,cleanup:I}=be(t.requestId,k,A,m),R=await r.requestApproval({request:t,displayData:A,signingData:k,updateTx:b});if(I(),"error"in R)return {error:R.error};let B;try{B=await J(m,R);}catch($){return {error:rpcErrors.internal({message:"Unable to get transaction hash",data:{cause:$}})}}return Y({provider:m,txHash:B,onTransactionConfirmed:r.onTransactionConfirmed,onTransactionReverted:r.onTransactionReverted,requestId:t.requestId}),{result:B}};var et=z$1.object({txHash:z$1.string(),txHex:z$1.string().optional(),index:z$1.number(),value:z$1.number(),script:z$1.string().min(1),blockHeight:z$1.number(),confirmations:z$1.number(),confirmedTime:z$1.string().optional()}),tt=z$1.object({address:z$1.string(),value:z$1.number()}),rt=z$1.object({inputs:z$1.array(et).min(1),outputs:z$1.array(tt).min(1)}),Ie=t=>rt.safeParse(t);var Se=async({request:t,network:e,approvalController:r,proxyApiUrl:n})=>{let{dappInfo:o,params:a}=t,{success:s,data:c,error:i}=Ie(a);if(!s)return console.error("invalid params",i),{error:rpcErrors.invalidParams({message:"Transaction params are invalid",data:{cause:i}})};let p=await f({isTestnet:!!e.isTestnet,proxyApiUrl:n}),{details:d,error:m}=await at(c,p);if(m)return {error:rpcErrors.internal({message:"Transaction invalid or cannot be parsed",data:{cause:m}})};let{fee:h,fromAddress:g,outputs:P,transferTotal:v}=d,{decimals:y,symbol:T}=e.networkToken,w={title:"Approve Transaction",network:{chainId:e.chainId,name:e.chainName,logoUri:e.logoUri},details:[{title:"Transaction Details",items:[X("Website",o),N("From",g),E("Total Transferred Amount",BigInt(v),y,T)]},{title:"Recipients",items:P.map(({address:I,value:R})=>ye(I,BigInt(R),y,T))},{title:"Network Fee",items:[E("Total Fee",BigInt(h),y,T)]}],networkFeeSelector:!1},A={type:RpcMethod.BITCOIN_SIGN_TRANSACTION,account:g,data:{inputs:c.inputs,outputs:c.outputs}},k=await r.requestApproval({request:t,displayData:w,signingData:A});if("error"in k)return {error:k.error};let b;try{b=await J(p,k);}catch(I){return {error:rpcErrors.internal({message:"Unable to get transaction hash",data:{cause:I}})}}return Y({provider:p,txHash:b,onTransactionConfirmed:r.onTransactionConfirmed,onTransactionReverted:r.onTransactionReverted,requestId:t.requestId}),{result:b}},ot=t=>{let e=Array.from(new Set(t.map(({script:r})=>r)));if(e.length!==1)throw rpcErrors.invalidParams({message:`All input UTXOs must belong to a single address, found ${e.length}`});return e[0]},at=async(t,e)=>{try{let r=ot(t.inputs),n=await e.getAddressFromScript(r),o=t.outputs.filter(({address:p})=>p!==n),a=t.inputs.reduce((p,{value:d})=>p+d,0),s=t.outputs.reduce((p,{value:d})=>p+d,0),c=o.reduce((p,{value:d})=>p+d,0),i=a-s;return st(o),{error:null,details:{fromAddress:n,outputs:o,fee:i,transferTotal:c}}}catch(r){return console.error(r),{details:null,error:r instanceof Error?r:new Error(r?.toString()??"Unknown error")}}};function st(t){if(t.length<1)throw new Error("No actual output is provided, this transaction would only burn funds")}var x,U,Be=class{constructor({environment:e,approvalController:r}){D(this,x,void 0);D(this,U,void 0);let{proxyApiUrl:n}=se(e);C(this,U,r),C(this,x,n);}getProvider(e){return f({isTestnet:!!e.isTestnet,proxyApiUrl:l(this,x)})}getAddress({accountIndex:e,xpub:r,isTestnet:n,walletType:o}){return he({accountIndex:e,xpub:r,isTestnet:n,walletType:o})}getBalances({addresses:e,currency:r,network:n,storage:o}){return j({addresses:e,currency:r,network:n,proxyApiUrl:l(this,x),storage:o})}getManifest(){let e=parseManifest(ie);return e.success?e.data:void 0}getNetworkFee(e){return ce({isTestnet:!!e.isTestnet,proxyApiUrl:l(this,x)})}async getTransactionHistory({address:e,network:r}){return {transactions:await le({address:e,network:r,proxyApiUrl:l(this,x)})}}getTokens(e){return Promise.resolve([])}async onRpcRequest(e,r){switch(e.method){case RpcMethod.BITCOIN_SEND_TRANSACTION:return ke({request:e,network:r,approvalController:l(this,U),proxyApiUrl:l(this,x)});case RpcMethod.BITCOIN_SIGN_TRANSACTION:return Se({request:e,network:r,approvalController:l(this,U),proxyApiUrl:l(this,x)});default:return {error:rpcErrors.methodNotSupported(`Method ${e.method} not supported`)}}}};x=new WeakMap,U=new WeakMap;
var Ae=Object.defineProperty;var De=(t,e,r)=>e in t?Ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var oe=(t,e,r)=>(De(t,typeof e!="symbol"?e+"":e,r),r),ne=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var l=(t,e,r)=>(ne(t,e,"read from private field"),r?r.call(t):e.get(t)),D=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r);},C=(t,e,r,o)=>(ne(t,e,"write to private field"),o?o.call(t,r):e.set(t,r),r);var Ce={glacierApiUrl:"https://glacier-api.avax.network",proxyApiUrl:"https://proxy-api.avax.network"},Ee={glacierApiUrl:"https://glacier-api-dev.avax.network",proxyApiUrl:"https://proxy-api-dev.avax.network"},se=t=>{switch(t){case Environment.PRODUCTION:return Ce;case Environment.DEV:return Ee}};var ie={name:"Bitcoin",description:"",version:"0.0.1",sources:{module:{checksum:"",location:{npm:{filePath:"dist/bundle.js",packageName:"@avalabs/bitcoin-module",registry:"https://registry.npmjs.org"}}},provider:{checksum:"",location:{npm:{filePath:"dist/provider.js",packageName:"@avalabs/bitcoin-module",registry:"https://registry.npmjs.org"}}}},network:{chainIds:["bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],namespaces:["bip122"]},cointype:"0",permissions:{rpc:{dapps:!0,methods:["bitcoin_sendTransaction","bitcoin_signTransaction"]}},manifestVersion:"0.0"};var f=async({isTestnet:t,proxyApiUrl:e})=>new BitcoinProvider(!t,void 0,`${e}/proxy/nownodes/${t?"btcbook-testnet":"btcbook"}`,`${e}/proxy/nownodes/${t?"btc-testnet":"btc"}`,process.env.GLACIER_API_KEY?{token:process.env.GLACIER_API_KEY}:{});async function ce({isTestnet:t,proxyApiUrl:e}){let r=await f({isTestnet:t,proxyApiUrl:e}),{high:o,low:n,medium:a}=await r.getFeeRates();return {low:{maxFeePerGas:BigInt(n)},medium:{maxFeePerGas:BigInt(a)},high:{maxFeePerGas:BigInt(o)},isFixedFee:!1}}var me=(t,{address:e,network:r})=>{let{explorerUrl:o,networkToken:n}=r,a=t.addresses[0]??"";return {chainId:r.chainId.toString(),explorerLink:`${o}/tx/${t.hash}`,from:t.isSender?e:a,gasUsed:t.fee.toString(),hash:t.hash,isContractCall:!1,isIncoming:!t.isSender,isOutgoing:t.isSender,isSender:t.isSender,timestamp:t.receivedTime*1e3,to:t.isSender?a:e,tokens:[{amount:(Math.abs(t.amount)/10**n.decimals).toString(),decimal:n.decimals.toString(),name:n.name,symbol:n.symbol,type:TokenType.NATIVE}],txType:t.isSender?TransactionType.SEND:TransactionType.RECEIVE}};var le=async({address:t,network:e,proxyApiUrl:r})=>(await(await f({isTestnet:!!e.isTestnet,proxyApiUrl:r})).getTxHistory(t)).map(a=>me(a,{address:t,network:e}));var ee=async({operation:t,isSuccess:e,maxRetries:r=10,backoffPolicy:o=O.exponential()})=>{let n=0,a=0,s;for(;a<r;){a>0&&await Oe(n);try{let i=await t(a);if(e(i))return i}catch(i){s=i;}n=o(a),a++;}let c=s?`Max retry exceeded. ${s}`:"Max retry exceeded.";throw new Error(c)},O=class{static exponential(){return e=>Math.pow(2,e)*1e3}static constant(e){return r=>e*1e3}static constantMs(e){return r=>e}};function Oe(t){return new Promise(e=>setTimeout(e,t))}var te=t=>ee({operation:e=>t(e>0),maxRetries:2,backoffPolicy:O.constant(1),isSuccess:e=>e?.status?.error_code!==429});function de(t){let e,r=0;for(e=0;e<t.length;e++)r+=t.charCodeAt(e)*(e+1);return r}function re(t){let e,r=0;for(e=0;e<t.length;e++){let o=de(t[e]??"");r=r+65027/o;}return (""+r).slice(0,16)}async function V(t,e){let r=await fetch(...t);if(!r.ok)throw new Error(`Request failed with status ${r.status}`);let o=await r.json();return e.parse(o)}var H=class{constructor(e){this.proxyApiUrl=e;}simplePrice(e){let r=new URLSearchParams(e);return V([`${this.proxyApiUrl}/proxy/coingecko/simple/price?${r}`,{method:"POST",headers:{"Content-Type":"application/json"}}],RawSimplePriceResponseSchema)}simplePriceByContractAddresses(e){let{id:r,...o}=e,n=new URLSearchParams(o);return V([`${this.proxyApiUrl}/proxy/coingecko/simple/token_price/${r}?${n}`,{method:"POST",headers:{"Content-Type":"application/json"}}],SimplePriceResponseSchema)}};var ue=getBasicCoingeckoHttp(),S,E,G=class{constructor({storage:e,proxyApiUrl:r}){D(this,S,void 0);D(this,E,void 0);oe(this,"transformSimplePriceResponse",(e,r=[VsCurrencyType.USD])=>{let o={};return Object.keys(e).forEach(n=>{let a=e[n];o[n]={},r.forEach(s=>{o[n]={[s]:{price:a?.[s],change24:a?.[`${s}_24h_change`],vol24:a?.[`${s}_24h_vol`],marketCap:a?.[`${s}_market_cap`]}};});}),o});C(this,S,e),C(this,E,r);}async getSimplePrice({coinIds:e=[],currencies:r=[VsCurrencyType.USD]}){let o,a=`getSimplePrice-${e?`${re(e)}-${r.toString()}`:`${r.toString()}`}`;if(o=l(this,S)?.get?.(a),o)return o;try{o=await te(s=>this.simplePrice({coinIds:e,currencies:r,marketCap:!0,vol24:!0,change24:!0,useCoingeckoProxy:s}));}catch{o=void 0;}return l(this,S)?.set?.(a,o),o}async getPricesByAddresses(e,r,o=VsCurrencyType.USD){let n,s=`getPricesWithMarketDataByAddresses-${`${re(e)}-${r}-${o}`}`;if(n=l(this,S)?.get?.(s),n)return n;try{n=await te(c=>this.fetchPricesByAddresses({assetPlatformId:r,tokenAddresses:e,currency:o,useCoingeckoProxy:c}));}catch{n=void 0;}return l(this,S)?.set?.(s,n),n}async fetchPricesByAddresses({assetPlatformId:e,tokenAddresses:r,currency:o=VsCurrencyType.USD,useCoingeckoProxy:n=!1}){return n?new H(l(this,E)).simplePriceByContractAddresses({id:e,contract_addresses:r,vs_currencies:[o],include_market_cap:!0,include_24hr_vol:!0,include_24hr_change:!0}):simpleTokenPrice(ue,{assetPlatformId:e,tokenAddresses:r,currencies:[o],marketCap:!0,vol24:!0,change24:!0})}async simplePrice({coinIds:e=[],currencies:r=[VsCurrencyType.USD],marketCap:o=!1,vol24:n=!1,change24:a=!1,lastUpdated:s=!1,useCoingeckoProxy:c=!1,shouldThrow:i=!0}){if(c){let p=await new H(l(this,E)).simplePrice({ids:e,vs_currencies:r,include_market_cap:o,include_24hr_vol:n,include_24hr_change:a,include_last_updated_at:s});return this.transformSimplePriceResponse(p,r)}return simplePrice(ue,{coinIds:e,currencies:r,marketCap:o,vol24:n,change24:a,lastUpdated:s,shouldThrow:i})}};S=new WeakMap,E=new WeakMap;object({date:string(),usd:record(number())});var ye=(t,e,r,o)=>({type:DetailItemType.FUNDS_RECIPIENT,label:t,amount:e,maxDecimals:r,symbol:o}),_=(t,e,r,o)=>({label:t,type:DetailItemType.CURRENCY,value:e,maxDecimals:r,symbol:o});var X=(t,e)=>({label:t,value:e,type:DetailItemType.LINK}),N=(t,e)=>({label:t,type:DetailItemType.ADDRESS,value:e});var fe=(t,e,r)=>{let o=r?.[t]?.[e??""]??{};return {priceInCurrency:o.price??void 0,marketCap:o.marketCap??void 0,vol24:o.vol24??void 0,change24:o.change24??void 0}};var j=async({addresses:t,currency:e,network:r,withScripts:o=!1,proxyApiUrl:n,storage:a})=>{let s=await f({isTestnet:!!r.isTestnet,proxyApiUrl:n}),c=new G({proxyApiUrl:n,storage:a}),i=r.pricingProviders?.coingecko.nativeTokenId,d=typeof e=="string"&&typeof i=="string"?await c.getSimplePrice({coinIds:[i],currencies:[e]}):void 0,{priceInCurrency:m,change24:h,marketCap:g,vol24:P}=fe(i??"",e,d);return (await Promise.allSettled(t.map(async y=>{let{balance:T,utxos:B,balanceUnconfirmed:A,utxosUnconfirmed:k}=await s.getUtxoBalance(y,o),b=new TokenUnit(T,r.networkToken.decimals,r.networkToken.symbol),I=m!==void 0?b.mul(m):void 0,R=b.toDisplay(),w=new TokenUnit(A,r.networkToken.decimals,r.networkToken.symbol),$=m!==void 0?w.mul(m):void 0,Be=r.networkToken.symbol;return {[y]:{[Be]:{...r.networkToken,utxos:B,utxosUnconfirmed:k,coingeckoId:i??"",type:TokenType.NATIVE,balance:b.toSubUnit(),balanceDisplayValue:R,balanceInCurrency:I?.toDisplay({fixedDp:2,asNumber:!0}),balanceCurrencyDisplayValue:I?.toDisplay({fixedDp:2}),priceInCurrency:m,marketCap:g,vol24:P,change24:h,unconfirmedBalance:w.toSubUnit(),unconfirmedBalanceDisplayValue:w.toDisplay(),unconfirmedBalanceInCurrency:$?.toDisplay({fixedDp:2,asNumber:!0}),unconfirmedBalanceCurrencyDisplayValue:$?.toDisplay({fixedDp:2})}}}}))).reduce((y,T)=>T.status==="rejected"?y:{...y,...T.value},{})};var he=async({accountIndex:t,xpub:e,isTestnet:r,walletType:o})=>{switch(o){case WalletType.Mnemonic:case WalletType.Ledger:case WalletType.Keystone:return {[NetworkVMType.BITCOIN]:getBech32AddressFromXPub(e,t,r?networks.testnet:networks.bitcoin)};case WalletType.LedgerLive:case WalletType.Seedless:{let n=Buffer.from(e,"hex");return {[NetworkVMType.BITCOIN]:getBtcAddressFromPubKey(n,r?networks.testnet:networks.bitcoin)}}default:throw rpcErrors.invalidParams(`Unsupported wallet type: ${o}`)}};var Ye=z$1.object({from:z$1.string(),to:z$1.string(),amount:z$1.number(),feeRate:z$1.number()}),xe=t=>Ye.safeParse(t);var Pe=t=>{if(!t)return !1;let e="utxos"in t,r="locked"in t,o="unlockedUnstaked"in t;return e&&!o&&!r};var z=(t,e)=>t/e;var K=new Map,be=(t,e,r,o)=>(K.set(t,{signingData:e,displayData:r}),{updateTx:({feeRate:n})=>{let a=K.get(t);if(!a)throw rpcErrors.resourceNotFound();let{signingData:s}=a;if(typeof n>"u"||n===s.data.feeRate)return a;let{account:c,data:{to:i,amount:p,balance:d}}=s,{inputs:m,outputs:h,fee:g}=createTransferTx(i,c,p,n,d.utxos,o.getNetwork());if(!m||!h)throw rpcErrors.internal("Unable to create transaction");let P={...s,data:{...s.data,fee:g,feeRate:n,gasLimit:z(g,n),inputs:m,outputs:h}},v={...a,signingData:P};return K.set(t,v),v},cleanup:()=>K.delete(t)});var Y=async({provider:t,txHash:e,onTransactionConfirmed:r,onTransactionReverted:o,requestId:n})=>{try{await t.waitForTx(e),r(e,n);}catch(a){console.error(a),o(e,n);}};var J=async(t,e)=>"txHash"in e?e.txHash:t.issueRawTx(e.signedData);var ke=async({request:t,network:e,approvalController:r,proxyApiUrl:o})=>{let{dappInfo:n,params:a}=t,{success:s,data:c,error:i}=xe(a);if(!s)return console.error("invalid params",i),{error:rpcErrors.invalidParams({message:"Transaction params are invalid",data:{cause:i}})};let d=(await j({addresses:[c.from],network:e,proxyApiUrl:o,withScripts:!0}))?.[c.from]?.[e.networkToken.symbol];if(!Pe(d))return {error:rpcErrors.internal("Balance for the source account is not available")};let m=await f({isTestnet:!!e.isTestnet,proxyApiUrl:o}),{to:h,from:g,amount:P,feeRate:v}=c,{inputs:y,outputs:T,fee:B}=createTransferTx(h,g,P,v,d.utxos,m.getNetwork());if(!y||!T)return {error:rpcErrors.internal("Unable to create transaction")};let A={title:"Approve Transaction",network:{chainId:e.chainId,name:e.chainName,logoUri:e.logoUri},details:[{title:"Transaction Details",items:[X("Website",n),N("From",g),N("To",h),_("Amount",BigInt(P),e.networkToken.decimals,e.networkToken.symbol)]}],networkFeeSelector:!0},k={type:RpcMethod.BITCOIN_SEND_TRANSACTION,account:g,data:{to:h,amount:P,fee:B,feeRate:v,gasLimit:z(B,v),inputs:y,outputs:T,balance:d}},{updateTx:b,cleanup:I}=be(t.requestId,k,A,m),R=await r.requestApproval({request:t,displayData:A,signingData:k,updateTx:b});if(I(),"error"in R)return {error:R.error};let w;try{w=await J(m,R);}catch($){return {error:rpcErrors.internal({message:"Unable to get transaction hash",data:{cause:$}})}}return Y({provider:m,txHash:w,onTransactionConfirmed:r.onTransactionConfirmed,onTransactionReverted:r.onTransactionReverted,requestId:t.requestId}),{result:w}};var et=z$1.object({txHash:z$1.string(),txHex:z$1.string().optional(),index:z$1.number(),value:z$1.number(),script:z$1.string().min(1),blockHeight:z$1.number(),confirmations:z$1.number(),confirmedTime:z$1.string().optional()}),tt=z$1.object({address:z$1.string(),value:z$1.number()}),rt=z$1.object({inputs:z$1.array(et).min(1),outputs:z$1.array(tt).min(1)}),Ie=t=>rt.safeParse(t);var Se=async({request:t,network:e,approvalController:r,proxyApiUrl:o})=>{let{dappInfo:n,params:a}=t,{success:s,data:c,error:i}=Ie(a);if(!s)return console.error("invalid params",i),{error:rpcErrors.invalidParams({message:"Transaction params are invalid",data:{cause:i}})};let p=await f({isTestnet:!!e.isTestnet,proxyApiUrl:o}),{details:d,error:m}=await at(c,p);if(m)return {error:rpcErrors.internal({message:"Transaction invalid or cannot be parsed",data:{cause:m}})};let{fee:h,fromAddress:g,outputs:P,transferTotal:v}=d,{decimals:y,symbol:T}=e.networkToken,B={title:"Approve Transaction",network:{chainId:e.chainId,name:e.chainName,logoUri:e.logoUri},details:[{title:"Transaction Details",items:[X("Website",n),N("From",g),_("Total Transferred Amount",BigInt(v),y,T)]},{title:"Recipients",items:P.map(({address:I,value:R})=>ye(I,BigInt(R),y,T))},{title:"Network Fee",items:[_("Total Fee",BigInt(h),y,T)]}],networkFeeSelector:!1},A={type:RpcMethod.BITCOIN_SIGN_TRANSACTION,account:g,data:{inputs:c.inputs,outputs:c.outputs}},k=await r.requestApproval({request:t,displayData:B,signingData:A});if("error"in k)return {error:k.error};let b;try{b=await J(p,k);}catch(I){return {error:rpcErrors.internal({message:"Unable to get transaction hash",data:{cause:I}})}}return Y({provider:p,txHash:b,onTransactionConfirmed:r.onTransactionConfirmed,onTransactionReverted:r.onTransactionReverted,requestId:t.requestId}),{result:b}},nt=t=>{let e=Array.from(new Set(t.map(({script:r})=>r)));if(e.length!==1)throw rpcErrors.invalidParams({message:`All input UTXOs must belong to a single address, found ${e.length}`});return e[0]},at=async(t,e)=>{try{let r=nt(t.inputs),o=await e.getAddressFromScript(r),n=t.outputs.filter(({address:p})=>p!==o),a=t.inputs.reduce((p,{value:d})=>p+d,0),s=t.outputs.reduce((p,{value:d})=>p+d,0),c=n.reduce((p,{value:d})=>p+d,0),i=a-s;return st(n),{error:null,details:{fromAddress:o,outputs:n,fee:i,transferTotal:c}}}catch(r){return console.error(r),{details:null,error:r instanceof Error?r:new Error(r?.toString()??"Unknown error")}}};function st(t){if(t.length<1)throw new Error("No actual output is provided, this transaction would only burn funds")}var x,U,we=class{constructor({environment:e,approvalController:r}){D(this,x,void 0);D(this,U,void 0);let{proxyApiUrl:o}=se(e);C(this,U,r),C(this,x,o);}getProvider(e){return f({isTestnet:!!e.isTestnet,proxyApiUrl:l(this,x)})}getAddress({accountIndex:e,xpub:r,isTestnet:o,walletType:n}){return he({accountIndex:e,xpub:r,isTestnet:o,walletType:n})}getBalances({addresses:e,currency:r,network:o,storage:n}){return j({addresses:e,currency:r,network:o,proxyApiUrl:l(this,x),storage:n})}getManifest(){let e=parseManifest(ie);return e.success?e.data:void 0}getNetworkFee(e){return ce({isTestnet:!!e.isTestnet,proxyApiUrl:l(this,x)})}async getTransactionHistory({address:e,network:r}){return {transactions:await le({address:e,network:r,proxyApiUrl:l(this,x)})}}getTokens(e){return Promise.resolve([])}async onRpcRequest(e,r){switch(e.method){case RpcMethod.BITCOIN_SEND_TRANSACTION:return ke({request:e,network:r,approvalController:l(this,U),proxyApiUrl:l(this,x)});case RpcMethod.BITCOIN_SIGN_TRANSACTION:return Se({request:e,network:r,approvalController:l(this,U),proxyApiUrl:l(this,x)});default:return {error:rpcErrors.methodNotSupported(`Method ${e.method} not supported`)}}}};x=new WeakMap,U=new WeakMap;
export { Be as BitcoinModule, z as calculateGasLimit };
export { we as BitcoinModule, z as calculateGasLimit };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map
{
"name": "@avalabs/bitcoin-module",
"version": "0.0.0-feat-p-dynamic-fees-ray-20241107155908",
"version": "0.0.0-feat-p-dynamic-fees-ray-20241108142637",
"main": "dist/index.cjs",

@@ -22,3 +22,3 @@ "module": "dist/index.js",

"bitcoinjs-lib": "5.2.0",
"@avalabs/vm-module-types": "0.0.0-feat-p-dynamic-fees-ray-20241107155908"
"@avalabs/vm-module-types": "0.0.0-feat-p-dynamic-fees-ray-20241108142637"
},

@@ -33,3 +33,3 @@ "devDependencies": {

"@internal/tsup-config": "0.0.1",
"@internal/utils": "0.0.0-feat-p-dynamic-fees-ray-20241107155908",
"@internal/utils": "0.0.0-feat-p-dynamic-fees-ray-20241108142637",
"eslint-config-custom": "0.0.1"

@@ -36,0 +36,0 @@ },

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc