@gardenfi/core 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @gardenfi/core
2
2
 
3
- The `@gardenfi/core` package serves as an abstraction layer over the `@catalogfi/wallets` and `@gardenfi/orderbook` packages. It provides a simple interface to perform atomic swaps.
3
+ The `@gardenfi/core` package serves as an abstraction layer over the `@catalogfi/wallets`(contains different kind of bitcoin and evm wallets) and `@gardenfi/orderbook` packages. It provides a simple interface to perform atomic swaps.
4
4
 
5
5
  ## Installation
6
6
 
@@ -21,6 +21,10 @@ For more information regarding using the library in different environments see [
21
21
 
22
22
  No extra setup is required as both `cjs` and `esm` modules are supported.
23
23
 
24
+ ### Browser
25
+
26
+ Following cases only cover vite and webpack setups. For other bundlers, please refer to their respective documentation on how to add wasm and polyfills support.
27
+
24
28
  ### Vite
25
29
 
26
30
  Install the vite plugins:
@@ -31,18 +35,18 @@ npm install vite-plugin-wasm vite-plugin-node-polyfills --save-dev
31
35
 
32
36
  and update your `vite.config.ts` as follows:
33
37
 
34
- ```
38
+ ```typescript
35
39
  import { defineConfig } from "vite";
36
40
  import wasm from "vite-plugin-wasm";
37
41
  import { nodePolyfills } from "vite-plugin-node-polyfills";
38
42
 
39
43
  export default defineConfig({
40
- plugins: [
41
- nodePolyfills(),
42
- wasm(),
43
- //other plugins
44
- ],
45
- //other settings
44
+ plugins: [
45
+ nodePolyfills(),
46
+ wasm(),
47
+ //other plugins
48
+ ],
49
+ //other settings
46
50
  });
47
51
  ```
48
52
 
@@ -50,18 +54,18 @@ export default defineConfig({
50
54
 
51
55
  If you're using webpack with a framework like next, then in your webpack config, (if you're using NextJS, this can be found in `next.config.js` ) add support for wasm as shown below:
52
56
 
53
- ```
57
+ ```typescript
54
58
  /** @type {import('next').NextConfig} */
55
59
  const nextConfig = {
56
- //other nextConfig options
57
- webpack: function (config, options) {
58
- //other webpack config options
59
- config.experiments = {
60
- ...config.experiments,
61
- asyncWebAssembly: true,
62
- };
63
- return config;
64
- },
60
+ //other nextConfig options
61
+ webpack: function (config, options) {
62
+ //other webpack config options
63
+ config.experiments = {
64
+ ...config.experiments,
65
+ asyncWebAssembly: true,
66
+ };
67
+ return config;
68
+ },
65
69
  };
66
70
  module.exports = nextConfig;
67
71
  ```
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("ethers"),c=require("@gardenfi/orderbook"),u=require("@catalogfi/utils"),S=async(e,t,r,o)=>{const i=r[e],n=r[t];if(!n)throw new Error(`No ${e} wallet found`);if(!i)throw new Error(`No ${t} wallet found`);let d;if(w(e)){const s=h.sha256(u.with0x(Buffer.from("catalog.js"+o+await n.getAddress()).toString("hex"))).slice(2);d=await i.sign(s)}else{const s=h.sha256(u.with0x(Buffer.from("catalog.js"+o+await i.getAddress()).toString("hex"))).slice(2);d=await n.sign(s)}return u.trim0x(h.sha256(u.with0x(d)))},w=e=>e==="bitcoin"||e==="bitcoin_testnet"||e==="bitcoin_regtest",m={WALLET_NOT_FOUND:e=>`${e?"from":"to"} wallet not found`,CHAIN_WALLET_NOT_FOUND:e=>`no ${e} wallet found`},p={NO_ACTION:"no actions can be performed in this state",NO_SECRET:"secret not found in order",INVALID_ACTION:(e,t)=>`can not ${e} on status: ${t}`};class _{constructor(t,r){this.order=t,this.wallets=r}get action(){return c.parseStatus(this.order)}get status(){return+`${this.order.status}${this.order.initiatorAtomicSwap.swapStatus}${this.order.followerAtomicSwap.swapStatus}`}async next(){switch(v[this.action]){case"Initiate":return await this.init();case"Redeem":return await this.redeem();case"Refund":return await this.refund();default:return L}}async init(){switch(this.action){case c.Actions.UserCanInitiate:{const t=this.wallets[this.order.initiatorAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.initiatorAtomicSwap.chain} wallet found`);return{user:"initiator",action:"Initiate",output:await(await l(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).init()}}case c.Actions.CounterpartyCanInitiate:{const t=this.wallets[this.order.followerAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.followerAtomicSwap.chain} wallet`);return{user:"redeemer",action:"Initiate",output:await(await l(t,this.order,"foreign",this.order.followerAtomicSwap.asset)).init()}}default:throw new Error(p.INVALID_ACTION("init",this.status))}}async redeem(){const t=this.getWallet(this.order.followerAtomicSwap.chain),r=this.getWallet(this.order.initiatorAtomicSwap.chain);switch(this.action){case c.Actions.UserCanRedeem:{const o=await l(t,this.order,"foreign",this.order.followerAtomicSwap.asset),i=await S(this.order.initiatorAtomicSwap.chain,this.order.followerAtomicSwap.chain,this.wallets,this.order.secretNonce);return console.log("secret when redeeming: ",i),{user:"initiator",action:"Redeem",output:await o.redeem(i,this.order.userBtcWalletAddress)}}case c.Actions.CounterpartyCanRedeem:{if(!this.order.secret)throw new Error("Secret not found in order");return{user:"redeemer",action:"Redeem",output:await(await l(r,this.order,"native",this.order.initiatorAtomicSwap.asset)).redeem(this.order.secret)}}default:throw new Error(p.INVALID_ACTION("redeem",this.status))}}async refund(){const t=this.getWallet(this.order.initiatorAtomicSwap.chain),r=this.getWallet(this.order.followerAtomicSwap.chain);if(this.order.initiatorAtomicSwap.swapStatus===3)return{user:"initiator",action:"Refund",output:await(await l(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};if(this.order.followerAtomicSwap.swapStatus===3)return{user:"redeemer",action:"Refund",output:await(await l(r,this.order,"foreign",this.order.followerAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};throw new Error(p.INVALID_ACTION("refund",this.status))}id(){throw new Error("Method not implemented.")}getWallet(t){const r=this.wallets[t];if(!r)throw new Error(`No ${t} wallet found`);return r}}const l=async(e,t,r,o)=>{console.log(r,o);const i=r==="native"?t.initiatorAtomicSwap:t.followerAtomicSwap;return e.newSwap({recipientAddress:i.redeemerAddress,refundAddress:i.initiatorAddress,initiatorAddress:i.initiatorAddress,chain:c.chainToId[i.chain],expiryBlocks:+i.timelock,secretHash:t.secretHash,amount:+i.amount,contractAddress:o})};var I=(e=>(e.INITIATOR="initiator",e.REDEEMER="redeemer",e))(I||{}),N=(e=>(e.Init="Initiate",e.Redeem="Redeem",e.Refund="Refund",e.None="None",e))(N||{});const v={[c.Actions.UserCanInitiate]:"Initiate",[c.Actions.CounterpartyCanInitiate]:"Initiate",[c.Actions.UserCanRedeem]:"Redeem",[c.Actions.CounterpartyCanRedeem]:"Redeem",[c.Actions.UserCanRefund]:"Refund",[c.Actions.CounterpartyCanRefund]:"Refund",[c.Actions.NoAction]:"None"},L={user:"initiator",action:"None",output:""};class ${constructor(t){if(t)this.extensionId=t.id;else if(x())this.extensionId=g("chrome");else if(E())this.extensionId=g("window");else throw new Error("Catalog wallet extension not found")}send(t,r){return new Promise((o,i)=>{const n={url:"",favicon:""},d=window.location.href.split("://")[1].replace(/\/$/,"");n.url=d;let s=document.querySelector("link[rel='icon']");if(s||(s=document.querySelector("link[rel='shortcut icon']")),s||(s=document.querySelector("link[rel='apple-touch-icon']")),s||(s=document.querySelector("meta[property='og:image']")),s)n.favicon=s instanceof HTMLMetaElement?s.content:s.href;else{const a=new URL(window.location.href);n.favicon=`${a.protocol}//${a.hostname}/favicon.ico`}chrome.runtime.sendMessage(this.extensionId,{method:t,params:r,metadata:n},a=>chrome.runtime.lastError?i(chrome.runtime.lastError):typeof a=="object"&&a&&"error"in a?i(a.error):o(a))})}}const E=()=>{try{const e=window;return e&&e.catalog&&e.catalog.id}catch{return!1}},g=e=>{if(e==="chrome")return chrome.runtime.id;if(e==="window")return window.catalog.id;throw new Error("Invalid medium to get wallet id")},x=()=>{try{return chrome&&!!chrome.runtime&&!!chrome.runtime.id}catch{return!1}},O={createOrderAndSwap:"createOrderAndSwap"};class D{constructor(t,r){this.orderbook=t,this.wallets=r}subscribeOrders(t,r){this.orderbook.subscribeOrders(t,r)}unsubscribeOrders(){return this.orderbook.unsubscribeOrders()}async swap(t,r,o,i,n){if(E()){const T=await new $().send(O.createOrderAndSwap,{from:t,to:r,amt:o,receiveAmount:i,opts:n});return Number(T)}const d=this.wallets[t.chain],s=this.wallets[r.chain];if(!d)throw new Error(m.WALLET_NOT_FOUND(!0));if(!s)throw new Error(m.WALLET_NOT_FOUND(!1));U(t.chain,r.chain),(n&&!n.btcInputAddress||!n)&&(n=n||{},n.btcInputAddress=await this.wallets[w(t.chain)?t.chain:r.chain].getAddress());const a=w(t.chain),A=a?s:d,f=a?d:s,W=await A.getAddress(),b=await this.orderbook.getOrders(W),R=a?await f.getAddress():await A.getAddress(),C=a?await A.getAddress():await f.getAddress(),y=await S(t.chain,r.chain,this.wallets,b.length+1);return this.orderbook.createOrder({fromAsset:t,toAsset:r,sendAmount:o.toString(),receiveAmount:i.toString(),receiveAddress:C,sendAddress:R,secretHash:h.sha256(u.with0x(y)),btcInputAddress:n.btcInputAddress??await f.getAddress()})}getSwap(t){return new _(t,this.wallets)}calculateReceiveAmt(t,r,o){return Promise.resolve(o-o*.03)}}const U=(e,t)=>{if(w(e)===w(t))throw new Error(w(e)?m.CHAIN_WALLET_NOT_FOUND("Bitcoin"):m.CHAIN_WALLET_NOT_FOUND("EVM"))};exports.GardenJS=D;exports.SwapperActions=N;exports.SwapperRole=I;exports.catalogWalletActions=O;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("ethers"),c=require("@gardenfi/orderbook"),u=require("@catalogfi/utils"),g=async(e,t,r,s)=>{const i=r[e],a=r[t];if(!a)throw new Error(`No ${e} wallet found`);if(!i)throw new Error(`No ${t} wallet found`);let d;if(w(e)){const o=h.sha256(u.with0x(Buffer.from("catalog.js"+s+await a.getAddress()).toString("hex"))).slice(2);d=await i.sign(o)}else{const o=h.sha256(u.with0x(Buffer.from("catalog.js"+s+await i.getAddress()).toString("hex"))).slice(2);d=await a.sign(o)}return u.trim0x(h.sha256(u.with0x(d)))},w=e=>e==="bitcoin"||e==="bitcoin_testnet"||e==="bitcoin_regtest",m={WALLET_NOT_FOUND:e=>`${e?"from":"to"} wallet not found`,CHAIN_WALLET_NOT_FOUND:e=>`no ${e} wallet found`},p={NO_ACTION:"no actions can be performed in this state",NO_SECRET:"secret not found in order",INVALID_ACTION:(e,t)=>`can not ${e} on status: ${t}`};class _{constructor(t,r){this.order=t,this.wallets=r}get action(){return c.parseStatus(this.order)}get status(){return+`${this.order.status}${this.order.initiatorAtomicSwap.swapStatus}${this.order.followerAtomicSwap.swapStatus}`}async next(){switch(v[this.action]){case"Initiate":return await this.init();case"Redeem":return await this.redeem();case"Refund":return await this.refund();default:return L}}async init(){switch(this.action){case c.Actions.UserCanInitiate:{const t=this.wallets[this.order.initiatorAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.initiatorAtomicSwap.chain} wallet found`);return{user:"initiator",action:"Initiate",output:await(await l(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).init()}}case c.Actions.CounterpartyCanInitiate:{const t=this.wallets[this.order.followerAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.followerAtomicSwap.chain} wallet`);return{user:"redeemer",action:"Initiate",output:await(await l(t,this.order,"foreign",this.order.followerAtomicSwap.asset)).init()}}default:throw new Error(p.INVALID_ACTION("init",this.status))}}async redeem(){const t=this.getWallet(this.order.followerAtomicSwap.chain),r=this.getWallet(this.order.initiatorAtomicSwap.chain);switch(this.action){case c.Actions.UserCanRedeem:{const s=await l(t,this.order,"foreign",this.order.followerAtomicSwap.asset),i=await g(this.order.initiatorAtomicSwap.chain,this.order.followerAtomicSwap.chain,this.wallets,this.order.secretNonce);return{user:"initiator",action:"Redeem",output:await s.redeem(i,this.order.userBtcWalletAddress)}}case c.Actions.CounterpartyCanRedeem:{if(!this.order.secret)throw new Error("Secret not found in order");return{user:"redeemer",action:"Redeem",output:await(await l(r,this.order,"native",this.order.initiatorAtomicSwap.asset)).redeem(this.order.secret)}}default:throw new Error(p.INVALID_ACTION("redeem",this.status))}}async refund(){const t=this.getWallet(this.order.initiatorAtomicSwap.chain),r=this.getWallet(this.order.followerAtomicSwap.chain);if(this.order.initiatorAtomicSwap.swapStatus===3)return{user:"initiator",action:"Refund",output:await(await l(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};if(this.order.followerAtomicSwap.swapStatus===3)return{user:"redeemer",action:"Refund",output:await(await l(r,this.order,"foreign",this.order.followerAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};throw new Error(p.INVALID_ACTION("refund",this.status))}id(){throw new Error("Method not implemented.")}getWallet(t){const r=this.wallets[t];if(!r)throw new Error(`No ${t} wallet found`);return r}}const l=async(e,t,r,s)=>{const i=r==="native"?t.initiatorAtomicSwap:t.followerAtomicSwap;return e.newSwap({recipientAddress:i.redeemerAddress,refundAddress:i.initiatorAddress,initiatorAddress:i.initiatorAddress,chain:c.chainToId[i.chain],expiryBlocks:+i.timelock,secretHash:t.secretHash,amount:+i.amount,contractAddress:s})};var I=(e=>(e.INITIATOR="initiator",e.REDEEMER="redeemer",e))(I||{}),N=(e=>(e.Init="Initiate",e.Redeem="Redeem",e.Refund="Refund",e.None="None",e))(N||{});const v={[c.Actions.UserCanInitiate]:"Initiate",[c.Actions.CounterpartyCanInitiate]:"Initiate",[c.Actions.UserCanRedeem]:"Redeem",[c.Actions.CounterpartyCanRedeem]:"Redeem",[c.Actions.UserCanRefund]:"Refund",[c.Actions.CounterpartyCanRefund]:"Refund",[c.Actions.NoAction]:"None"},L={user:"initiator",action:"None",output:""};class ${constructor(t){if(t)this.extensionId=t.id;else if(x())this.extensionId=S("chrome");else if(E())this.extensionId=S("window");else throw new Error("Catalog wallet extension not found")}send(t,r){return new Promise((s,i)=>{const a={url:"",favicon:""},d=window.location.href.split("://")[1].replace(/\/$/,"");a.url=d;let o=document.querySelector("link[rel='icon']");if(o||(o=document.querySelector("link[rel='shortcut icon']")),o||(o=document.querySelector("link[rel='apple-touch-icon']")),o||(o=document.querySelector("meta[property='og:image']")),o)a.favicon=o instanceof HTMLMetaElement?o.content:o.href;else{const n=new URL(window.location.href);a.favicon=`${n.protocol}//${n.hostname}/favicon.ico`}chrome.runtime.sendMessage(this.extensionId,{method:t,params:r,metadata:a},n=>chrome.runtime.lastError?i(chrome.runtime.lastError):typeof n=="object"&&n&&"error"in n?i(n.error):s(n))})}}const E=()=>{try{const e=window;return e&&e.catalog&&e.catalog.id}catch{return!1}},S=e=>{if(e==="chrome")return chrome.runtime.id;if(e==="window")return window.catalog.id;throw new Error("Invalid medium to get wallet id")},x=()=>{try{return chrome&&!!chrome.runtime&&!!chrome.runtime.id}catch{return!1}},O={createOrderAndSwap:"createOrderAndSwap"};class D{constructor(t,r){this.orderbook=t,this.wallets=r}subscribeOrders(t,r){this.orderbook.subscribeOrders(t,r)}unsubscribeOrders(){return this.orderbook.unsubscribeOrders()}async swap(t,r,s,i,a){if(E()){const T=await new $().send(O.createOrderAndSwap,{from:t,to:r,amt:s,receiveAmount:i,opts:a});return Number(T)}const d=this.wallets[t.chain],o=this.wallets[r.chain];if(!d)throw new Error(m.WALLET_NOT_FOUND(!0));if(!o)throw new Error(m.WALLET_NOT_FOUND(!1));U(t.chain,r.chain),(a&&!a.btcInputAddress||!a)&&(a=a||{},a.btcInputAddress=await this.wallets[w(t.chain)?t.chain:r.chain].getAddress());const n=w(t.chain),A=n?o:d,f=n?d:o,W=await A.getAddress(),b=await this.orderbook.getOrders(W),R=n?await f.getAddress():await A.getAddress(),C=n?await A.getAddress():await f.getAddress(),y=await g(t.chain,r.chain,this.wallets,b.length+1);return this.orderbook.createOrder({fromAsset:t,toAsset:r,sendAmount:s.toString(),receiveAmount:i.toString(),receiveAddress:C,sendAddress:R,secretHash:h.sha256(u.with0x(y)),btcInputAddress:a.btcInputAddress??await f.getAddress()})}getSwap(t){return new _(t,this.wallets)}calculateReceiveAmt(t,r,s){return Promise.resolve(s-s*.03)}}const U=(e,t)=>{if(w(e)===w(t))throw new Error(w(e)?m.CHAIN_WALLET_NOT_FOUND("Bitcoin"):m.CHAIN_WALLET_NOT_FOUND("EVM"))};exports.GardenJS=D;exports.SwapperActions=N;exports.SwapperRole=I;exports.catalogWalletActions=O;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{sha256 as l}from"ethers";import{Actions as c,parseStatus as L,chainToId as v}from"@gardenfi/orderbook";import{with0x as u,trim0x as W}from"@catalogfi/utils";const S=async(e,t,r,a)=>{const i=r[e],s=r[t];if(!s)throw new Error(`No ${e} wallet found`);if(!i)throw new Error(`No ${t} wallet found`);let d;if(w(e)){const o=l(u(Buffer.from("catalog.js"+a+await s.getAddress()).toString("hex"))).slice(2);d=await i.sign(o)}else{const o=l(u(Buffer.from("catalog.js"+a+await i.getAddress()).toString("hex"))).slice(2);d=await s.sign(o)}return W(l(u(d)))},w=e=>e==="bitcoin"||e==="bitcoin_testnet"||e==="bitcoin_regtest",m={WALLET_NOT_FOUND:e=>`${e?"from":"to"} wallet not found`,CHAIN_WALLET_NOT_FOUND:e=>`no ${e} wallet found`},p={NO_ACTION:"no actions can be performed in this state",NO_SECRET:"secret not found in order",INVALID_ACTION:(e,t)=>`can not ${e} on status: ${t}`};class ${constructor(t,r){this.order=t,this.wallets=r}get action(){return L(this.order)}get status(){return+`${this.order.status}${this.order.initiatorAtomicSwap.swapStatus}${this.order.followerAtomicSwap.swapStatus}`}async next(){switch(x[this.action]){case"Initiate":return await this.init();case"Redeem":return await this.redeem();case"Refund":return await this.refund();default:return U}}async init(){switch(this.action){case c.UserCanInitiate:{const t=this.wallets[this.order.initiatorAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.initiatorAtomicSwap.chain} wallet found`);return{user:"initiator",action:"Initiate",output:await(await h(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).init()}}case c.CounterpartyCanInitiate:{const t=this.wallets[this.order.followerAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.followerAtomicSwap.chain} wallet`);return{user:"redeemer",action:"Initiate",output:await(await h(t,this.order,"foreign",this.order.followerAtomicSwap.asset)).init()}}default:throw new Error(p.INVALID_ACTION("init",this.status))}}async redeem(){const t=this.getWallet(this.order.followerAtomicSwap.chain),r=this.getWallet(this.order.initiatorAtomicSwap.chain);switch(this.action){case c.UserCanRedeem:{const a=await h(t,this.order,"foreign",this.order.followerAtomicSwap.asset),i=await S(this.order.initiatorAtomicSwap.chain,this.order.followerAtomicSwap.chain,this.wallets,this.order.secretNonce);return console.log("secret when redeeming: ",i),{user:"initiator",action:"Redeem",output:await a.redeem(i,this.order.userBtcWalletAddress)}}case c.CounterpartyCanRedeem:{if(!this.order.secret)throw new Error("Secret not found in order");return{user:"redeemer",action:"Redeem",output:await(await h(r,this.order,"native",this.order.initiatorAtomicSwap.asset)).redeem(this.order.secret)}}default:throw new Error(p.INVALID_ACTION("redeem",this.status))}}async refund(){const t=this.getWallet(this.order.initiatorAtomicSwap.chain),r=this.getWallet(this.order.followerAtomicSwap.chain);if(this.order.initiatorAtomicSwap.swapStatus===3)return{user:"initiator",action:"Refund",output:await(await h(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};if(this.order.followerAtomicSwap.swapStatus===3)return{user:"redeemer",action:"Refund",output:await(await h(r,this.order,"foreign",this.order.followerAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};throw new Error(p.INVALID_ACTION("refund",this.status))}id(){throw new Error("Method not implemented.")}getWallet(t){const r=this.wallets[t];if(!r)throw new Error(`No ${t} wallet found`);return r}}const h=async(e,t,r,a)=>{console.log(r,a);const i=r==="native"?t.initiatorAtomicSwap:t.followerAtomicSwap;return e.newSwap({recipientAddress:i.redeemerAddress,refundAddress:i.initiatorAddress,initiatorAddress:i.initiatorAddress,chain:v[i.chain],expiryBlocks:+i.timelock,secretHash:t.secretHash,amount:+i.amount,contractAddress:a})};var g=(e=>(e.INITIATOR="initiator",e.REDEEMER="redeemer",e))(g||{}),I=(e=>(e.Init="Initiate",e.Redeem="Redeem",e.Refund="Refund",e.None="None",e))(I||{});const x={[c.UserCanInitiate]:"Initiate",[c.CounterpartyCanInitiate]:"Initiate",[c.UserCanRedeem]:"Redeem",[c.CounterpartyCanRedeem]:"Redeem",[c.UserCanRefund]:"Refund",[c.CounterpartyCanRefund]:"Refund",[c.NoAction]:"None"},U={user:"initiator",action:"None",output:""};class D{constructor(t){if(t)this.extensionId=t.id;else if(k())this.extensionId=E("chrome");else if(N())this.extensionId=E("window");else throw new Error("Catalog wallet extension not found")}send(t,r){return new Promise((a,i)=>{const s={url:"",favicon:""},d=window.location.href.split("://")[1].replace(/\/$/,"");s.url=d;let o=document.querySelector("link[rel='icon']");if(o||(o=document.querySelector("link[rel='shortcut icon']")),o||(o=document.querySelector("link[rel='apple-touch-icon']")),o||(o=document.querySelector("meta[property='og:image']")),o)s.favicon=o instanceof HTMLMetaElement?o.content:o.href;else{const n=new URL(window.location.href);s.favicon=`${n.protocol}//${n.hostname}/favicon.ico`}chrome.runtime.sendMessage(this.extensionId,{method:t,params:r,metadata:s},n=>chrome.runtime.lastError?i(chrome.runtime.lastError):typeof n=="object"&&n&&"error"in n?i(n.error):a(n))})}}const N=()=>{try{const e=window;return e&&e.catalog&&e.catalog.id}catch{return!1}},E=e=>{if(e==="chrome")return chrome.runtime.id;if(e==="window")return window.catalog.id;throw new Error("Invalid medium to get wallet id")},k=()=>{try{return chrome&&!!chrome.runtime&&!!chrome.runtime.id}catch{return!1}},O={createOrderAndSwap:"createOrderAndSwap"};class B{constructor(t,r){this.orderbook=t,this.wallets=r}subscribeOrders(t,r){this.orderbook.subscribeOrders(t,r)}unsubscribeOrders(){return this.orderbook.unsubscribeOrders()}async swap(t,r,a,i,s){if(N()){const y=await new D().send(O.createOrderAndSwap,{from:t,to:r,amt:a,receiveAmount:i,opts:s});return Number(y)}const d=this.wallets[t.chain],o=this.wallets[r.chain];if(!d)throw new Error(m.WALLET_NOT_FOUND(!0));if(!o)throw new Error(m.WALLET_NOT_FOUND(!1));H(t.chain,r.chain),(s&&!s.btcInputAddress||!s)&&(s=s||{},s.btcInputAddress=await this.wallets[w(t.chain)?t.chain:r.chain].getAddress());const n=w(t.chain),f=n?o:d,A=n?d:o,R=await f.getAddress(),C=await this.orderbook.getOrders(R),b=n?await A.getAddress():await f.getAddress(),_=n?await f.getAddress():await A.getAddress(),T=await S(t.chain,r.chain,this.wallets,C.length+1);return this.orderbook.createOrder({fromAsset:t,toAsset:r,sendAmount:a.toString(),receiveAmount:i.toString(),receiveAddress:_,sendAddress:b,secretHash:l(u(T)),btcInputAddress:s.btcInputAddress??await A.getAddress()})}getSwap(t){return new $(t,this.wallets)}calculateReceiveAmt(t,r,a){return Promise.resolve(a-a*.03)}}const H=(e,t)=>{if(w(e)===w(t))throw new Error(w(e)?m.CHAIN_WALLET_NOT_FOUND("Bitcoin"):m.CHAIN_WALLET_NOT_FOUND("EVM"))};export{B as GardenJS,I as SwapperActions,g as SwapperRole,O as catalogWalletActions};
1
+ import{sha256 as u}from"ethers";import{Actions as c,parseStatus as L,chainToId as v}from"@gardenfi/orderbook";import{with0x as l,trim0x as W}from"@catalogfi/utils";const S=async(e,t,r,s)=>{const i=r[e],a=r[t];if(!a)throw new Error(`No ${e} wallet found`);if(!i)throw new Error(`No ${t} wallet found`);let d;if(w(e)){const o=u(l(Buffer.from("catalog.js"+s+await a.getAddress()).toString("hex"))).slice(2);d=await i.sign(o)}else{const o=u(l(Buffer.from("catalog.js"+s+await i.getAddress()).toString("hex"))).slice(2);d=await a.sign(o)}return W(u(l(d)))},w=e=>e==="bitcoin"||e==="bitcoin_testnet"||e==="bitcoin_regtest",m={WALLET_NOT_FOUND:e=>`${e?"from":"to"} wallet not found`,CHAIN_WALLET_NOT_FOUND:e=>`no ${e} wallet found`},p={NO_ACTION:"no actions can be performed in this state",NO_SECRET:"secret not found in order",INVALID_ACTION:(e,t)=>`can not ${e} on status: ${t}`};class ${constructor(t,r){this.order=t,this.wallets=r}get action(){return L(this.order)}get status(){return+`${this.order.status}${this.order.initiatorAtomicSwap.swapStatus}${this.order.followerAtomicSwap.swapStatus}`}async next(){switch(x[this.action]){case"Initiate":return await this.init();case"Redeem":return await this.redeem();case"Refund":return await this.refund();default:return U}}async init(){switch(this.action){case c.UserCanInitiate:{const t=this.wallets[this.order.initiatorAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.initiatorAtomicSwap.chain} wallet found`);return{user:"initiator",action:"Initiate",output:await(await h(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).init()}}case c.CounterpartyCanInitiate:{const t=this.wallets[this.order.followerAtomicSwap.chain];if(!t)throw new Error(`No ${this.order.followerAtomicSwap.chain} wallet`);return{user:"redeemer",action:"Initiate",output:await(await h(t,this.order,"foreign",this.order.followerAtomicSwap.asset)).init()}}default:throw new Error(p.INVALID_ACTION("init",this.status))}}async redeem(){const t=this.getWallet(this.order.followerAtomicSwap.chain),r=this.getWallet(this.order.initiatorAtomicSwap.chain);switch(this.action){case c.UserCanRedeem:{const s=await h(t,this.order,"foreign",this.order.followerAtomicSwap.asset),i=await S(this.order.initiatorAtomicSwap.chain,this.order.followerAtomicSwap.chain,this.wallets,this.order.secretNonce);return{user:"initiator",action:"Redeem",output:await s.redeem(i,this.order.userBtcWalletAddress)}}case c.CounterpartyCanRedeem:{if(!this.order.secret)throw new Error("Secret not found in order");return{user:"redeemer",action:"Redeem",output:await(await h(r,this.order,"native",this.order.initiatorAtomicSwap.asset)).redeem(this.order.secret)}}default:throw new Error(p.INVALID_ACTION("redeem",this.status))}}async refund(){const t=this.getWallet(this.order.initiatorAtomicSwap.chain),r=this.getWallet(this.order.followerAtomicSwap.chain);if(this.order.initiatorAtomicSwap.swapStatus===3)return{user:"initiator",action:"Refund",output:await(await h(t,this.order,"native",this.order.initiatorAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};if(this.order.followerAtomicSwap.swapStatus===3)return{user:"redeemer",action:"Refund",output:await(await h(r,this.order,"foreign",this.order.followerAtomicSwap.asset)).refund(this.order.userBtcWalletAddress)};throw new Error(p.INVALID_ACTION("refund",this.status))}id(){throw new Error("Method not implemented.")}getWallet(t){const r=this.wallets[t];if(!r)throw new Error(`No ${t} wallet found`);return r}}const h=async(e,t,r,s)=>{const i=r==="native"?t.initiatorAtomicSwap:t.followerAtomicSwap;return e.newSwap({recipientAddress:i.redeemerAddress,refundAddress:i.initiatorAddress,initiatorAddress:i.initiatorAddress,chain:v[i.chain],expiryBlocks:+i.timelock,secretHash:t.secretHash,amount:+i.amount,contractAddress:s})};var g=(e=>(e.INITIATOR="initiator",e.REDEEMER="redeemer",e))(g||{}),I=(e=>(e.Init="Initiate",e.Redeem="Redeem",e.Refund="Refund",e.None="None",e))(I||{});const x={[c.UserCanInitiate]:"Initiate",[c.CounterpartyCanInitiate]:"Initiate",[c.UserCanRedeem]:"Redeem",[c.CounterpartyCanRedeem]:"Redeem",[c.UserCanRefund]:"Refund",[c.CounterpartyCanRefund]:"Refund",[c.NoAction]:"None"},U={user:"initiator",action:"None",output:""};class D{constructor(t){if(t)this.extensionId=t.id;else if(k())this.extensionId=E("chrome");else if(N())this.extensionId=E("window");else throw new Error("Catalog wallet extension not found")}send(t,r){return new Promise((s,i)=>{const a={url:"",favicon:""},d=window.location.href.split("://")[1].replace(/\/$/,"");a.url=d;let o=document.querySelector("link[rel='icon']");if(o||(o=document.querySelector("link[rel='shortcut icon']")),o||(o=document.querySelector("link[rel='apple-touch-icon']")),o||(o=document.querySelector("meta[property='og:image']")),o)a.favicon=o instanceof HTMLMetaElement?o.content:o.href;else{const n=new URL(window.location.href);a.favicon=`${n.protocol}//${n.hostname}/favicon.ico`}chrome.runtime.sendMessage(this.extensionId,{method:t,params:r,metadata:a},n=>chrome.runtime.lastError?i(chrome.runtime.lastError):typeof n=="object"&&n&&"error"in n?i(n.error):s(n))})}}const N=()=>{try{const e=window;return e&&e.catalog&&e.catalog.id}catch{return!1}},E=e=>{if(e==="chrome")return chrome.runtime.id;if(e==="window")return window.catalog.id;throw new Error("Invalid medium to get wallet id")},k=()=>{try{return chrome&&!!chrome.runtime&&!!chrome.runtime.id}catch{return!1}},O={createOrderAndSwap:"createOrderAndSwap"};class B{constructor(t,r){this.orderbook=t,this.wallets=r}subscribeOrders(t,r){this.orderbook.subscribeOrders(t,r)}unsubscribeOrders(){return this.orderbook.unsubscribeOrders()}async swap(t,r,s,i,a){if(N()){const y=await new D().send(O.createOrderAndSwap,{from:t,to:r,amt:s,receiveAmount:i,opts:a});return Number(y)}const d=this.wallets[t.chain],o=this.wallets[r.chain];if(!d)throw new Error(m.WALLET_NOT_FOUND(!0));if(!o)throw new Error(m.WALLET_NOT_FOUND(!1));H(t.chain,r.chain),(a&&!a.btcInputAddress||!a)&&(a=a||{},a.btcInputAddress=await this.wallets[w(t.chain)?t.chain:r.chain].getAddress());const n=w(t.chain),f=n?o:d,A=n?d:o,R=await f.getAddress(),C=await this.orderbook.getOrders(R),b=n?await A.getAddress():await f.getAddress(),_=n?await f.getAddress():await A.getAddress(),T=await S(t.chain,r.chain,this.wallets,C.length+1);return this.orderbook.createOrder({fromAsset:t,toAsset:r,sendAmount:s.toString(),receiveAmount:i.toString(),receiveAddress:_,sendAddress:b,secretHash:u(l(T)),btcInputAddress:a.btcInputAddress??await A.getAddress()})}getSwap(t){return new $(t,this.wallets)}calculateReceiveAmt(t,r,s){return Promise.resolve(s-s*.03)}}const H=(e,t)=>{if(w(e)===w(t))throw new Error(w(e)?m.CHAIN_WALLET_NOT_FOUND("Bitcoin"):m.CHAIN_WALLET_NOT_FOUND("EVM"))};export{B as GardenJS,I as SwapperActions,g as SwapperRole,O as catalogWalletActions};
@@ -1,3 +1,3 @@
1
- export { GardenJS } from "./lib/garden";
2
- export { SwapperActions, SwapperRole } from "./lib/swapper";
3
- export { catalogWalletActions } from "./lib/catalogActions";
1
+ export { GardenJS } from './lib/garden';
2
+ export { SwapperActions, SwapperRole } from './lib/swapper';
3
+ export { catalogWalletActions } from './lib/catalogActions';
@@ -1,9 +1,9 @@
1
1
  export declare const CatalogErrors: {
2
2
  WALLET_NOT_FOUND: (from: boolean) => string;
3
- CHAIN_WALLET_NOT_FOUND: (blockchain: 'EVM' | 'Bitcoin') => string;
3
+ CHAIN_WALLET_NOT_FOUND: (blockchain: "EVM" | "Bitcoin") => string;
4
4
  };
5
5
  export declare const SwapperErrors: {
6
6
  NO_ACTION: string;
7
7
  NO_SECRET: string;
8
- INVALID_ACTION: (action: 'init' | 'redeem' | 'refund', status: number) => string;
8
+ INVALID_ACTION: (action: "init" | "redeem" | "refund", status: number) => string;
9
9
  };
@@ -1,7 +1,7 @@
1
- import { Orders, Order, Asset } from "@gardenfi/orderbook";
2
- import type { IOrderbook } from "@gardenfi/orderbook";
3
- import { ISwapper } from "./swapper";
4
- import { IGardenJS, Wallets } from "./garden.types";
1
+ import { Orders, Order, Asset, IOrderbook } from '@gardenfi/orderbook';
2
+ import { ISwapper } from './swapper';
3
+ import { IGardenJS, Wallets } from './garden.types';
4
+
5
5
  /**
6
6
  * @class
7
7
  * @implements {ICatalogJS}
@@ -1,6 +1,7 @@
1
- import { Asset, Chain, EvmChain, Order, Orders } from "@gardenfi/orderbook";
2
- import { IBitcoinWallet, IEVMWallet } from "@catalogfi/wallets";
3
- import { ISwapper } from "./swapper";
1
+ import { Asset, Chain, EvmChain, Order, Orders } from '@gardenfi/orderbook';
2
+ import { IBitcoinWallet, IEVMWallet } from '@catalogfi/wallets';
3
+ import { ISwapper } from './swapper';
4
+
4
5
  export interface IGardenJS {
5
6
  /**
6
7
  *
@@ -1,6 +1,6 @@
1
- import { Actions, Order } from "@gardenfi/orderbook";
2
- import { Chain } from "@gardenfi/orderbook";
3
- import { IBaseWallet } from "@catalogfi/wallets";
1
+ import { Actions, Order, Chain } from '@gardenfi/orderbook';
2
+ import { IBaseWallet } from '@catalogfi/wallets';
3
+
4
4
  export interface ISwapper {
5
5
  id(): string;
6
6
  next(): Promise<SwapOutput>;
@@ -1,5 +1,6 @@
1
- import { Chain, Order } from "@gardenfi/orderbook";
2
- import { Wallet, JsonRpcProvider } from "ethers";
1
+ import { Chain, Order } from '@gardenfi/orderbook';
2
+ import { Wallet, JsonRpcProvider } from 'ethers';
3
+
3
4
  export declare const orderFactory: ({ secret, secretHash, userBtcWalletAddress, secretNonce, initiatorTimelock, followerTimelock, initiatorAmount, followerAmount, initiatorInitatorAddress, initiatorRedeemerAddress, followerInitiatorAddress, followerRedeemerAddress, initiatorChain, redeemerChain, initiatorAsset, followerAsset, }: {
4
5
  secret: string;
5
6
  secretHash: string;
@@ -1,4 +1,5 @@
1
- import { IBaseWallet } from "@catalogfi/wallets";
2
- import { Chain } from "@gardenfi/orderbook";
1
+ import { IBaseWallet } from '@catalogfi/wallets';
2
+ import { Chain } from '@gardenfi/orderbook';
3
+
3
4
  export declare const computeSecret: (fromChain: Chain, toChain: Chain, wallets: Partial<Record<Chain, IBaseWallet>>, nonce: number) => Promise<string>;
4
- export declare const isFromChainBitcoin: (chain: Chain) => boolean;
5
+ export declare const isFromChainBitcoin: (chain: Chain) => chain is "bitcoin" | "bitcoin_testnet" | "bitcoin_regtest";
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@gardenfi/core",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "dependencies": {
6
6
  "@catalogfi/utils": "^0.1.6",
7
- "@catalogfi/wallets": "^0.2.35",
8
- "@gardenfi/orderbook": "^0.1.4",
7
+ "@catalogfi/wallets": "^0.2.43",
8
+ "@gardenfi/orderbook": "^0.1.5",
9
9
  "ethers": "6.8.0"
10
10
  },
11
11
  "files": [